#!/usr/bin/env python3
"""Gentle serial probe for USB LoRa boards.

This only sends common query commands. It does not flash firmware.
"""

from __future__ import annotations

import sys
import time

import serial


BAUDS = [9600, 19200, 38400, 57600, 115200]
COMMANDS = [
    b"AT\r\n",
    b"AT+VER\r\n",
    b"AT+INFO\r\n",
    b"AT+PARAMETER?\r\n",
    b"AT+ADDRESS?\r\n",
    b"+++\r\n",
]


def probe(port: str) -> int:
    for baud in BAUDS:
        print(f"baud={baud}")
        try:
            with serial.Serial(port, baudrate=baud, timeout=0.35, write_timeout=0.35) as link:
                link.reset_input_buffer()
                for command in COMMANDS:
                    link.write(command)
                    link.flush()
                    time.sleep(0.25)
                    data = link.read(256)
                    if data:
                        print(f"  {command!r} -> {data!r}")
        except Exception as exc:
            print(f"  error: {type(exc).__name__}: {exc}")
    return 0


def main(argv: list[str]) -> int:
    if len(argv) != 2:
        print("Usage: lora_usb_probe.py /dev/ttyUSB0")
        return 2
    return probe(argv[1])


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
