現在、MQTT、Python、およびOpenHabを使用して簡単なアプリケーションを作成しようとしています。ですから、MQTTサーバーに接続し、トピックにサブスクライブし、そこに配置されたデータ/メッセージを読み取るだけです。何でもうまくいくが、「限界」がある。 PythonクライアントはMQTTに接続し、購読して...ブーム!何もない!購読されたトピックからメッセージを読むことはできますが、クライアント接続後にトピックを更新する必要があります。クライアント接続後にトピックデータを再更新しなければ、実際のデータがあっても何も見ることができません。 ので、簡単なサブスクリプションでMQTTトピックを読む
- Pythonクライアントに(PAHO MQTT 1.3V)は、MQTT(mosquitto)サーバー誰かがするまで、何も起こりません指定したトピックへ
- 購読(ここでは、現在のトピックのデータを見たい)
- に接続しますトピックを再更新してください。
どのようにしてトピックデータを再更新せずに読むことができますか?
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)