I try to connect to a MQTT broker running on an external server where I need to handle multiple different topics. The problem is, that only the last subscribed handler is called, even if the topic does not match the one passed as parameter to the Subscribe()
method.
Example: sending any content to p1/test
triggers the registrationHandler which only should listen for "P1/controller/registration". The other handlers or the DefaultPublishHandler are never called.
A simplified version of my program:
func main(){
var opts = MQTT.NewClientOptions()
opts.AddBroker(address)
opts.SetClientID("go-controller")
opts.SetDefaultPublishHandler(func(client MQTT.Client, msg MQTT.Message) {
log.Printf("topic: %s
", msg.Topic())
})
client = MQTT.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Panicln(token.Error())
}
client.Subscribe("P1/#", 0, logHandler)
client.Subscribe("P1/controller/registration", 0, registrationHandler)
}
var logHandler MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
...
log.Printf("Topic %s logged...
", msg.Topic())
}
var registrationHandler MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
...
log.Printf("Topic %s registered...
", message.Value)
}
EDIT #1
I found out that the oder of subscribing to topics matters. When I swap both subscription calls the correct handlers get called.
For paho.mqtt.python implementation one client can subscribe to multiple subscriptions one call in an Array like so
client.subscribe([("P1/#", 0),("P1/controller/registration", 0)])
It is not sensitive to the order of items in the Array. This is not related to the 'golang' language implementation but I leave it here for reference sake.