You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
rgb-led-board/mqttcoms.go

51 lines
1.3 KiB
Go

package main
import (
"fmt"
"log"
"os"
MQTT "github.com/eclipse/paho.mqtt.golang"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
9 months ago
// contents of struct mostly don't matter for toolkit.
type incomingMessage struct {
Type string `json:"type"`
Image string `json:"image"`
}
// listens on topic for messages
func listener(mqMessages chan mqtt.Message) {
opts := setupMQTT()
client := MQTT.NewClient(opts)
topic := "home/rgbboard"
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Println(fmt.Sprintf("failed to connect to mq: %s", token.Error().Error()))
panic(token.Error())
}
log.Println("connected")
client.Subscribe(topic, 0, func(client mqtt.Client, msg mqtt.Message) {
log.Println("Receiving ", string(msg.Payload()), " on topic: ", msg.Topic())
mqMessages <- msg
})
}
// connection lost management
func onConnectionLostHandler(c MQTT.Client, reason error) {
log.Fatalf(reason.Error())
}
// setup connection to mqtt, topic to listen to, qos
func setupMQTT() *mqtt.ClientOptions {
opts := MQTT.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s:%s", os.Getenv("MQTTBROKER"), os.Getenv("MQTTPORT")))
opts.SetUsername(os.Getenv("MQTTUSER"))
opts.SetPassword(os.Getenv("MQTTPASSWORD"))
opts.SetClientID("rgbboard")
opts.SetAutoReconnect(true)
opts.SetConnectionLostHandler(onConnectionLostHandler)
return opts
}