阅读关于订阅的 MQTT 主题

Posted

技术标签:

【中文标题】阅读关于订阅的 MQTT 主题【英文标题】:Read MQTT topic on subscribing 【发布时间】:2017-07-03 14:13:44 【问题描述】:

目前,我正在尝试使用 MQTT、Python 和 OpenHab 制作一个简单的应用程序。所以,我只想连接到 MQTT 服务器,订阅主题并读取放置在那里的数据/消息。一切正常,但有“限制”。 Python 客户端能够连接到 MQTT、订阅和... BOOM!没有!我能够从订阅的主题中读取消息,但我需要在客户端连接后更新主题。客户端连接后如果不重新更新主题数据,即使有真实数据我也看不到任何东西。 所以,简而言之

Python 客户端 (paho MQTT 1.3v) 连接到 MQTT (mosquitto) 服务器 订阅指定主题(想在此处查看当前主题数据) 在有人重新更新主题之前,什么都不会发生。

如何在不重新更新主题的情况下读取主题数据?

这是我的代码 MQTTBroker 类(对象):

def __init__(self, Trigger, ipAddress, userName, password, fileNameTopic, volumeTopic, enabledTopic):
    self.ipaddress = ipAddress
    self.username = userName
    self.password = password
    self.topic = topic
    self.fileNameTopic = fileNameTopic
    self.volumeTopic = volumeTopic
    self.enabledTopic = enabledTopic
    self.state = 0
    self.client = mqtt.Client()
    self.client.on_connect = self.on_connect
    self.client.on_message = self.on_message
    self.logger = logging.getLogger(__name__)
    self.client.enable_logger(logger)

    self.client.connect(self.ipaddress, 1883, 60)
    self.client.loop_start()

def __exit__(self, exc_type, exc_val, exc_tb):
    self.client.loop_stop()

# The callback for when the client receives a CONNACK response from the server.
def on_connect(self, client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    self.client.subscribe(self.fileNameTopic, 0)
    self.client.subscribe(self.volumeTopic, 0)
    self.client.subscribe(self.enabledTopic, 0)

# The callback for when a PUBLISH message is received from the server.
def on_message(self, client, userdata, msg):
    self.state = msg.payload
    if msg.topic == self.fileNameTopic:
        Trigger.change_file_name(msg.payload)
    elif msg.topic == self.volumeTopic:
        Trigger.change_volume(msg.payload)
    elif msg.topic == self.enabledTopic:
        Trigger.change_state(msg.payload)

【问题讨论】:

【参考方案1】:

MQTT 不是这样工作的,消息不是从主题中“读取”的。

一般情况下你订阅,然后等到有新消息发布,此时broker会将新消息传递给订阅者。

如果您想在订阅时收到发布到主题的最后一条消息,那么您需要确保在发布消息时将保留标志设置为 true。当(由发布者)在消息上设置此标志时,代理将存储该消息并在新订阅者连接时将其传递。

您尚未包含发布者的代码,因此我无法指出要更改的内容,但 paho 文档应该解释:https://pypi.python.org/pypi/paho-mqtt/1.1#publishing

【讨论】:

以上是关于阅读关于订阅的 MQTT 主题的主要内容,如果未能解决你的问题,请参考以下文章

关于MQTTHTTPWebService

如何使用 NodeJS mqtt、emqx 订阅所有主题/消息

2019-07-10-mqtt-mosquitto系列13之共享主题

2019-07-10-mqtt-mosquitto系列13之共享主题

2019-07-10-mqtt-mosquitto系列13之共享主题

Linux编程MQTT实现主题发布订阅