尽管订阅但未调用 MQTT handleMessage 函数

问题描述 投票:0回答:1

我正在开发一个 Go 应用程序,该应用程序订阅 MQTT 主题并使用 handleMessage 函数处理传入消息。但是,我遇到了一个问题,尽管 MQTT 客户端成功订阅了主题并接收了消息,但仍然没有调用 handleMessage 函数。

以下是相关代码片段的摘要:

if token := client.Subscribe(topic, 0, func(client mqtt.Client, msg mqtt.Message) {
    // Pass db as a parameter to handleMessage function
    handleMessage(client, msg, db)
    log.Printf("Received message on topic %s: %s\n", msg.Topic(), msg.Payload())
}); token.Wait() && token.Error() != nil {
    log.Printf("Error subscribing to MQTT topic %s: %v\n", topic, token.Error())
    return fmt.Errorf("failed to subscribe to MQTT topic %s: %w", topic, token.Error())
} else {
    log.Printf("Subscribed to MQTT topic: %s\n", topic)
}

// Definition of the handleMessage function
func handleMessage(client mqtt.Client, msg mqtt.Message, db *pg.DB) {
    // Logic to handle incoming MQTT messages
    // This function should be invoked when a message is received
    log.Printf("Handling MQTT message: %s\n", msg.Payload())
    // Additional processing logic...
}

尽管进行了正确的 MQTT 客户端初始化、订阅和与代理的连接,但在订阅主题上收到消息时,不会调用 handleMessage 函数。我已验证消息确实正在发布到该主题。

以下是我解决该问题所采取的步骤:

验证MQTT消息接收和订阅参数。 检查MQTT客户端的连接状态,确保没有连接错误。 检查了handleMessage 函数的实现以确保其正确定义和导出。 尽管做出了这些努力,我仍无法确定问题的根本原因。任何有关可能导致handleMessage函数不被调用的原因的见解或建议将不胜感激。

预先感谢您的协助!

go mqtt iot paho messagebroker
1个回答
0
投票

如果 mqtt 服务器和客户端都在同一台机器上运行,我们必须将 NoLocal 属性设置为 false。另外,我也用过

github.com/eclipse/paho.golang v0.11.0
。订阅功能对我来说非常不同。

subs := map[string]paho.SubscribeOptions{topic: {
    QoS: byte(clnt.QoS), NoLocal: false,
}}

_, err := clnt.Client.Subscribe(clnt.Context, &paho.Subscribe{
    Subscriptions: subs,
})
if err != nil {
    return err
}
clnt.Client.Router.RegisterHandler(topic, func(msg *paho.Publish) {
    props := make(map[string]string)
    for _, prop := range msg.Properties.User {
        props[prop.Key] = prop.Value
    }
    handler(msg.Payload, props)
})
© www.soinside.com 2019 - 2024. All rights reserved.