I am working on a project using some C.H.I.P.s (Think Raspberry Pi) where I need to wirelessly send some information from a slave back to a master board. I am using Paho as my Mqtt client, and am using Mosquitto as my broker. My problem is when I push one of the buttons connected to the slave board, it sends my message, but when the master board receives it, it seems to be getting it in the form "b''". For example if I send the message "off", when I print out msg.payload it prints "b'off'". This is causing a problem because then I can not compare the message in order to do commands off of my master board.
Here is my Slave Board Code:
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)
And here is my Master Board Code (Broker)
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()
The problem happens when I print str(msg.payload) in my Master board code. I should add that both of these compile fine and run fine, it just is an issue that I noticed when I was figuring out why it wasn't going through either of the if statements that I have in on_message().
'bXXX'
means bytes. You need to convert this to UTF-8 before using it:
msg.payload = msg.payload.decode("utf-8")
I'm not sure why the payload is in bytes, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With