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 VID =0x1a86 PID = 0x7523 DATA_SIZE = 4 device = usb.core.find(idVendor = VID, idProduct = PID) if device is None: 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: sys.exit("Could not detatch kernel driver: %s" % str(e)) try: device.reset() device.set_configuration() except usb.core.USBError as e: sys.exit("Could not set configuration: %s" % str(e)) endpoint = device[0][(0,0)][0] print(endpoint.wMaxPacketSize) data = array.array('B',(0,)*4) while data[0] != 3 and th_abort == False: try: data = device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize) print(data) result, mid = client.publish("sds011/data", str(data), 0) except usb.core.USBError as e: if e.args == ('Operation timed out',): print("timeout)") continue #print("work!") print('sdsAnalyzer stopped...') exit() 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 th_abort = False client = mqtt.Mosquitto() client.on_connect = on_connect client.on_message = on_message client.on_subscribe = on_subscribe resp = client.connect('127.0.0.1', 1883, 60) sds011_thread_Event = Event() sds011_thread = Thread(target=sdsAnalyzer, args=(sds011_thread_Event,client,)) sds011_thread.start() # start the child thread client.loop_start() while not th_abort: time.sleep(0.1) client.loop_stop() client.disconnect() print ("sds011 script stopped...") exit()