import os
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
import serial, csv, math
from datetime import datetime
with serial.serial_for_url(os.getenv('SERIAL_PORT', '/dev/ttyACM0'), 9600, timeout=1) as ser:
    while True:
        line = ser.readline().decode('utf-8', errors='replace').strip()
        if line.startswith('TEMP:'):
            try:
                value = float(line.split(':', 1)[1])
            except ValueError:
                continue
            if not math.isfinite(value) or not -40 <= value <= 80:
                continue
            timestamp = datetime.now().isoformat()
            print(timestamp, value)
            with open('temp_log.csv', 'a', newline='') as file:
                csv.writer(file).writerow([timestamp, value])
