我正在使用一些CHIP(Think Raspberry Pi)进行项目开发,我需要将一些信息从从机无线发送回主板。我使用Paho作为我的Mqtt客户,并使用Mosquitto作为我的经纪人。我的问题是,当我按下连接到从属板上的按钮之一时,它将发送我的消息,但是当主板接收到它时,似乎是以“ b”形式接收消息。例如,如果我发送消息“ off”,则当我打印出msg.payload时,它会打印“ b'off'”。这引起了一个问题,因为这样我就无法比较消息以执行我的主板上的命令。
这是我的从板代码:
import paho.mqtt.client as paho
import CHIP_IO.GPIO as GPIO
import time
GPIO.cleanup()
GPIO.setup("XIO-P0", GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup("XIO-P2", GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
client = paho.Client()
client.connect("172.20.0.1", 1883)
print ("CONNECTED")
while True:
if (GPIO.input("XIO-P0") == False):
print ("Button P0 Pressed")
client.publish('tipup', 'flag')
time.sleep(1)
if (GPIO.input("XIO-P2") == False):
print ("Button P2 Pressed")
client.publish('tipup', 'off')
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
这是我的主板代码(经纪人)
import paho.mqtt.client as paho
import CHIP_IO.GPIO as GPIO
GPIO.cleanup()
GPIO.setup("XIO-P2", GPIO.OUT)
GPIO.output("XIO-P2", GPIO.HIGH)
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("tipup")
print("Subscribed")
def on_message(client, userdata, msg):
print ("Message Received")
print (str(msg.payload))
if (msg.payload == 'flag'):
print("Went through 'flag' if statement")
print("Turning on LED")
GPIO.output("XIO-P2", GPIO.LOW)
if (msg.payload == 'off'):
print ("Turning off LED")
GPIO.output("XIO-P2", GPIO.HIGH)
client = paho.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("172.20.0.1", 1883)
client.loop_forever()
GPIO.cleanup()
Run Code Online (Sandbox Code Playgroud)
当我在主板代码中打印str(msg.payload)时,就会发生问题。我要补充一点,这两个都可以正常编译并且可以正常运行,这只是我在弄清楚为什么没有通过on_message()中的任何if语句时注意到的一个问题。
'bXXX'表示字节。您需要在使用前将其转换为UTF-8:
msg.payload = msg.payload.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)
不过,我不确定为什么有效载荷以字节为单位。