python - paho.mqtt - getting msg.payload to be printed outside of on_message function -
i have below simple code. i'd able print var form on_message outside of it, if put print(msg.payload) outside of loop doesn't work, loop_forever initializes function on_message, having print(msg.payload) within loop doesn't work neither (as function not initialized.
mybuffer = '' def on_subscribe(client, userdata, mid, granted_qos): print('subscribed') def on_message(client, userdata, msg): mybuffer = str(msg.payload) print('on_message: '+ mybuffer) client = paho.client() client.on_subscribe = on_subscribe client.on_message = on_message client.connect('broker', 1883) client.subscribe('/andrzej/sensorki') client.loop_forever() print(mybuffer)
there 2 problems code (which ralight , hardlib have alluded to). first, program never exits loop_forever() , therefore cannot execute further commands. second, need define mybuffer global variable passes out of on_message callback. feels little clunky (as far know) best way trying do.
the solution first problem use loop_start() instead of loop_forever(). suspicion when tried before didn't put delay in give script time receive messages. second problem can solved adding line global mybuffer in on_message callback. tells python global variable, not local one.
here working code illustrates this:
import paho.mqtt.client paho import time mybuffer = '' def on_subscribe(client, userdata, mid, granted_qos): print('subscribed') def on_message(client, userdata, msg): global mybuffer mybuffer = str(msg.payload) print('on_message: '+ mybuffer) client = paho.client() client.on_subscribe = on_subscribe client.on_message = on_message client.connect('test.mosquitto.org') client.subscribe('$sys/#') client.loop_start() time.sleep(1) client.loop_stop() print(mybuffer)
however, not best way accomplish trying because cannot handle multiple messages in predictable way. better approach wrap of code on_message call this:
import paho.mqtt.client paho import time def on_subscribe(client, userdata, mid, granted_qos): print('subscribed') def on_message(client, userdata, msg): mybuffer = str(msg.payload) print('on_message: '+ mybuffer) print(mybuffer) client = paho.client() client.on_subscribe = on_subscribe client.on_message = on_message client.connect('test.mosquitto.org') client.subscribe('$sys/#') client.loop_forever()
this far more robust solution problem and, perspective, easier understand.
Comments
Post a Comment