Reader small image

You're reading from  Practical Python Programming for IoT

Product typeBook
Published inNov 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838982461
Edition1st Edition
Languages
Right arrow

The on_message() MQTT callback method

It's the on_message() handler at line (11) that is called whenever a new message for a subscribed topic is received by our program. The message is available through the msg parameter, which is an instance of MQTTMessage

At line (12), we access the payload property of msg and decode it into a string. We expect our data to be a JSON string (for example, { "level": 100 }), so we parse the string into a Python dictionary using json.loads() and assign the result to data. If the message payload is not valid JSON, we catch the exception and log an error:

def on_message(client, userdata, msg):                    # (11)
data = None
try:
data = json.loads(msg.payload.decode("UTF-8")) # (12)
except json.JSONDecodeError as e:
logger.error("JSON Decode Error: "
+ msg.payload.decode("UTF-8")...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Practical Python Programming for IoT
Published in: Nov 2020Publisher: PacktISBN-13: 9781838982461