Skip to content

Commit

Permalink
Ensure MQTT is connected when publishing message
Browse files Browse the repository at this point in the history
  • Loading branch information
jbaudoux committed Sep 7, 2019
1 parent 10a828b commit 3a9dbc5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
19 changes: 17 additions & 2 deletions OpenSprinkler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down

0 comments on commit 3a9dbc5

Please sign in to comment.