Added climate logging

This commit is contained in:
Maximilian Giller 2023-10-17 17:57:32 +02:00
parent 8fec41ae33
commit c7e128d8f2
2 changed files with 31 additions and 4 deletions

View file

@ -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
return None
def get_last_read(self):
if self.last_read is None:
self.read()
return self.last_read

View file

@ -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"}