【问题标题】:Change subscribing topic during program MQTT在程序 MQTT 期间更改订阅主题
【发布时间】:2018-07-26 01:22:33
【问题描述】:

我有一个订阅主题 "info" 的 MQTT Go 程序,我在其中收到一条 JSON 消息。我验证那个 JSON 消息,如果验证成功,我想开始订阅一个新主题 "info_updates"。这是我的订阅代码:

func Info(){
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)

    opts := MQTT.NewClientOptions().AddBroker("tcp://test.mosquitto.org:1883")

    opts.SetDefaultPublishHandler(f)
    topic := "info" //I want to be able to change this later to "info_updates"

    opts.OnConnect = func(c MQTT.Client) {
        if token := c.Subscribe(topic, 0, f); token.Wait() && token.Error() != nil {
            panic(token.Error())
        }
    }
    // Creating new client
    client := MQTT.NewClient(opts)
    if token := client.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
    } else {
        fmt.Printf("Connected to server\n")
    }
    <-c

}

这是我验证 JSON 的代码(部分):

var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
var integrationResult string

        if JSONValidate(msg.Payload())[0] == ""{ //sanity check = successful
         integrationResult = "successful"
        }else{ //sanity check = unsuccessful
        integrationResult = "unsuccessful"
        }

//do something here to tell the first function to change subscribing topic if integrationResult = "successful"

}

注意: func Info()MQTT.MessageHandler 位于两个单独的文件中。我不知道如何与func Info() 交流以更改主题订阅。谢谢你。

【问题讨论】:

  • 你为什么不在你的 MessageHandler 函数中做 client.Subscribe(newTopic,...) 呢?我也很好奇它是否有效。
  • @atayenel 这会停止订阅"info" 并仅订阅来自"info_updates" 的消息吗?我仍然可以试一试。
  • 我真的不知道,所以我很好奇。
  • @atayenel 好的,所以我做了if integrationResult == "unsuccessful"{ client.Subscribe("data_update/" + deviceID, 0, g) },其中g 是一个新的messagerHandler。在新的处理程序中,我打印出从"info_updates" 收到的消息,目前它没有打印。我不确定到底是什么问题。
  • 基于意见,如果可能的话,我不会动态订阅/取消订阅主题。我会一直保持连接,我会将新消息与当前状态进行比较并执行所需的操作(重新排队、处理、转发等)

标签: go mqtt


【解决方案1】:

在我的message.Handler 中,我这样做了:

if integrationResult == "unsuccessful"{
        client.Subscribe("data_update/" + deviceID, 0, g)
    }

其中g 是一个新的message.Handler。使用这种方法,我不确定第一个连接(订阅info)是否断开,或者两个连接是否都打开。但是,如果您只是想从新主题中获取消息,这是一个不错的方法。

【讨论】:

    猜你喜欢
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多