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 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?