multithreading - Thread issue while subscribing to MQTT in Python using Paho MQTT -
i have python program listens mqtt topic , needs process message. specify number of arguments command line evaluate message differently.
import argparse import datetime import json import paho.mqtt.client mqtt ### mqtt functions def on_connect(mqttc, obj, flags, rc): print("connected! - " + str(rc)) def on_message(mqttc, obj, msg): print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload)) def on_publish(mqttc, obj, mid): print("published! "+str(mid)) def on_subscribe(mqttc, obj, mid, granted_qos): print("subscribed! - "+str(mid)+" "+str(granted_qos)) def on_log(mqttc, obj, level, string): print(string) if __name__ == "__main__": # handle args parser = argparse.argumentparser( description='this usedin conjunction wifiscanner on raspberry pi') parser.add_argument('--topic', metavar='base/sub', type=str, nargs='?', help='full topic listen to. (example "proximity/sensor")', default="proximity/#") parser.add_argument('--host', metavar='url', type=str, nargs='?', help='uql of mqtt server.') parser.add_argument('--graph', metavar='true/false', type=bool, nargs='?', help='whether print data.', default=true) parser.add_argument('--timeout', metavar='sec', type=int, nargs='?', help='how long device remembered', default=10) args = parser.parse_args() # mqtt mqttc = mqtt.client() # mqttc.on_message = on_message mqttc.on_connect = on_connect mqttc.on_publish = on_publish mqttc.on_subscribe = on_subscribe # uncomment enable debug messages #mqttc.on_log = on_log mqttc.connect(args.host, 1883, 60) mqttc.subscribe(args.topic, 0) # start listen while true: print mqttc.loop()
the problem this, can't see easy way pass command line arguments on_message
callback. tried using return value of .loop
. however, when try exit using ctrl+z (only keyboard interrupt works), not exit mqtt threads , leaves them running.
the documentation , examples don't have example on how handle messages outside on_message
callback , how cleanly exit.
so fixing issue appreciated.
thanks in advance
you use userdata
argument client()
constructor. ends being passed every callback.
Comments
Post a Comment