【发布时间】: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"收到的消息,目前它没有打印。我不确定到底是什么问题。 -
基于意见,如果可能的话,我不会动态订阅/取消订阅主题。我会一直保持连接,我会将新消息与当前状态进行比较并执行所需的操作(重新排队、处理、转发等)