Merge branch '2.0.x-maintenance' into master-merge-commit
[ExpressLRS.git] / src / python / serials_find.py
blobc9634b2bb1e4f6dffca823ac5439e5dded7a4756
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 else:
45 raise Exception('Unsupported platform')
47 for port in ports:
48 try:
49 s = serial.Serial(port)
50 s.close()
51 result.append(port)
52 except (OSError, serial.SerialException) as error:
53 if "permission denied" in str(error).lower():
54 raise Exception("You don't have persmission to use serial port!")
55 pass
56 result.reverse()
57 return result
59 def get_serial_port(debug=True):
60 result = serial_ports()
61 if debug:
62 print()
63 print("Detected the following serial ports on this system:")
64 for port in result:
65 print(" %s" % port)
66 print()
68 if len(result) == 0:
69 raise Exception('No valid serial port detected or port already open')
71 return result[0]
73 if __name__ == '__main__':
74 results = get_serial_port(True)
75 print("Found: %s" % (results, ))