Phase 3: STM32 Removal: Shared RX/TX parts (#3016)
[ExpressLRS.git] / src / python / serials_find.py
blob649ca0a4ce9f51224dc6f399e7978607662d900f
1 import serial
2 import sys, glob
5 def serial_ports():
6 """ Lists serial port names
8 :raises Exception:
9 On unsupported or unknown platforms
10 :returns:
11 A list of the serial ports available on the system
12 """
13 result = []
14 ports = []
16 try:
17 from serial.tools.list_ports import comports
18 if comports:
19 print(" ** Searching flight controllers **")
20 __ports = list(comports())
21 for port in __ports:
22 if (port.manufacturer and port.manufacturer in ['FTDI', 'Betaflight', ]) or \
23 (port.product and "STM32" in port.product) or (port.vid and port.vid == 0x0483):
24 print(" > FC found from '%s'" % port.device)
25 ports.append(port.device)
26 except ImportError:
27 pass
29 if not ports:
30 print(" ** No FC found, find all ports **")
32 platform = sys.platform.lower()
33 if platform.startswith('win'):
34 ports = ['COM%s' % (i + 1) for i in range(256)]
35 elif platform.startswith('linux') or platform.startswith('cygwin'):
36 # this excludes your current terminal "/dev/tty"
37 #ports = glob.glob('/dev/tty[A-Za-z]*')
38 # List all ttyACM* and ttyUSB* ports only
39 ports = glob.glob('/dev/ttyACM*')
40 ports.extend(glob.glob('/dev/ttyUSB*'))
41 elif platform.startswith('darwin'):
42 ports = glob.glob('/dev/tty.usbmodem*')
43 ports.extend(glob.glob('/dev/tty.SLAB*'))
44 ports.extend(glob.glob('/dev/tty.usbserial*'))
45 ports.extend(glob.glob('/dev/tty.wchusbserial*'))
46 else:
47 raise Exception('Unsupported platform')
49 for port in ports:
50 try:
51 s = serial.Serial(port)
52 s.close()
53 result.append(port)
54 except (OSError, serial.SerialException) as error:
55 if "permission denied" in str(error).lower():
56 raise Exception("You don't have permission to use serial port!")
57 pass
58 result.reverse()
59 return result
61 def get_serial_port(debug=True):
62 result = serial_ports()
63 if debug:
64 print()
65 print("Detected the following serial ports on this system:")
66 for port in result:
67 print(" %s" % port)
68 print()
70 if len(result) == 0:
71 raise Exception('No valid serial port detected or port already open')
73 return result[0]
75 if __name__ == '__main__':
76 results = get_serial_port(True)
77 print("Found: %s" % (results, ))