From 5e673e0c0edabaaf9a761404a42062d8800d0fca Mon Sep 17 00:00:00 2001 From: Maximilian Giller Date: Sat, 10 Aug 2024 02:50:05 +0200 Subject: [PATCH] Self implemented co2 again --- src/handler/mhz19_co2.py | 40 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) 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