diff --git a/src/handler/mhz19_co2.py b/src/handler/mhz19_co2.py new file mode 100644 index 0000000..74c4fde --- /dev/null +++ b/src/handler/mhz19_co2.py @@ -0,0 +1,65 @@ +import serial + + +class Mhz19Co2: + def __init__(self): + self.last_read = None + + self.serial_port = "/dev/tty.usbserial-B001BTPZ" + self.baud_rate = 9600 + self.byte_size = 8 + self.parity = "N" + self.stop_bits = 1 + self.timeout = None + + def get_last_read(self): + if self.last_read is None: + return self.read() + return self.last_read + + def read(self): + try: + ser = serial.Serial( + port=self.serial_port, + baudrate=self.baud_rate, + bytesize=self.byte_size, + parity=self.parity, + stopbits=self.stop_bits, + timeout=self.timeout, + ) + + # send "Read CO2" command + command_data = bytes([0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79]) + ser.write(command_data) + + # read "Return Value (CO2 concentration)" + data = ser.read(9) + # print("data[2]", data[2]) + # print("data[3]", data[3]) + # print("data[4]", data[4]) + # print("data[5]", data[5]) + # print("data[6]", data[6]) + # print("data[7]", data[7]) + # print("data[8]", data[8]) + + # show CO2 concentration + concentration = data[2] * 256 + data[3] + print(f"=== send data ===") + print(f"send: {command_data}") + print(f"=== read data ===") + print(f"data: {data}") + print(f"data[2] {data[2]}") + print(f"data[3] {data[3]}") + print(f"CO2 Concentration {concentration} ppm") + print(f"=== === ===") + print(f"") + + except Exception as e: + print(f"Error reading data: {e}") + finally: + if ser: + ser.close() + ser = None + + self.last_read = concentration + return concentration