# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
import socket, threading, json, csv
from datetime import datetime
 
HOST, PORT = '127.0.0.1', 6000        # gateway listens on loopback for lab safety
LIMIT = 30.0                        # fan switches on above 30 °C
lock = threading.Lock()             # one thread writes the CSV at a time
 
# ---- One thread per node: read JSON lines, log them, reply with a command
def handle_node(conn, addr):
    """Serve one sensor node until it disconnects."""
    # makefile('r') lets us read the TCP stream one line at a time.
    with conn, conn.makefile('r') as rx:
        for line in rx:                          # one JSON message per line
            msg = json.loads(line)               # text -> dict
            # Log the reading with a timestamp (lock = safe file access).
            with lock, open('readings.csv', 'a', newline='') as f:
                csv.writer(f).writerow([datetime.now().isoformat(),
                                        msg['id'], msg['temp']])
            # Decide the command and send it back to the same node.
            cmd = 'FAN_ON' if msg['temp'] > LIMIT else 'FAN_OFF'
            conn.sendall((cmd + '\n').encode())
            print(addr[0], msg, '->', cmd)
 
# ---- Main program: create, bind and listen on the gateway socket.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind((HOST, PORT))
    srv.listen()
    print('Gateway listening on port', PORT)
    while True:                                  # serve nodes forever
        conn, addr = srv.accept()                # wait for a new node
        # One thread per node, so many rooms can connect at once.
        threading.Thread(target=handle_node, args=(conn, addr),
                         daemon=True).start()
