Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing a received message using paho mqtt in python

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("/leds/pi")

def on_message(client, userdata, msg):
    if msg.topic == '/leds/pi':
        print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost", 1883, 60)
client.loop_start()

I use this basic code to subscribe to a topic and receive a message. The on_message function gets called whenever a message is received. I need to be able to access the msg.payload outside the function and store it to a variable. The value in the variable should be updated whenever a message is received. I tried to store the msg.payload to a Global variable inside the function and access it but, that gave an error saying that the variable is not defined. Please help.

like image 641
Swishonary Avatar asked Nov 07 '25 08:11

Swishonary


1 Answers

I need to be able to access the msg.payload outside the function and store it to a variable.

You need a global variable like:

myGlobalMessagePayload = ''   #HERE!

def on_message(client, userdata, msg):
    global myGlobalMessagePayload
    if msg.topic == '/leds/pi':
        myGlobalMessagePayload  = msg.payload   #HERE!
        print(msg.topic+" "+str(msg.payload))
like image 128
ΦXocę 웃 Пepeúpa ツ Avatar answered Nov 09 '25 02:11

ΦXocę 웃 Пepeúpa ツ