# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Runs on the Raspberry Pi gateway  (IP 192.168.1.20)
import socket
 
# TCP/IPv4 socket; "with" closes it automatically at the end.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind(('192.168.1.20', 5000))     # this Pi's IP, fixed port 5000
    srv.listen()                         # wait for nodes to connect
    print('Listening on', srv.getsockname())
    conn, addr = srv.accept()            # blocks until a node connects
    with conn:
        print('Connection from', addr)   # node IP + its temporary port
        print('Server side  :', conn.getsockname())
        data = conn.recv(1024)           # up to 1024 bytes
        print('Received', len(data), 'bytes:', data.decode())
        conn.sendall(b'ACK')             # confirm receipt
