目前,我正在嘗試使用MQTT,Python和OpenHab來製作一個簡單的應用程序。所以,我只想連接到MQTT服務器,訂閱主題並閱讀放置在那裏的數據/消息。 Everthing工作正常,但有「限制」。 Python客戶端能夠連接到MQTT,訂閱和... BOOM!沒有!我能夠從訂閱的主題中讀取消息,但是我需要在客戶端連接後更新主題。客戶端連接後,如果沒有重新更新主題數據,即使存在真實數據,我也無法看到任何內容。 因此,在短暫的閱讀關於訂閱的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)