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")...