Subscribing MQTT using Goroutine not printing messages


Subscribing MQTT using Goroutine not printing messages



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("%sn", 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 servern")
}
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.





I believe you'll need to send your goroutine the message in order for this to work. go func(msg MQTT.Message) { fmt.Println(msg.Payload) }(message)
– Fishdigger
2 days ago



go func(msg MQTT.Message) { fmt.Println(msg.Payload) }(message)





@Fishdigger That doesn't seem to work. message is already passed into the function as a parameter.
– Melissa
2 days ago


message




1 Answer
1



I managed to fix it Here is my new code:


var wg sync.WaitGroup
// All messages are handled here - printing published messages and publishing new messages
var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {

wg.Add(1)
go func() {
defer wg.Done()
fmt.Printf("%sn", msg.Payload())
}()

}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Possible Unhandled Promise Rejection (id: 0): ReferenceError: user is not defined ReferenceError: user is not defined

Opening a url is failing in Swift