我正在尝试将传入的MQTT消息分配给一个变量。该变量需要在方法外部可以访问,但是,我无法实现。 当我发送MQTT消息时,没有任何反应。
import paho.mqtt.client as mqtt #import the client1
import time
class Mqttreceiving:
def mqttreceivingMethod():
global mqttMesssage
def on_message(client, userdata, message):
mqttMesssage = str(message.payload.decode("utf-8"))
#should return mqtt value outside method
return mqttMesssage
########################################
broker_address="192.168.0.31"
client = mqtt.Client("Secondpi") #create new instance
client.connect(broker_address) #connect to broker
print("Waiting to receive mqtt message")
client.on_message=on_message
client.loop_start()
client.subscribe("carpark/message")
time.sleep(4) # wait
client.loop_stop() # stop the loop
#should return back value of mqtt
Mqttreceiving.mqttreceivingMethod()