3
我正在使用一些C.H.I.P.s(Think Raspberry Pi)的項目,我需要從一個從設備無線發送一些信息回主板。我使用Paho作爲我的Mqtt客戶端,並使用Mosquitto作爲我的經紀人。我的問題是,當我按下連接到從板的其中一個按鈕時,它會發送我的信息,但當主板接收到它時,似乎以「b」'「形式得到它。例如,如果我發送消息「關閉」,當我打印出msg.payload時,它會打印「b'off'」。這是造成問題的原因,因爲那時我無法比較消息,以便從我的主控板上執行命令。Python-爲什麼我的Paho Mqtt消息與我發送時不同?
這是我的備用板代碼:
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)
,這裏是我的主板代碼(代理)
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()
,當我在我的主拷貝STR(msg.payload)時出現的問題板代碼。我應該補充說,這兩種編譯都很好,並且運行良好,這只是我注意到的一個問題,當我弄清楚爲什麼它沒有通過on_message()中的if語句之一。
首先,您需要在slave板代碼中的while循環中添加'client.loop()'。如果您使用mosquitto_sub查看正在發佈的內容,會發生什麼情況? – hardillb
@hardillb:我可以回答這個問題,因爲我有**完全相同的問題。我所有的消息有效載荷都被封裝在'b''和'''(例如'b'msg'')中。但是,當使用mosquitto_sub來查看正在發佈的內容時,它只是'msg',所以這與paho-mqtt有關。 – user128216