# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform — P36
"""Forward temperature-only TEMP:<value> serial lines to a private channel."""
import os, time, sys, math
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
# Reuse P34's key and response validation without importing hardware drivers.
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'lab34'))
from dht22_thingspeak import validate_key, response_entry
from getpass import getpass, GetPassWarning
import warnings
warnings.filterwarnings("error",category=GetPassWarning)
import serial


def main():
    try:
        key=validate_key(os.getenv('THINGSPEAK_WRITE_KEY','').strip() or getpass('ThingSpeak channel Write API Key (hidden): '))
    except (ValueError,EOFError,GetPassWarning) as e:
        print('Credential error:',str(e),file=sys.stderr);return 1
    last=-float('inf')
    try:
        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 not line.startswith('TEMP:'):continue
                try: temp=float(line.split(':',1)[1])
                except ValueError:continue
                if not math.isfinite(temp) or not -40<=temp<=80:continue
                if time.monotonic()-last<20:continue
                last=time.monotonic() # Pace attempted requests as well as accepted ones.
                req=Request('https://api.thingspeak.com/update',data=urlencode({'api_key':key,'field1':temp,'status':'arduino-demo'}).encode(),method='POST',headers={'Content-Type':'application/x-www-form-urlencoded'})
                try:
                    with urlopen(req,timeout=15) as r: entry=response_entry(r.status,r.read(128).decode('ascii',errors='replace'))
                    print('HTTP 200; accepted entry:',entry,'Temperature:',temp,flush=True)
                except HTTPError as e: print('HTTP',e.code,'— check channel credentials/permissions and update interval.',flush=True)
                except (RuntimeError,ValueError) as e:print('Upload rejected:',str(e),flush=True)
                except (URLError,TimeoutError,OSError):print('Connection failed; check DNS, network, clock and TLS trust.',flush=True)
    except serial.SerialException:
        print('Serial unavailable; check SERIAL_PORT and close other applications using the port.',file=sys.stderr);return 1

if __name__=='__main__':
    try:sys.exit(main())
    except KeyboardInterrupt:sys.exit(130)
