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 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示