multithreading - Add several individual threads to MQTT Python code -
this code , need add,
(1) loop(thread1) can publish data when receive specific data uart(ser.read())
(2) loop(thread2) can run report_temp_humidity() timed delay
so put thread test runs 1 time, not loop.
is cause "mqttclient.loop_forever()" @ end of line?
need on this.
import paho.mqtt.client mqtt import adafruit_dht import adafruit_bbio.uart uart import serial import threading import time # dht-11 temperature & humidity sensor = adafruit_dht.dht11 sensor_pin = 'p8_11' # uart uart.setup("uart1") ser = serial.serial(port = "/dev/ttyo1", baudrate=9600) ser.close() ser.open() # define event callbacks def on_connect(self, client, userdata, rc): if rc == 0: print("connected successfully.") else: print("connection failed. rc= "+str(rc)) def on_publish(client, userdata, mid): print("message "+str(mid)+" published.") def on_subscribe(client, userdata, mid, granted_qos): print("subscribe mid "+str(mid)+" received.") def on_message(client, userdata, msg): print("message received on topic "+msg.topic+" qos "+str(msg.qos)+"and payload "+msg.payload) if msg.payload == "check_status": report_temp_humidity() if msg.payload == "motor_run!": print "send command rf" ser.write("11.1111[s]") # define function prototypes def report_temp_humidity(): hum, temp = adafruit_dht.read_retry(sensor, sensor_pin) mqttclient.publish("/my_topic1/", "temperature "+ str(temp) + "`c", qos=0) mqttclient.publish("/my_topic1/", "humidity " + str(hum) + "%", qos=0) # define thread(loop) test def loop_test(delay): print(loop!) time.sleep(1) t1 = threading.thread(target=loop_test, args=('1,',)) t1.start() mqttclient = mqtt.client() # assign event callbacks mqttclient.on_connect = on_connect mqttclient.on_publish = on_publish mqttclient.on_subscribe = on_subscribe mqttclient.on_message = on_message # connect mqttclient.username_pw_set("dioty_user", "1234567") mqttclient.connect("mqtt.dioty.co", 1883) # start subscription mqttclient.subscribe("/my_topic1/") # publish message mqttclient.publish("/my_topic1/", "hello world message!") # loop mqttclient.loop_forever()
this has nothing mqtt library.
your thread t1
run loop_test
function, has 2 statements in it. run these (once) exit, there nothing tell continue else.
if want thread continue run ever need include loop statement of sort (e.g. while true
).
Comments
Post a Comment