From 3a9dbc5ade4df8afb48b001b3ffdbfd0aa33738f Mon Sep 17 00:00:00 2001 From: Jacques-Etienne Baudoux Date: Sat, 7 Sep 2019 15:22:12 +0100 Subject: [PATCH] Ensure MQTT is connected when publishing message --- OpenSprinkler.cpp | 19 +++++++++++++++++-- main.cpp | 2 +- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/OpenSprinkler.cpp b/OpenSprinkler.cpp index f1c2b4aa..fe82859e 100644 --- a/OpenSprinkler.cpp +++ b/OpenSprinkler.cpp @@ -326,7 +326,7 @@ byte OpenSprinkler::options[] = { 8, 0, // special station auto refresh 0, // ifttt enable bits - 255, // mqtt enable bits + 0, // mqtt enable bits 0, // sensor 2 type 0, // sensor 2 option. 0: normally closed; 1: normally open. 0 // reset @@ -550,7 +550,22 @@ void OpenSprinkler::update_dev() { void OpenSprinkler::mqtt_publish(const char *topic, const char *payload) { #if defined(MQTT) && defined(OSPI) - mosquitto_publish(mqtt_client, NULL, topic, strlen(payload), payload, 0, true); + int rc = mosquitto_reconnect(mqtt_client); + if (rc != MOSQ_ERR_SUCCESS) { + DEBUG_PRINT("MQTT connection failed. Error: "); + DEBUG_PRINTLN(rc); + return; + } + rc = mosquitto_publish(mqtt_client, NULL, topic, strlen(payload), payload, 0, true); + switch(rc) { + case MOSQ_ERR_SUCCESS: + DEBUG_PRINTLN("Message pushed successfuly"); + return; + default: + DEBUG_PRINT("Unexpected error: "); + DEBUG_PRINTLN(rc); + return; + } // mqtt_client.publish(topic, payload, true); #endif } diff --git a/main.cpp b/main.cpp index e5020f83..6cc56f0b 100644 --- a/main.cpp +++ b/main.cpp @@ -1368,7 +1368,7 @@ void push_message(byte type, uint32_t lval, float fval, const char* sval) { break; } - if (os.options[OPTION_MQTT_ENABLE]&test_type) os.mqtt_publish(topic, payload); + if ((os.options[OPTION_MQTT_ENABLE]&test_type) && strlen(topic) & strlen(payload)) os.mqtt_publish(topic, payload); if (!os.options[OPTION_IFTTT_ENABLE]&test_type) return;