Increase maximum number of Lua params (#2207)
[ExpressLRS.git] / src / python / serials_find.py
blob74baa17a6778ef929f7542f70f26b63ae89660de
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 else:
46 raise Exception('Unsupported platform')
48 for port in ports:
49 try:
50 s = serial.Serial(port)
51 s.close()
52 result.append(port)
53 except (OSError, serial.SerialException) as error:
54 if "permission denied" in str(error).lower():
55 raise Exception("You don't have persmission to use serial port!")
56 pass
57 result.reverse()
58 return result
60 def get_serial_port(debug=True):
61 result = serial_ports()
62 if debug:
63 print()
64 print("Detected the following serial ports on this system:")
65 for port in result:
66 print(" %s" % port)
67 print()
69 if len(result) == 0:
70 raise Exception('No valid serial port detected or port already open')
72 return result[0]
74 if __name__ == '__main__':
75 results = get_serial_port(True)
76 print("Found: %s" % (results, ))