0

I have a sample code for getting a message from Mqtt broker

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("123")
def on_message(client, userdata, msg):
    x = int(msg.payload)*10
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.connect("broker.hivemq.com", 1883)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()

How can I get the variable of msg.payload in on_message?

I add the x variable in function of on_connect:

def on_message(client, userdata, msg):
    x = int(msg.payload)*10
    print(msg.topic+" "+str(msg.payload))
    return x

Question: How do I get the variable x?

高露潔
  • 1
  • 3
  • 1
    `on_message` is a callback function. You can not simply retrieve the return value because it is called implicitly. So, whatever you want to do with `x`, do it inside of the function. – Klaus D. Dec 28 '17 at 04:40
  • use a global variable and set its value to x from within the `on_message` – Pratik Kumar Jan 22 '18 at 13:11

1 Answers1

0

My approach to solve this would be as follows:

import paho.mqtt.client as mqtt
msg_arrived_flag = False
global_X = 0


def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))
  client.subscribe("123")
def on_message(client, userdata, msg):
  global_X = int(msg.payload)*10
  print(msg.topic+" "+str(msg.payload))
  msg_arrived_flag = True

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.hivemq.com", 1883)

while True:
  client.loop_start()
  time.sleep(5)
  client.loop_stop()
  if msg_arrived_flag:
    msg_arrived_flag = False
    #Use global_X here

Time to sleep between start and stop may be set as convenience. Also I suggest to set callbacks before connect. Hope this helps!

smajtkst
  • 461
  • 4
  • 6