From c6249f96b09d9862f160c439ac8a97a92edb8228 Mon Sep 17 00:00:00 2001 From: xengineering Date: Sat, 20 Dec 2025 13:57:21 +0100 Subject: Implement /server/health This indicates if the Sia server is available and connected to the MQTT broker. Using the MQTT Will messages these will also be sent if the Sia server unexpectedly crashes. Using the retained flag it is ensured that freshly connected MQTT clients will receive these messages even when they missed the initial one from the Sia server. --- mqtt.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/mqtt.go b/mqtt.go index 5c1b1ad..6d01103 100644 --- a/mqtt.go +++ b/mqtt.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "log" "time" @@ -18,11 +19,19 @@ const ( MQTT_KEEPALIVE_PERIOD = 2 * time.Second ) +var ( + mqttServerHealthTopic string +) + type MQTTMessage struct { Topic string Payload []byte } +func init() { + mqttServerHealthTopic = fmt.Sprintf("%s/server/health", TOPIC_PREFIX) +} + func MQTTRun(tx chan MQTTMessage) { opts := mqtt.NewClientOptions() opts.AddBroker(BROKER) @@ -34,6 +43,7 @@ func MQTTRun(tx chan MQTTMessage) { opts.SetConnectRetry(true) opts.SetConnectTimeout(MQTT_CONNECT_TIMEOUT) opts.SetKeepAlive(MQTT_KEEPALIVE_PERIOD) + opts.SetWill(mqttServerHealthTopic, `bad`, QOS, true) client := mqtt.NewClient(opts) @@ -52,6 +62,7 @@ func MQTTRun(tx chan MQTTMessage) { func MQTTOnConnectHandler(c mqtt.Client) { log.Printf("Connected to MQTT broker (%s)", BROKER) + c.Publish(mqttServerHealthTopic, QOS, true, []byte(`good`)) } func MQTTConnectionLostHandler(c mqtt.Client, err error) { -- cgit v1.2.3-70-g09d2