# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Install once, inside a virtual environment (Part 1):
#   python3 -m venv --system-site-packages ~/iot-env
#   source ~/iot-env/bin/activate
#   pip install adafruit-circuitpython-dht
# ---- Current DHT22 library: retry on RuntimeError, max 5 times
import time
import board                          # Pi pin names (from Adafruit Blinka)
import adafruit_dht
 
dht = adafruit_dht.DHT22(board.D23)   # DATA on BCM GPIO23 (pin 16)
try:
    for attempt in range(5):
        try:
            t = dht.temperature
            h = dht.humidity
            if t is None or h is None or not (-40 <= t <= 80 and 0 <= h <= 100):
                raise RuntimeError("Invalid DHT22 sample")
            print(f"Temp={t:0.1f} C  Humidity={h:0.1f}%")
            break
        except RuntimeError as err:
            print("Read failed:", err)
            if attempt < 4:
                time.sleep(2.0)
    else:
        raise SystemExit("DHT22 failed after five attempts; no reading recorded.")
finally:
    dht.exit()
