#include <PubSubClient.h>
#include <ESP8266WiFi.h>
const char* ssid = “SSID”;
const char* password = “PASSWORD”;
const char* mqtt_server = “SERVER_IP”;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
int timeoutcounter = 0;
Serial.begin(9600);
WiFi.begin(ssid, password);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
while (WiFi.status() != WL_CONNECTED) {
timeoutcounter++;
delay(500);
Serial.print(“.”);
if (timeoutcounter >= 30){
Serial.println(“Failed to connect to wireless - sleeping for 5 minutes”);
delay(100);
ESP.deepSleep(300000000, WAKE_RF_DEFAULT);
delay(100);
}
}
Serial.println(“”);
Serial.println(“WiFi connected”);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(“Attempting MQTT connection…”);
// Attempt to connect
if (client.connect(“ESP8266Client”)) {
Serial.println(“connected”);
client.subscribe(“CayenneInput”);
} else {
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Sleep for 5 minutes before retrying
Serial.println(“Failed to connect to MQTT server - sleeping for 5 minutes”);
delay(100);
ESP.deepSleep(300000000, WAKE_RF_DEFAULT);
delay(100);
}
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(“Message arrived [”);
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
float t = 20.2;
float h = 30.3;
float hif = 40.4;
String mqtt_message = “temp,f=” + String(t) + “,channel=10”;
mqtt_message.toCharArray(msg, 50);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish(“arduino_1_data”, msg);
mqtt_message = “rel_hum,rel_hum=” + String(h) + “,channel=11”;
mqtt_message.toCharArray(msg, 50);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish(“arduino_1_data”, msg);
mqtt_message = “temp,f=” + String(hif) + “,channel=12”;
mqtt_message.toCharArray(msg, 50);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish(“arduino_1_data”, msg);
delay(5000);
}