# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
import csv
from datetime import datetime
import time
import board
import adafruit_dht
sensor = adafruit_dht.DHT22(board.D23)
try:
    for attempt in range(5):
        try:
            temperature, humidity = sensor.temperature, sensor.humidity
        except RuntimeError as err:
            print('Read failed:', err)
            if attempt < 4:
                time.sleep(2)
            continue
        if temperature is not None and humidity is not None and -40 <= temperature <= 80 and 0 <= humidity <= 100:
            with open('dht22_log.csv', 'a', newline='', encoding='utf-8') as file:
                csv.writer(file).writerow([datetime.now().isoformat(), temperature, humidity])
            print('Reading stored in CSV.')
            break
        if attempt < 4:
            time.sleep(2)
    else:
        raise SystemExit("DHT22 failed after five attempts; no CSV row appended.")
finally:
    sensor.exit()
