I currently have Go code that subscribes to a topic and prints out sensor data. The part that prints out the sensor data is in a Goroutine, however, nothing is printing out currently. This is my code:
package main
import (
"fmt"
MQTT "github.com/eclipse/paho.mqtt.golang"
"os"
"os/signal"
"syscall"
"sync"
)
var wg sync.WaitGroup
func subscriber(client MQTT.Client, message MQTT.Message) {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Printf("%s
", message.Payload())
}()
}
func main() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
opts := MQTT.NewClientOptions().AddBroker("tcp://test.mosquitto.org:1883")
//opts.SetDefaultPublishHandler(f)
// Topic to subscribe to for sensor data
topic := "sensor/data"
client := MQTT.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
} else {
fmt.Printf("Connected to server
")
}
opts.OnConnect = func(c MQTT.Client) {
//if token := c.Subscribe(topic, 0, f); token.Wait() && token.Error() != nil {
if token := c.Subscribe(topic, 0, subscriber); token.Wait() && token.Error() != nil {
panic(token.Error())
}
}
wg.Wait()
<-c
}
I'm wondering if it has to do with the way I coded the sync.WaitGroup? Any ideas are appreciated.