diff options
| author | xengineering <me@xengineering.eu> | 2025-12-20 13:57:21 +0100 |
|---|---|---|
| committer | xengineering <me@xengineering.eu> | 2025-12-20 13:57:21 +0100 |
| commit | c6249f96b09d9862f160c439ac8a97a92edb8228 (patch) | |
| tree | 04f84a98d62e09089cadb9f1ae3e1ecc69002232 /mqtt.go | |
| parent | 576e1bf2300e7a324713710871d9bcd5424ff286 (diff) | |
| download | sia-server-c6249f96b09d9862f160c439ac8a97a92edb8228.tar sia-server-c6249f96b09d9862f160c439ac8a97a92edb8228.tar.zst sia-server-c6249f96b09d9862f160c439ac8a97a92edb8228.zip | |
Implement <prefix>/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.
Diffstat (limited to 'mqtt.go')
| -rw-r--r-- | mqtt.go | 11 |
1 files changed, 11 insertions, 0 deletions
@@ -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) { |
