From c7e128d8f22522678a39a0e317833d57671c62e7 Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 17 Oct 2023 17:57:32 +0200 Subject: [PATCH] Added climate logging --- src/climate.py | 11 +++++++++-- src/main.py | 24 ++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/climate.py b/src/climate.py index 5f0c87d..fdc0149 100644 --- a/src/climate.py +++ b/src/climate.py @@ -4,10 +4,17 @@ class Dht22Sensor: def __init__(self, pin): self.sensor = Adafruit_DHT.AM2302 self.pin = pin + self.last_read = None def read(self): humidity, temperature = Adafruit_DHT.read_retry(self.sensor, self.pin) if humidity is not None and temperature is not None: - return {'temperature': temperature, 'humidity': humidity} + self.last_read = {'temperature': temperature, 'humidity': humidity} + return self.last_read else: - return None \ No newline at end of file + return None + + def get_last_read(self): + if self.last_read is None: + self.read() + return self.last_read \ No newline at end of file diff --git a/src/main.py b/src/main.py index de00931..ba366a6 100644 --- a/src/main.py +++ b/src/main.py @@ -1,3 +1,4 @@ +import os from fastapi import FastAPI, HTTPException from datetime import datetime import requests @@ -25,10 +26,28 @@ app.add_middleware( should_run_time_loop = True dht22_pin = 17 +climate_log_file = "./climate.csv" matrix_display = MatrixDisplay() dht22_sensor = Dht22Sensor(dht22_pin) +# Start background service to log temperature and humidity every minute +async def log_temperature(): + # If file does not exist, create it and write header + if not os.path.isfile(climate_log_file): + with open(climate_log_file, "w") as f: + f.write("timestamp,temperature,humidity\n") + + while True: + measurements = dht22_sensor.read() + if measurements is not None: + with open(climate_log_file, "a") as f: + f.write("{},{},{}\n".format( + datetime.now().isoformat(), + measurements["temperature"], + measurements["humidity"] + )) + await asyncio.sleep(60) async def display_time(): while should_run_time_loop: @@ -46,6 +65,7 @@ async def display_time(): asyncio.create_task(display_time()) +asyncio.create_task(log_temperature()) @@ -68,7 +88,7 @@ async def turn_off(): @app.post("/temperature") async def temperature(): - measurements = dht22_sensor.read() + measurements = dht22_sensor.get_last_read() if measurements is None: return {"message": "Failed to read temperature"} @@ -89,7 +109,7 @@ async def temperature(): @app.post("/humidity") async def humidity(): - measurements = dht22_sensor.read() + measurements = dht22_sensor.get_last_read() if measurements is None: return {"message": "Failed to read humidity"}