#!/usr/bin/env python3
"""Check if MCU is outputting anything on the USB serial port."""
import serial
import time
import sys

def check_mcu():
    port = '/dev/cu.usbmodem0001507128921'
    print(f"Opening {port}...")
    try:
        s = serial.Serial(port, 115200, timeout=3)
        time.sleep(0.5)
        # Try to read any output
        data = s.read(500)
        if data:
            print(f"MCU output ({len(data)} bytes):")
            # Show as hex + printable
            for i in range(0, len(data), 16):
                chunk = data[i:i+16]
                hex_str = ' '.join(f'{b:02x}' for b in chunk)
                ascii_str = ''.join(chr(b) if 32 <= b < 127 else '.' for b in chunk)
                print(f"  {i:04x}: {hex_str:<48s} {ascii_str}")
        else:
            print("MCU serial port is open but no data received.")
            print("MCU might be running but not outputting anything at 115200.")
        
        # Try alternative baud rates
        for baud in [460800, 9600]:
            print(f"\nTrying {baud} baud...")
            s.close()
            s = serial.Serial(port, baud, timeout=2)
            time.sleep(0.3)
            data = s.read(500)
            if data:
                print(f"Got {len(data)} bytes at {baud}: {repr(data[:100])}")
            else:
                print(f"No data at {baud}")
        
        s.close()
        
    except serial.SerialException as e:
        print(f"Cannot open {port}: {e}")
        print("MCU might not be powered or the port is busy.")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == '__main__':
    check_mcu()
