Untitled

 avatar
unknown
plain_text
9 months ago
1.7 kB
14
Indexable
def find_device_port_by_snr(target_snr: str, device_type: str) -> str:
    """
    Find the correct serial port for a given device type and serial number.
    
    Args:
        target_snr (str): The device's serial number (unique per board).
        device_type (str): One of {'ppk2', 'nordic', 'stm'}.
    
    Returns:
        str: Path to the serial port (e.g. '/dev/ttyACM0').
    """
    ports = list(serial.tools.list_ports.comports())

    for port in ports:
        # --- Common filter: match serial number ---
        if port.serial_number != target_snr:
            continue

        # --- Device-specific filters ---
        if device_type.lower() == "ppk2":
            if port.product == "PPK2" and port.location and port.location.endswith("1"):
                return port.device

        elif device_type.lower() == "nordic":
            # Nordic boards (e.g. nRF52840, nRF5340)
            #TODO Check if these filters actually work
            if (
                "Nordic" in (port.manufacturer or "")
                or (port.product and "nRF" in port.product)
            ):
                return port.device

        elif device_type.lower() == "stm":
            # STMicroelectronics devices (e.g. NUCLEO, Discovery boards)
            #TODO Check if these filters actually work
            if (
                "STM" in (port.manufacturer or "")
                or (port.product and "ST" in port.product)
            ):
                return port.device

        else:
            raise ValueError(f"Unknown device_type: {device_type}")

    # If we reached here, no matching port was found
    raise DeviceNotFoundError(
        f"No {device_type} device with serial number {target_snr} found."
    )
Editor is loading...
Leave a Comment