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 }