# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
import socket, json, time
 
GATEWAY = '127.0.0.1'               # IP of the Pi gateway (e.g. 192.168.1.20)
PORT, NODE_ID = 6000, 'room-101'    # gateway port and this node's name
 
# ---- Connect once and keep the TCP connection open for all readings.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((GATEWAY, PORT))
    rx = s.makefile('r')                         # read replies line by line
    for temp in [24.5, 31.2, 28.0]:              # demo values (or a DHT22)
        msg = {'id': NODE_ID, 'temp': temp}      # build the message
        # dict -> JSON text + newline (framing) -> bytes -> send
        s.sendall((json.dumps(msg) + '\n').encode())
        cmd = rx.readline().strip()              # wait for FAN_ON / FAN_OFF
        print('sent', temp, '-> gateway says', cmd)
        time.sleep(1)                            # next reading in 1 s
