Domotique/WifiControlSensor/MQTT.ino
2016-03-16 00:54:13 +01:00

56 lines
1.5 KiB
C++

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
Adafruit_MQTT_Client *mqtt;
Adafruit_MQTT_Publish *mqtt_temp;
Adafruit_MQTT_Publish *mqtt_pressure;
const char TEMPERATURE_FEED[] = "/feeds/temperature";
const char PRESSURE_FEED[] = "/feeds/pressure";
boolean mqttIsConfigured;
int publishMQTT(double temp, double pressure) {
if (MQTT_connect() == 0) {
Serial.println("publishing !");
mqtt_temp->publish(temp);
mqtt_pressure->publish(pressure);
}
}
int setupMQTT(char *server, char *user, char *passwd, int port) {
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
mqtt = new Adafruit_MQTT_Client(&client, server, port, user, passwd);
mqtt_temp = new Adafruit_MQTT_Publish(mqtt, TEMPERATURE_FEED);
mqtt_pressure = new Adafruit_MQTT_Publish(mqtt, PRESSURE_FEED);
return 0;
}
int MQTT_isConnected() {
return mqtt->connected();
}
// 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.
if (mqtt->connected()) {
return 0;
}
uint8_t retries = 3;
while ((ret = mqtt->connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt->connectErrorString(ret));
Serial.println("Retrying MQTT connection ...");
mqtt->disconnect();
delay(100); // wait
retries--;
if (retries == 0) {
return -1;
}
}
return 0;
}