#!/usr/bin/env python3
"""
MCU UART 十六进制/ASCII 测试脚本
尝试多种命令格式，查找 AMS 响应
"""
import serial
import time
import binascii

PORT = "/dev/cu.usbmodem1302"
BAUD = 921600
TIMEOUT = 4


def hex_to_bytes(hex_str: str) -> bytes:
    """从十六进制字符串解析字节，支持空格分隔"""
    return binascii.unhexlify(hex_str.replace(" ", ""))


def bytes_to_hex(data: bytes) -> str:
    return " ".join(f"{b:02X}" for b in data)


def test_command(ser: serial.Serial, name: str, payload: bytes, wait: float = 2.0):
    print(f"\n{'='*60}")
    print(f"测试 [{name}]")
    print(f"发送 HEX ({len(payload)} bytes): {bytes_to_hex(payload)}")
    try:
        print(f"发送 ASCII: {payload.decode('utf-8', errors='replace')!r}")
    except Exception:
        pass

    ser.reset_input_buffer()
    ser.reset_output_buffer()
    time.sleep(0.1)

    ser.write(payload)
    ser.flush()

    # 分阶段读取
    all_rx = b""
    deadline = time.time() + wait
    while time.time() < deadline:
        rx = ser.read(ser.in_waiting or 1)
        if rx:
            all_rx += rx
        else:
            time.sleep(0.05)

    if all_rx:
        print(f"收到 ({len(all_rx)} bytes):")
        print(f"  HEX: {bytes_to_hex(all_rx[:300])}")
        try:
            ascii_str = all_rx.decode("utf-8", errors="replace")
            print(f"  ASCII: {ascii_str[:500]!r}")
        except Exception as e:
            print(f"  解码失败: {e}")

        # 检查是否包含关键词
        text = all_rx.decode("utf-8", errors="ignore").lower()
        keywords = ["ams", "radio", "freq", "ok", "error", "found", "not found"]
        found = [k for k in keywords if k in text]
        if found:
            print(f"  关键词命中: {found}")
    else:
        print("未收到数据")


def main():
    print(f"目标串口: {PORT}")
    print(f"波特率: {BAUD}")
    print(f"数据位: 8, 停止位: 1, 校验: None, 流控: None")

    try:
        with serial.Serial(
            port=PORT,
            baudrate=BAUD,
            bytesize=serial.EIGHTBITS,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            rtscts=False,
            dsrdtr=False,
            xonxoff=False,
            timeout=0.1,
        ) as ser:
            # 1. 原始 ASCII 命令 + 不同换行
            test_command(ser, "radio_test 4 1 + CR", b"radio_test 4 1\r")
            test_command(ser, "radio_test 4 1 + LF", b"radio_test 4 1\n")
            test_command(ser, "radio_test 4 1 + CRLF", b"radio_test 4 1\r\n")

            # 2. help 类命令
            test_command(ser, "help + CR", b"help\r")
            test_command(ser, "? + CR", b"?\r")
            test_command(ser, "AT + CR", b"AT\r")

            # 3. radio 相关变体
            test_command(ser, "radio + CR", b"radio\r")
            test_command(ser, "radio_test + CR", b"radio_test\r")
            test_command(ser, "radio_test 4 1 0 + CR", b"radio_test 4 1 0\r")
            test_command(ser, "radio 4 1 + CR", b"radio 4 1\r")

            # 4. 十六进制帧尝试（基于 MCU 协议帧头 FF AA）
            test_command(ser, "MCU poll frame", hex_to_bytes("FF AA 00 07 01 05 F3"))

            # 5. 空发送
            test_command(ser, "Only CR", b"\r")
            test_command(ser, "Only LF", b"\n")

    except serial.SerialException as e:
        print(f"串口错误: {e}")
    except Exception as e:
        print(f"异常: {e}")

    print("\n测试完成")


if __name__ == "__main__":
    main()
