diff --git a/src/handler/mhz19_co2.py b/src/handler/mhz19_co2.py index 4ac99d7..bc28016 100644 --- a/src/handler/mhz19_co2.py +++ b/src/handler/mhz19_co2.py @@ -1,16 +1,48 @@ -import mh_z19 -import logging +import serial class Mhz19Co2: - def __init__(self): self.last_read = None + self.serial_port = "/dev/serial0" + self.baud_rate = 9600 + self.byte_size = 8 + self.parity = "N" + self.stop_bits = 1 + self.timeout = None + def get_last_read(self) -> int | None: if self.last_read is None: return self.read() return self.last_read def read(self) -> int | None: - return mh_z19.read()["co2"] + ser = None + 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) + concentration = data[2] * 256 + data[3] + + except Exception as e: + print(f"Error reading data: {e}") + finally: + if ser: + ser.close() + ser = None + + self.last_read = concentration + return concentration