2016-03-14 01:47:43 +01:00
|
|
|
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
|
|
|
|
WiFiClient client;
|
|
|
|
Adafruit_MQTT_Client *mqtt;
|
|
|
|
Adafruit_MQTT_Publish *mqtt_temp;
|
|
|
|
|
|
|
|
const char TEMPERATURE_FEED[] = "/feeds/temperature";
|
|
|
|
|
|
|
|
boolean mqttIsConfigured;
|
|
|
|
|
|
|
|
int publishMQTT(int temp) {
|
|
|
|
if (MQTT_connect() == 0) {
|
|
|
|
Serial.println("publishing !");
|
|
|
|
mqtt_temp->publish(temp);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int setupMQTT(char *server, char *user, char *passwd) {
|
|
|
|
|
|
|
|
if(server == ""){
|
|
|
|
Serial.println("Mqtt Server not configured");
|
|
|
|
}
|
|
|
|
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
|
|
|
|
mqtt = new Adafruit_MQTT_Client(&client, server, 1883, user, passwd);
|
|
|
|
mqtt_temp = new Adafruit_MQTT_Publish(mqtt, TEMPERATURE_FEED);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2016-03-11 01:31:03 +01:00
|
|
|
// Function to connect and reconnect as necessary to the MQTT server.
|
|
|
|
// Should be called in the loop function and it will take care if connecting.
|
|
|
|
int MQTT_connect() {
|
|
|
|
int8_t ret;
|
|
|
|
|
|
|
|
// Stop if already connected.
|
2016-03-14 01:47:43 +01:00
|
|
|
if (mqtt->connected()) {
|
2016-03-11 01:31:03 +01:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
uint8_t retries = 3;
|
2016-03-14 01:47:43 +01:00
|
|
|
while ((ret = mqtt->connect()) != 0) { // connect will return 0 for connected
|
|
|
|
Serial.println(mqtt->connectErrorString(ret));
|
2016-03-11 01:31:03 +01:00
|
|
|
Serial.println("Retrying MQTT connection ...");
|
2016-03-14 01:47:43 +01:00
|
|
|
mqtt->disconnect();
|
2016-03-11 01:31:03 +01:00
|
|
|
delay(100); // wait
|
|
|
|
retries--;
|
|
|
|
if (retries == 0) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|