阅读有关订阅的MQTT主题

2024-10-01 13:35:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

  • 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)

Tags: 数据selfclientmessage主题topicondef
1条回答
网友
1楼 · 发布于 2024-10-01 13:35:28

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

在正常情况下,您要订阅,然后等待一个新消息发布,此时代理将把新消息传递给订阅者。在

如果要在订阅时接收发布到主题的最后一条消息,则需要确保消息发布时保留标志设置为true。当发布者在消息上设置此标志时,代理将存储该消息,并在新的订阅服务器连接点传递它。在

您没有包含发布者的代码,所以我不能指出要更改什么,但是paho文档应该解释:https://pypi.python.org/pypi/paho-mqtt/1.1#publishing

相关问题 更多 >