[英]Data parsing in mqtt broker
我有一個 python 代碼,用於從 mqtt 訂閱者接收數據。來自 mqtt 訂閱者的消息根據收到的字符串作為字符串發送,我正在處理結果。 但是代碼每次都只針對 else 情況。
import paho.mqtt.client as mqtt
MQTT_ADDRESS = '192.168.103.5'
MQTT_USER = 'user'
MQTT_PASSWORD = '12345678'
MQTT_TOPIC = 'home/+/+'
def on_connect(client, userdata, flags, rc):
""" The callback for when the client receives a CONNACK response from the server."""
print('Connected with result code ' + str(rc))
client.subscribe(MQTT_TOPIC)
candidate1 = 0
candidate2 = 0
candidate3 = 0
total_count = 0
def on_message(client, userdata, msg):
"""The callback for when a PUBLISH message is received from the server."""
global candidate1
global candidate2
global candidate3
global total_count
print(msg.topic + ' ' + str(msg.payload))
msg1 = "Candidate1:"
print(msg1)
rx_msg = str(msg.payload)
print(rx_msg)
msg2 = "Candidate2:"
print(msg2)
total_count = total_count + 1
f_total = open("total_count.txt","w")
f_total.write(str(total_count))
f_total.close()
if msg1 == rx_msg:
candidate1 = candidate1+1
f_c1 = open("candidate1.txt","w")
f_c1.write(str(candidate1))
f_c1.close()
elif msg2 == rx_msg:
candidate2 = candidate2+1
f_c2 = open("candidate2.txt","w")
f_c2.write(str(candidate2))
f_c2.close()
else:
candidate3 = candidate3+1
f_c3 = open("candidate3.txt","w")
f_c3.write(str(candidate3))
f_c3.close()
def parse_message(msg):
"""This callback parses input is received"""
def main():
mqtt_client = mqtt.Client()
mqtt_client.username_pw_set(MQTT_USER, MQTT_PASSWORD)
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.connect(MQTT_ADDRESS, 1883)
mqtt_client.loop_forever()
if __name__ == '__main__':
print('MQTT to InfluxDB bridge')
main()
代碼有什么問題嗎?
我運行代碼,你的所有問題都是
str(msg.payload)
它將字節轉換為帶有前綴b
和' '
字符串,例如b'Candidate1:'
, b'Candidate2:'
你應該使用
msg.payload.decode()
坦率地說,我不知道你為什么沒有看到print(msg.topic + ' ' + str(msg.payload)
給出類似的東西
home/x/x b'Candidate1:'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.