mqtt代理中的数据解析

Data parsing in mqtt broker

我有一个 python 代码,用于从 mqtt 接收数据 subscriber.The 来自 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:'