import array import sys import usb.core import usb.util import paho.mqtt.client as mqtt import time from threading import Event, Thread def sdsAnalyzer(sds011_thread_Event, client): global th_abort sds011_thread_Event.wait(5) VID =0x1a86 PID = 0x7523 DATA_SIZE = 4 device = usb.core.find(idVendor = VID, idProduct = PID) if device is None: th_abort = True sys.exit("Could not find sds011 Sensor.") if device.is_kernel_driver_active(0): try: device.detach_kernel_driver(0) except usb.core.USBError as e: th_abort = True sys.exit("Could not detatch kernel driver: %s" % str(e)) try: device.reset() device.set_configuration() except usb.core.USBError as e: th_abort = True sys.exit("Could not set configuration: %s" % str(e)) endpoint = device[0][(0,0)][0] print(endpoint.wMaxPacketSize) result, mid = client.publish("sds011/data", "Starting data reading", 0) data = array.array('B',(0,)*4) while data[0] != 3 and not th_abort: try: data = device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize) print(data) # result, mid = client.publish("sds011/data", str(data), 0) sds011_thread_Event.wait(1) except usb.core.USBError as e: if e.args == ('Operation timed out',): print("timeout)") continue #print("work!") print('sdsAnalyzer stopped...') exit() def mqttConnector(mqtt_thread_Event, client): def on_connect(client, obj, flags, rc): client.subscribe("sds011/#", 0) def on_subscribe(client, userdata, mid, granted_qos): print ('Subscribed:', userdata, mid, granted_qos) print ('We are here, waiting...') def on_message(mosq, obj, msg): global th_abort if "Are you alive?" in msg.payload.decode("utf-8"): result, mid = client.publish("sds011/heartbeat_response", "alive", 0) if "abort" in msg.payload.decode("utf-8"): th_abort = True global th_abort client.on_connect = on_connect client.on_message = on_message client.on_subscribe = on_subscribe resp = client.connect('127.0.0.1', 1883, 60) client.loop_start() while not th_abort: mqtt_thread_Event.wait(0.1) client.loop_stop() client.disconnect() print ("mqttConnector: stopped...") exit() th_abort = False client = mqtt.Mosquitto() mqtt_thread_Event = Event() mqtt_thread = Thread(target=mqttConnector, args=(mqtt_thread_Event,client,)) mqtt_thread.start() # start the child thread sds011_thread_Event = Event() sds011_thread = Thread(target=sdsAnalyzer, args=(sds011_thread_Event,client,)) sds011_thread.start() # start the child thread print ("sds011 script stopped...") exit()