splitting up some code responsibilitiy
All checks were successful
build rgb-board / build (push) Successful in 8m23s
All checks were successful
build rgb-board / build (push) Successful in 8m23s
extending the mq Message to have a type field
This commit is contained in:
44
mqttcoms.go
Normal file
44
mqttcoms.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
MQTT "github.com/eclipse/paho.mqtt.golang"
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
Reference in New Issue
Block a user