diff --git a/src/lib/mqtt.cpp b/src/lib/mqtt.cpp index 185a7f5..70ecac3 100644 --- a/src/lib/mqtt.cpp +++ b/src/lib/mqtt.cpp @@ -5,18 +5,39 @@ TaskHandle_t mqttTaskHandle = NULL; WiFiClient wifiClient; PubSubClient client(wifiClient); +// avoid circular deps, just forward declare externs used here. +bool hasLightLevel(); +float getLightLevel(); +String getMyHostname(); + void onMqttCallback(char* topic, byte* payload, unsigned int length) { Serial.println("MQTT message arrived"); } +const String getDeviceTopic() +{ + const String hostname = getMyHostname(); + const String rootTopic = preferences.getString("mqttRootTopic", DEFAULT_MQTT_ROOTTOPIC); + String fullTopic = rootTopic; + if (!rootTopic.endsWith("/") && rootTopic != "") + { + fullTopic += "/"; + } + fullTopic += hostname + "/"; + return String(fullTopic); +} + boolean connectMqtt() { - boolean result = client.connect("btclockClient"); + const String willTopic = getDeviceTopic() + "status"; + boolean result = client.connect("btclockClient", willTopic.c_str(), 0, true, "offline"); if (!result) { Serial.println("[MQTT] could not connect"); + return result; } + publish("status", "online", true); return result; } @@ -43,11 +64,6 @@ void setupMqtt() connectMqtt(); } -// avoid circular deps, just forward declare externs used here. -bool hasLightLevel(); -float getLightLevel(); -String getMyHostname(); - void mqttTask(void *pvParameters) { int t=0; @@ -74,6 +90,7 @@ void mqttTask(void *pvParameters) int8_t rssi = WiFi.RSSI(); std::string rssi_s = std::to_string(static_cast(rssi)); publish("wifi/rssi", rssi_s.c_str()); + publish("wifi/bssid", WiFi.BSSIDstr().c_str()); } std::string heap_free_s = std::to_string(static_cast(ESP.getFreeHeap())); publish("mem/heap_free", heap_free_s.c_str()); @@ -89,6 +106,11 @@ void setupMqttTask() } void publish(const char *topic, const char *value) +{ + publish(topic, value, false); +} + +void publish(const char *topic, const char *value, boolean retain) { if (!client.connected()) { @@ -96,16 +118,9 @@ void publish(const char *topic, const char *value) return; } - const String hostname = getMyHostname(); - const String rootTopic = preferences.getString("mqttRootTopic", DEFAULT_MQTT_ROOTTOPIC); - String fullTopic = rootTopic; - if (!rootTopic.endsWith("/") && rootTopic != "") - { - fullTopic += "/"; - } - fullTopic += hostname + "/" + topic; + const String fullTopic = getDeviceTopic() + topic; - if (!client.publish(fullTopic.c_str(), value)) + if (!client.publish(fullTopic.c_str(), value, retain)) { Serial.println("[MQTT] could not write"); } diff --git a/src/lib/mqtt.hpp b/src/lib/mqtt.hpp index 229d54b..d00d4ad 100644 --- a/src/lib/mqtt.hpp +++ b/src/lib/mqtt.hpp @@ -6,4 +6,5 @@ void setupMqtt(); void setupMqttTask(); -void publish(const char *key, const char *value); +void publish(const char *topic, const char *value); +void publish(const char *topic, const char *value, boolean retain);