|
| 1 | +""" |
| 2 | +Reply format. See http://cl.ly/ekot |
| 3 | +
|
| 4 | +0 Header '\xaa' |
| 5 | +1 Command '\xc0' |
| 6 | +2 DATA1 PM2.5 Low byte |
| 7 | +3 DATA2 PM2.5 High byte |
| 8 | +4 DATA3 PM10 Low byte |
| 9 | +5 DATA4 PM10 High byte |
| 10 | +6 DATA5 ID byte 1 |
| 11 | +7 DATA6 ID byte 2 |
| 12 | +8 Checksum Low byte of sum of DATA bytes |
| 13 | +9 Tail '\xab' |
| 14 | +
|
| 15 | +""" |
| 16 | + |
| 17 | +import machine |
| 18 | +import ustruct as struct |
| 19 | +import mqtt |
| 20 | +import sys |
| 21 | +import utime as time |
| 22 | + |
| 23 | +uart = machine.UART(0, 9600) |
| 24 | +uart.init(9600, bits=8, parity=None, stop=1) |
| 25 | + |
| 26 | +def wake(): |
| 27 | + global uart |
| 28 | + while uart.read(1) == None: |
| 29 | + print('Sending wake command to sds011') |
| 30 | + cmd = b'\xaa\xb4\x06\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x06\xab' |
| 31 | + uart.write(cmd) |
| 32 | + print('sds011 woke up!') |
| 33 | + |
| 34 | +def sleep(): |
| 35 | + global uart |
| 36 | + AWAKE = True |
| 37 | + while AWAKE: |
| 38 | + print('Sending sleep command to sds011') |
| 39 | + cmd = b'\xaa\xb4\x06\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x05\xab' |
| 40 | + uart.write(cmd) |
| 41 | + header = uart.read(1) |
| 42 | + if header == b'\xaa': |
| 43 | + command = uart.read(1) |
| 44 | + if command == b'\xc5': |
| 45 | + AWAKE = False |
| 46 | + print('sds011 successfully put to sleep') |
| 47 | + |
| 48 | +def process_packet(packet): |
| 49 | + try: |
| 50 | + print('\nPacket:', packet) |
| 51 | + *data, checksum, tail = struct.unpack('<HHBBBs', packet) |
| 52 | + pm25 = data[0]/10.0 |
| 53 | + pm10 = data[1]/10.0 |
| 54 | + # device_id = str(data[2]) + str(data[3]) |
| 55 | + checksum_OK = checksum == (sum(data) % 256) |
| 56 | + tail_OK = tail == b'\xab' |
| 57 | + packet_status = 'OK' if (checksum_OK and tail_OK) else 'NOK' |
| 58 | + print('PM 2.5:', pm25, '\nPM 10:', pm10, '\nStatus:', packet_status) |
| 59 | + mqtt.publish({ |
| 60 | + 'pm25': pm25, |
| 61 | + 'pm10': pm10, |
| 62 | + 'status': packet_status |
| 63 | + }) |
| 64 | + except Exception as e: |
| 65 | + print('Problem decoding packet:', e) |
| 66 | + sys.print_exception(e) |
| 67 | + |
| 68 | +def read(allowed_time): |
| 69 | + global uart |
| 70 | + print('Reading from sds011 for', (allowed_time / 1000), 'secs') |
| 71 | + start_time = time.ticks_ms() |
| 72 | + SHOULD_READ = True |
| 73 | + while SHOULD_READ: |
| 74 | + try: |
| 75 | + delta_time = time.ticks_diff(time.ticks_ms(), start_time) |
| 76 | + if (delta_time > allowed_time): SHOULD_READ = False |
| 77 | + header = uart.read(1) |
| 78 | + if header == b'\xaa': |
| 79 | + command = uart.read(1) |
| 80 | + if command == b'\xc0': |
| 81 | + packet = uart.read(8) |
| 82 | + process_packet(packet) |
| 83 | + except Exception as e: |
| 84 | + print('Problem attempting to read:', e) |
| 85 | + sys.print_exception(e) |
0 commit comments