我有一个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()
代码中有什么错误吗
我运行代码,你所有的问题都是
它将字节转换为前缀为
b
和类似于b'Candidate1:'
,b'Candidate2:'
的字符串你应该使用
坦白说,我不知道你为什么没看到
print(msg.topic + ' ' + str(msg.payload)
给出类似于相关问题 更多 >
编程相关推荐