线程和MQTT接收python之间没有共享全局变量



mainthread:

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(Broker, 1883, 60)
client.on_log = on_log
client.loop_start()
global alarm
alarm = True
while True:        
    try:
        if alarm == True:
        ...

且功能具有更改变量:

def on_message(client, userdata, msg):
    message = str(msg.payload)
    if message.lower() == 'alarm off': alarm = False
    elif message.lower() == 'alarm on': alarm = True

它的工作方式与函数和主要线程中的单独变量一样,我找不到原因。

应将var标记为on_message函数中的全局,而不是您拥有的位置。

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(Broker, 1883, 60)
client.on_log = on_log
client.loop_start()
alarm = True
while True:        
    try:
        if alarm == True:
        ...

def on_message(client, userdata, msg):
    global alearm
    message = str(msg.payload)
    if message.lower() == 'alarm off': alarm = False
    elif message.lower() == 'alarm on': alarm = True

相关内容

  • 没有找到相关文章

最新更新