From 96299467958aaffdbef5cb8ae780d3abeddfcaba Mon Sep 17 00:00:00 2001 From: xengineering Date: Sat, 20 Dec 2025 13:27:42 +0100 Subject: Separate MQTT logic This reduces the coupling between the MQTT-related code and everything else to a single `tx` channel of type `MQTTMessage`. This improves the code quality significantly. --- mqtt.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 mqtt.go (limited to 'mqtt.go') diff --git a/mqtt.go b/mqtt.go new file mode 100644 index 0000000..2fd4d13 --- /dev/null +++ b/mqtt.go @@ -0,0 +1,51 @@ +package main + +import ( + "log" + "time" + + mqtt "github.com/eclipse/paho.mqtt.golang" +) + +const ( + BROKER = `tcp://127.0.0.1:1883` + CLIENT_ID = `siaserver` + TOPIC_PREFIX = `sia` + QOS = byte(1) + RETAINED = true + MQTT_CONNECT_TIMEOUT = 1 * time.Second + MQTT_DISCONNECT_TIMEOUT_US = 500 + MQTT_RECONNECT_PERIOD = 2 * time.Second +) + +type MQTTMessage struct { + Topic string + Payload []byte +} + +func MQTTRun(tx chan MQTTMessage) { + opts := mqtt.NewClientOptions() + opts.AddBroker(BROKER) + opts.SetClientID(CLIENT_ID) + opts.SetCleanSession(true) + opts.SetOnConnectHandler(MQTTOnConnectHandler) + + client := mqtt.NewClient(opts) + + token := client.Connect() + + success := token.WaitTimeout(MQTT_CONNECT_TIMEOUT) + if !success { + log.Printf("Timed out after %v.", MQTT_CONNECT_TIMEOUT) + return + } + defer client.Disconnect(MQTT_DISCONNECT_TIMEOUT_US) + + for message := range tx { + client.Publish(message.Topic, QOS, RETAINED, message.Payload) + } +} + +func MQTTOnConnectHandler(c mqtt.Client) { + log.Printf("Connected to MQTT broker (%s)", BROKER) +} -- cgit v1.2.3-70-g09d2