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.
45 lines
1.2 KiB
Go
45 lines
1.2 KiB
Go
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
|
|
}
|