import os
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Import the serial and time modules.
import serial
import time
 
# ---- Open the Arduino serial connection.
# Change the device name if your system uses a different one.
ser = serial.serial_for_url(os.getenv('SERIAL_PORT', '/dev/ttyACM0'), 9600)
time.sleep(2)   # the Uno resets when the port opens
 
# ---- Helper function that sends LED commands.
def toggle_led(command):
    # Normalise the user text.
    command = command.lower()
    if command == 'on':
        ser.write(b'H')       # H = LED on
    elif command == 'off':
        ser.write(b'L')       # L = LED off
    else:
        print("Invalid command. Use 'on' or 'off'.")

# ---- Main interactive loop (uses toggle_led from part 1).
try:
    while True:
        cmd = input("Enter 'on' or 'off': ")
        toggle_led(cmd)
        time.sleep(1)
except KeyboardInterrupt:
    # Close the serial connection safely.
    ser.close()
