如何使用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.

douyuai8994
douyuai8994 您可能应该将其作为错误提出。客户可能应该应用所有匹配的主题,而不是在找到第一个匹配项时停止
2 年多之前 回复

1个回答



对于paho.mqtt.python实现,一个客户端可以订阅多个订阅,像这样在Array中调用</ p>
\ n

  client.subscribe([(“ P1 /#”,0),(“ P1 / controller / registration”,0)])
</ code> </ pre>

< p>它对数组中项目的顺序不敏感。 这与'golang'语言的实现无关,但我留在这里仅供参考。</ p>
</ div>

展开原文

原文

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.

duanlie3187
duanlie3187 我的错。 我正在引用[github.com/eclipse/paho.mqtt.python]。 它支持此语法,并且对顺序不敏感。
2 年多之前 回复
dqoqnmb163241
dqoqnmb163241 我确定情况并非如此。 当您访问实现(github.com/eclipse/paho.mqtt.golang/blob/master/client.go#L550)时,您会看到它只允许一个主题。
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐