[英]How to send a message containing different data types over mqtt?
I am trying to send a message to the broker over a websocket.我正在尝试通过 websocket 向代理发送消息。 The message contains numbers that represent sensor data, so the message can be a mix of integers and floats.
该消息包含代表传感器数据的数字,因此该消息可以是整数和浮点数的混合。 When I run the code I get
TypeError: payload must be a string, bytearray, int, float or None.
当我运行代码时,我得到
TypeError: payload must be a string, bytearray, int, float or None.
How can the code be changed to send a message containing integers and floats?如何更改代码以发送包含整数和浮点数的消息? I am using CloudMQTT as a broker.
我使用 CloudMQTT 作为代理。
Full code:完整代码:
import paho.mqtt.client as mqtt
import time
client = mqtt.Client()
client.username_pw_set("User", "Password")
client.connect("Server", "Port")
num_one = 5.83
num_two = -12.46
num_three = 2
message = (num_one, num_two, num_three)
while True:
client.publish("topic", message)
time.sleep(1)
It looks like your problem is that the message you're sending is a tuple.看起来您的问题是您发送的消息是一个元组。 You probably want
你可能想要
message = (num_one, num_two, num_three)
message = ''.join([str(x) for x in message])
This will convert each number to a string, then join them to a single string.这会将每个数字转换为字符串,然后将它们连接为单个字符串。
Choose an appropriate binary or text based format for your message, and encode your structure in that format.为您的消息选择适当的二进制或基于文本的格式,并以该格式对您的结构进行编码。 It will then either be a bytearray or string.
然后它将是一个字节数组或字符串。
Unless there's a good reason to roll your own format, I'd suggest SenML as it is barely more complex than most non-standard JSON formats, but is sufficiently standardised you can at least say you're trying to be compatible with other applications.除非有充分的理由使用自己的格式,否则我建议使用SenML,因为它比大多数非标准 JSON 格式稍微复杂一点,但已经足够标准化,您至少可以说您正在尝试与其他应用程序兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.