Auto-detect the upload port from available serial ports. Only considers USB devices - filters out Bluetooth and other non-USB ports. Returns a structured result with success status, selected port, error details, and all scanned ports for diagnostics. Prefers common ESP32/Arduino US
(expected_environment: str | None)
| 67 | |
| 68 | |
| 69 | def auto_detect_upload_port(expected_environment: str | None) -> ComportResult: |
| 70 | """Auto-detect the upload port from available serial ports. |
| 71 | |
| 72 | Only considers USB devices - filters out Bluetooth and other non-USB ports. |
| 73 | Returns a structured result with success status, selected port, error details, |
| 74 | and all scanned ports for diagnostics. |
| 75 | |
| 76 | Prefers common ESP32/Arduino USB-to-serial chips: |
| 77 | - CP2102/CP210x (Silicon Labs) |
| 78 | - CH340/CH341 (WCH) |
| 79 | - FTDI chips |
| 80 | - Generic USB-Serial converters |
| 81 | |
| 82 | Returns: |
| 83 | ComportResult with detection status and diagnostics |
| 84 | """ |
| 85 | try: |
| 86 | # Scan all available COM ports |
| 87 | all_ports = list(serial.tools.list_ports.comports()) |
| 88 | except KeyboardInterrupt as ki: |
| 89 | handle_keyboard_interrupt(ki) |
| 90 | raise |
| 91 | except Exception as e: |
| 92 | # Failed to scan ports - return error result |
| 93 | return ComportResult( |
| 94 | ok=False, |
| 95 | selected_port=None, |
| 96 | error_message=f"Failed to scan COM ports: {e}", |
| 97 | all_ports=[], |
| 98 | ) |
| 99 | |
| 100 | if not all_ports: |
| 101 | # No ports found at all |
| 102 | return ComportResult( |
| 103 | ok=False, |
| 104 | selected_port=None, |
| 105 | error_message="No serial ports detected on system", |
| 106 | all_ports=[], |
| 107 | ) |
| 108 | |
| 109 | # Filter to USB devices only (exclude Bluetooth, ACPI, etc.) |
| 110 | # USB devices have "USB" in their hwid (hardware ID) string |
| 111 | usb_ports = [port for port in all_ports if "USB" in port.hwid.upper()] |
| 112 | |
| 113 | if not usb_ports: |
| 114 | # No USB ports found - only non-USB ports available |
| 115 | non_usb_types: set[str] = set() |
| 116 | for port in all_ports: |
| 117 | if "BTHENUM" in port.hwid.upper(): |
| 118 | non_usb_types.add("Bluetooth") |
| 119 | elif "ACPI" in port.hwid.upper(): |
| 120 | non_usb_types.add("ACPI") |
| 121 | else: |
| 122 | non_usb_types.add("other") |
| 123 | |
| 124 | types_str = ", ".join(sorted(non_usb_types)) |
| 125 | return ComportResult( |
| 126 | ok=False, |