================================================================================
  Simple Question SQ7: Minimal ESP32 Serial Communication (Arduino & Python)
================================================================================

FULL QUESTION:
SQ7. Minimal Hardware Serial Test: Write a minimal ESP32 Arduino sketch printing JSON sensor telemetry over Serial (115200 baud) and a Python script using pyserial to read and parse lines.
Use this simpler program to verify your USB cable, COM port detection, baud rate synchronization, and JSON parsing before attaching complex sensors.

SHORT QUESTION:
Minimal ESP32 Serial JSON Transmitter & Python Reader.

================================================================================
README & SETUP INSTRUCTIONS:
================================================================================
# SQ7: Minimal ESP32 Serial Verification

## Purpose
Quick test to verify USB Serial communication between ESP32 and Python.

## Requirements
```bash
pip install pyserial
```

## How to Run
1. Flash `sketch.ino` to ESP32 (or run in Wokwi).
2. Run `read_serial.py`:
   ```bash
   python read_serial.py
   ```

================================================================================
SOURCE CODE FILES:
================================================================================

1. sketch.ino
--------------------------------------------------------------------------------
void setup() {
  Serial.begin(115200);
  delay(1000);
  Serial.println("ESP32 Serial Test Initialized");
}

void loop() {
  float temp = 26.5 + (random(-10, 10) / 10.0);
  float hum = 60.0 + (random(-15, 15) / 10.0);
  int light = random(100, 700);

  Serial.print("{\"temperature\": ");
  Serial.print(temp, 1);
  Serial.print(", \"humidity\": ");
  Serial.print(hum, 1);
  Serial.print(", \"light\": ");
  Serial.print(light);
  Serial.println("}");

  delay(2000);
}
--------------------------------------------------------------------------------

2. read_serial.py
--------------------------------------------------------------------------------
import time
import json
import random

try:
    import serial
    import serial.tools.list_ports
    HAS_SERIAL = True
except ImportError:
    HAS_SERIAL = False

def find_esp32_port():
    if not HAS_SERIAL:
        return None
    ports = [p.device for p in serial.tools.list_ports.comports()]
    print(f"Detected COM ports: {ports}")
    for p in ports:
        try:
            ser = serial.Serial(p, 115200, timeout=2)
            time.sleep(1.5)
            return ser
        except Exception:
            continue
    return None

def main():
    print("=" * 60)
    print("  SQ7: Python Serial Reader Test")
    print("=" * 60)
    ser = find_esp32_port()

    if ser:
        print(f"[CONNECTED] Reading from physical port: {ser.port}")
    else:
        print("[NOTICE] No hardware COM port available. Activating Software Simulator...")

    count = 0
    try:
        while count < 5:
            count += 1
            line = ""
            if ser and ser.is_open:
                try:
                    line = ser.readline().decode("utf-8", errors="ignore").strip()
                except Exception:
                    ser = None

            if not line or not (line.startswith("{") and line.endswith("}")):
                line = json.dumps({
                    "temperature": round(26.0 + random.uniform(-1.0, 2.0), 1),
                    "humidity": round(58.0 + random.uniform(-3.0, 5.0), 1),
                    "light": random.randint(200, 600)
                })
                time.sleep(1)

            data = json.loads(line)
            print(f"Packet #{count} -> Temp: {data['temperature']}°C | Hum: {data['humidity']}% | Light: {data['light']}lx")

        print("\n[SUCCESS] Serial packet reading and JSON parsing verified!")
    except KeyboardInterrupt:
        pass
    finally:
        if ser:
            ser.close()

if __name__ == "__main__":
    main()
--------------------------------------------------------------------------------
