#!/usr/bin/env python3 """ identify_port.py Tool to identify a specific physical device's port name. 1. Lists all connected USB Serial devices. 2. Asks you to power down or unplug ONE device. 3. Tells you exactly which /dev/ttyUSBx port disappeared. """ import time import sys from serial.tools import list_ports class Colors: GREEN = '\033[92m' RED = '\033[91m' YELLOW = '\033[93m' BLUE = '\033[94m' RESET = '\033[0m' def get_current_ports(): """ Returns a set of all detected USB/ACM serial ports. We look for standard USB-to-Serial drivers. """ # Grab all ports that look like USB serial adapters ports = list(list_ports.grep("USB|ACM|CP210|FT232")) # Return a set of device paths (e.g. {'/dev/ttyUSB0', '/dev/ttyUSB1'}) return set(p.device for p in ports) def main(): print(f"{Colors.BLUE}{'='*60}{Colors.RESET}") print(f" USB Port Identifier") print(f"{Colors.BLUE}{'='*60}{Colors.RESET}") # 1. Initial Scan print("Scanning for connected devices...", end='', flush=True) initial_ports = get_current_ports() print(f" Found {len(initial_ports)} devices.") if not initial_ports: print(f"{Colors.RED}No USB serial devices found!{Colors.RESET}") sys.exit(1) # Print current list nicely sorted_ports = sorted(list(initial_ports)) print(f"\n{Colors.GREEN}Active Ports:{Colors.RESET}") for p in sorted_ports: print(f" - {p}") # 2. Prompt User print(f"\n{Colors.YELLOW}>>> ACTION REQUIRED: Power down (or unplug) the device you want to identify.{Colors.RESET}") input(f"{Colors.YELLOW}>>> Press ENTER once the device is off...{Colors.RESET}") # 3. Final Scan print("Rescanning...", end='', flush=True) # Give the OS a moment to deregister the device if it was just pulled time.sleep(1.0) final_ports = get_current_ports() print(" Done.") # 4. Calculate Difference removed_ports = initial_ports - final_ports added_ports = final_ports - initial_ports print(f"\n{Colors.BLUE}{'='*60}{Colors.RESET}") print(f" Result") print(f"{Colors.BLUE}{'='*60}{Colors.RESET}") if len(removed_ports) == 1: target = list(removed_ports)[0] print(f"The device you powered down was: {Colors.RED}{target}{Colors.RESET}") elif len(removed_ports) > 1: print(f"{Colors.RED}Multiple ports disappeared!{Colors.RESET}") for p in removed_ports: print(f" - {p}") elif len(added_ports) > 0: print(f"{Colors.YELLOW}No ports removed, but new ones appeared?{Colors.RESET}") for p in added_ports: print(f" + {p}") else: print(f"{Colors.YELLOW}No changes detected. Did you power it down?{Colors.RESET}") if __name__ == '__main__': main()