无法从paho python mq中的线程发布

2021-11-29 23:10:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用paho mqtt库来运行基于python的mqtt客户机。 我无法按照以下代码从单独的线程发布消息

cb_client = mqtt.Client(
    client_id = "timerScript",
    userdata = [db,conf],
    clean_session = True,
    protocol=mqtt.MQTTv311
)

cb_client.username_pw_set(bc['username'], bc['password'])
userdata = [db,conf]
cb_client.connect(host=bc['host'], port=int(bc['port']))
handle_trigger(cb_client, userdata,trigger) 
cb_client.loop_forever()

def handle_trigger(cbClient,userdata,trigger):
    route = route[0][0]
    cbClient.publish("test","from handler") << this is working
    t = threading.Thread(target=execute_trigger, args=[cbClient, userdata, trigger,route])
    t.daemon = True
    t.start()
    return

def execute_trigger(cbClient,userdata,trigger,route):
   print("Executing trigger {}".format(trigger))
   cbClient.publish("test","from thread") # <<this publish in thread is not working