Domotique/WifiControlSensor/MQTT.ino

78 lines
2.0 KiB
Arduino
Raw Normal View History

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;
2016-03-16 00:54:13 +01:00
Adafruit_MQTT_Publish *mqtt_pressure;
2016-03-14 01:47:43 +01:00
2016-03-21 00:56:27 +01:00
Adafruit_MQTT_Subscribe *pumpButton;
2016-03-14 01:47:43 +01:00
const char TEMPERATURE_FEED[] = "/feeds/temperature";
2016-03-16 00:54:13 +01:00
const char PRESSURE_FEED[] = "/feeds/pressure";
2016-03-14 01:47:43 +01:00
2016-03-21 00:56:27 +01:00
const char PUMP_CMD[] = "/feeds/pump/set";
boolean mqttIsConfigured = false;
2016-03-14 01:47:43 +01:00
2016-03-16 00:54:13 +01:00
int publishMQTT(double temp, double pressure) {
2016-03-14 01:47:43 +01:00
if (MQTT_connect() == 0) {
Serial.println("publishing !");
mqtt_temp->publish(temp);
2016-03-16 00:54:13 +01:00
mqtt_pressure->publish(pressure);
2016-03-14 01:47:43 +01:00
}
2016-03-21 00:56:27 +01:00
return 0;
}
char *mqttGetSubData() {
return (char *)pumpButton->lastread;
}
Adafruit_MQTT_Subscribe *subscription;
bool mqttSubAvailable() {
if (MQTT_connect() == 0) {
subscription = mqtt->readSubscription(0);
if (subscription == pumpButton) {
return true;
}
}
return false;
2016-03-14 01:47:43 +01:00
}
2016-03-14 17:18:36 +01:00
int setupMQTT(char *server, char *user, char *passwd, int port) {
2016-03-14 01:47:43 +01:00
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
2016-03-14 17:18:36 +01:00
mqtt = new Adafruit_MQTT_Client(&client, server, port, user, passwd);
2016-03-14 01:47:43 +01:00
mqtt_temp = new Adafruit_MQTT_Publish(mqtt, TEMPERATURE_FEED);
2016-03-16 00:54:13 +01:00
mqtt_pressure = new Adafruit_MQTT_Publish(mqtt, PRESSURE_FEED);
2016-03-21 00:56:27 +01:00
pumpButton = new Adafruit_MQTT_Subscribe(mqtt, PUMP_CMD);
2016-03-14 01:47:43 +01:00
2016-03-21 00:56:27 +01:00
mqtt->subscribe(pumpButton);
2016-03-14 01:47:43 +01:00
return 0;
}
2016-03-16 00:54:13 +01:00
int MQTT_isConnected() {
2016-03-14 18:05:14 +01:00
return mqtt->connected();
}
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;
}