【发布时间】:2020-09-10 11:23:22
【问题描述】:
我确实发布了多条消息:
#!/usr/bin/env python3
import paho.mqtt.publish as publish
topic1 = "testtopic/topic1"
topic2 = "testtopic/topic2"
val1 = b'54.8'
val2 = b'598.45'
val3 = b'4813.9'
msgs = [(topic1, val1),
(topic1, val2),
(topic2, val3)]
publish.multiple(msgs, hostname="localhost")
订阅时
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import json
broker_url = "localhost"
broker_port = 1883
def on_connect(client, userdata, flags, rc):
print("Connected With Result Code: {}".format(rc))
def on_disconnect(client, userdata, rc):
print("Client Got Disconnected")
def on_message(client, userdata, message):
msg = json.loads(message.payload.decode())
print("Message Recieved: " + str(msg))
client = mqtt.Client()
client.connect(broker_url, broker_port)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
topic = "testtopic/#"
client.subscribe(topic, qos=0)
client.loop_forever()
我明白了
Connected With Result Code: 0
Message Recieved: 54.8
Message Recieved: 598.45
Message Recieved: 4813.9
如何将这三个值分配给单个变量(例如 value1 = 54.8、value2 = 598.45、value3 = 598.45),以便能够像进行一些计算或将其保存到文件一样使用它们。
【问题讨论】:
-
也许每次收到消息时,将其附加到列表中?
-
您可以在 JSON 中发布值,例如 {"value1": 54.8, "value2": 598.45, "value3": 598.45}
标签: python mqtt publish-subscribe