From a286da68d2ce0b6d9c8fc959effe260fcc31cfcf Mon Sep 17 00:00:00 2001 From: Anton Piatek Date: Sat, 10 Feb 2018 14:04:13 +0000 Subject: [PATCH] publish status topic, clear with will --- sample_config.h | 1 + wemos_temp.ino | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/sample_config.h b/sample_config.h index e20a232..5f51483 100644 --- a/sample_config.h +++ b/sample_config.h @@ -10,6 +10,7 @@ // broker password or blank #define BROKER_PASS "" // base topic to publish on (will append "//temp") +// status (1 or 0) published as will to topic (TOPIC_ROOT//status) #define TOPIC_ROOT "Devices" // override default timeout from PubSubClient lib #define MQTT_KEEPALIVE 60 diff --git a/wemos_temp.ino b/wemos_temp.ino index 97ebdda..4610481 100644 --- a/wemos_temp.ino +++ b/wemos_temp.ino @@ -52,6 +52,7 @@ WiFiClient espClient; PubSubClient client(espClient); String clientId; String topic; +String willTopic; void wait10(){ for(int i=0; i<10; i++){ @@ -72,7 +73,8 @@ void setup(void) WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASS); topic = String(TOPIC_ROOT)+"/"+WiFi.macAddress()+"/temp"; - Serial.print("TOPIC: "+topic); + willTopic = String(TOPIC_ROOT)+"/"+WiFi.macAddress()+"/status"; + Serial.println("TOPIC: "+topic); //set mqtt clientId = WiFi.macAddress(); @@ -117,8 +119,9 @@ void checkComms(){ Serial.print("MQTT connecting..."); while (!client.connected()) { Serial.print("."); - if (client.connect(clientId.c_str(), "use-token-auth", BROKER_PASS)) { + if (client.connect(clientId.c_str(), "use-token-auth", BROKER_PASS, willTopic.c_str(), 0, 1, "0")) { Serial.println("connected"); + client.publish (willTopic.c_str(), "1", true); }else { Serial.print("failed, rc="); Serial.println(client.state()); @@ -139,7 +142,7 @@ void loop(void) Serial.println("C"); //TODO something with boolean RC - client.publish (topic.c_str(), String(tempC,2).c_str(), false); + client.publish (topic.c_str(), String(tempC,2).c_str(), true); //TODO #def - also how much does this affect an accurate reading