dppfxf909679 2018-05-22 13:33
浏览 1220

如何使用paho.mqtt.golang库订阅多个MQTT主题?

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.

  • 写回答

1条回答 默认 最新

  • dongmu1951 2018-05-22 14:04
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器