|
| 1 | +import os |
1 | 2 | import time
|
2 | 3 | from pathlib import Path
|
3 | 4 |
|
| 5 | +from serial.tools import list_ports # Part of pyserial library |
| 6 | + |
4 | 7 |
|
5 | 8 | def find_available_ports():
|
6 |
| - ports = [] |
7 |
| - for path in Path("/dev").glob("tty*"): |
8 |
| - ports.append(str(path)) |
| 9 | + if os.name == "nt": # Windows |
| 10 | + # List COM ports using pyserial |
| 11 | + ports = [port.device for port in list_ports.comports()] |
| 12 | + else: # Linux/macOS |
| 13 | + # List /dev/tty* ports for Unix-based systems |
| 14 | + ports = [str(path) for path in Path("/dev").glob("tty*")] |
9 | 15 | return ports
|
10 | 16 |
|
11 | 17 |
|
12 | 18 | def find_port():
|
13 | 19 | print("Finding all available ports for the MotorsBus.")
|
14 | 20 | ports_before = find_available_ports()
|
15 |
| - print(ports_before) |
| 21 | + print("Ports before disconnecting:", ports_before) |
16 | 22 |
|
17 |
| - print("Remove the usb cable from your MotorsBus and press Enter when done.") |
18 |
| - input() |
| 23 | + print("Remove the USB cable from your MotorsBus and press Enter when done.") |
| 24 | + input() # Wait for user to disconnect the device |
19 | 25 |
|
20 |
| - time.sleep(0.5) |
| 26 | + time.sleep(0.5) # Allow some time for port to be released |
21 | 27 | ports_after = find_available_ports()
|
22 | 28 | ports_diff = list(set(ports_before) - set(ports_after))
|
23 | 29 |
|
24 | 30 | if len(ports_diff) == 1:
|
25 | 31 | port = ports_diff[0]
|
26 | 32 | print(f"The port of this MotorsBus is '{port}'")
|
27 |
| - print("Reconnect the usb cable.") |
| 33 | + print("Reconnect the USB cable.") |
28 | 34 | elif len(ports_diff) == 0:
|
29 | 35 | raise OSError(f"Could not detect the port. No difference was found ({ports_diff}).")
|
30 | 36 | else:
|
31 | 37 | raise OSError(f"Could not detect the port. More than one port was found ({ports_diff}).")
|
32 | 38 |
|
33 | 39 |
|
34 | 40 | if __name__ == "__main__":
|
35 |
| - # Helper to find the usb port associated to all your MotorsBus. |
| 41 | + # Helper to find the USB port associated with your MotorsBus. |
36 | 42 | find_port()
|
0 commit comments