serialselect.py
2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Module to choose and open a serial port
# Written as a telemetry tool by:
# The UoN Robot Wars Project, 2018
def selectserial():
import platform
import serial
import os
devpatterns = ['ttyACM', 'ttyUSB', 'rfcomm']
targetdevs = []
if platform.system()=='Windows':
com_ports = ['COM%s' % (i + 1) for i in range(256)]
for port in com_ports:
try:
s = serial.Serial(port)
s.close()
targetdevs.append(port)
except (OSError, serial.SerialException):
pass
os='Windows' #may be useful
else:
alldevs = os.listdir("/dev/")
targetdevs = []
for dev in alldevs:
for pattern in devpatterns:
if pattern in dev:
targetdevs.append("/dev/" + dev)
os='Other' #may be useful
if len(targetdevs) == 0:
return "Sorry, no serial devices found."
elif len(targetdevs) > 1:
print("Found multiple serial devices: ")
for i, dev in enumerate(targetdevs):
print(" " + str(i) + ": " + dev)
while True:
try:
selection = int(input("Please enter your selection (as a digit):\n > "))
if selection >= 0 and selection < len(targetdevs):
break
except KeyboardInterrupt:
sys.exit()
except:
print("Choice unrecognised: please try again:")
else:
if os=='Windows':
print("Only found one likely serial device: " + targetdevs[0])
else:
print("Only found one likely serial device: " + targetdevs[0])
selection = 0
serialport=targetdevs[selection]
try:
datafeed = serial.Serial(
port=serialport,
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
print("Sucessfully opened " + serialport + " as data source!")
return datafeed
except Exception as e:
return str(e)