Search code examples
pythonmqttpayload

msg.payload.split fails for mqtt in python. How to fix?


I have created an MQTT class. It does connect fine and publishes the "Online" message upon connection. However something is wrong with the on_message method, as it starts but gets stuck on splitting the payload

class mqtt_function():
    def __init__(self):
        self.mqttc = mqtt.Client()
        # MQTT settings here
        self.mqttc.loop_forever()
    def on_connect(self, client, userdata,flags, rc):
        message = "connected with rc: " + str(rc)
        self.mqttc.subscribe(self.topic, 2)
        print("subscribed to ", self.topic)
        self.mqttc.publish(self.topicStatus, "Online", 1, True)
    def on_message(self, client, obj, msg):
        print("on_message method started")
        print(msg.payload)
        info = msg.payload.split(",")
        print("message was split")

returns

subscribed to commands/home
on_message method started
b'60,1581638400'

Expectation: The msg.payload.split should have separated the payload message by commas into the list named info. However, this does not happen.


Solution

  • The issue lies with understanding the msg.payload format.

    While print(msg.payload) returns a legible text, msg.payload is not a string but ASCII code. After converting msg.payload from ASCII to a string, the .split function can be used. Here is the working conversion for the mqtt payload.

        def on_message(self, client, obj, msg):
            characters = [chr(ascii) for ascii in msg.payload] # Convert ASCII to char
            chars_joined = ''.join(characters) # Join chars to a string
            received_message = chars_joined.split(",")     # Split string by comma