2016-05-14 141 views
0

我想問一下,如果有使用msg.payload全球,而不只是在回調函數的方式。如何將msg.payload全局用於MQTT Python客戶端?

貝婁是基本的回調函數:

# The callback for when a PUBLISH message is received from the server. 
def on_message(client, userdata, msg): 
    print(msg.topic+" "+str(msg.payload)) 
    # I usually then specify my steps here, but how can I use the variable outside? 


client = mqtt.Client() 
client.on_connect = on_connect 
client.on_message = on_message 

例如,我想要做這樣的事情:

def on_message(client, userdata, msg): 
    print(msg.topic+" "+str(msg.payload)) 
    return msg.payload 

global_data= on_message 
# do whatever I want with the data. I already tried to do this but it didn't work because 
# the client loops forever using client.loop_forever() 
+0

你是什麼意思?該消息只存在於回調中。如果你在其他地方需要它,你需要在那裏傳遞它。 –

+0

是的,但我如何通過它? –

+0

與其他函數參數相同。我不確定你在問什麼。 –

回答

1

使用,而不是client.loop功能client.start_loop功能。這將在一個單獨的線程上啓動網絡循環,允許您在主線程上執行自己的操作。

然後,您可以設置或從回調中改變一個全局變量的msg.payload的內容的價值。

E.g.

global_var 

def on_message(client, userdata, msg): 
    global global_var 
    print(msg.topic+" "+str(msg.payload)) 
    global_var = msg.payload 
相關問題