serialselect.py
2.21 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
# Module to choose and open a serial port
# Written as a telemetry tool by:
# The UoN Robot Wars Project, 2018
def selectserial():
"""Cross-platform function to find appropriate serial ports, query the user if necessary, and open one of them"""
import platform
import serial
import os
import easygui
import logging
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)
# Temporarily broadened exception in attempt to make this work on uni PCs
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:
logging.info("No serial device found.")
return None
elif len(targetdevs) > 1:
logging.info("Found multiple serial devices: ")
for i, dev in enumerate(targetdevs):
logging.info(" " + str(i) + ": " + dev)
message = "Please choose a serial port to recieve data through:"
title = "Found multiple serial ports!"
serialport = easygui.choicebox(message, title, targetdevs)
if serialport == None:
logging.info("User cancelled selection dialogue")
return None
else:
logging.info("Only found one likely serial device: " + targetdevs[0])
serialport = targetdevs[0]
try:
datafeed = serial.Serial(
port=serialport,
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
logging.info("Sucessfully opened " + serialport + " as data source!")
return datafeed
except Exception as e:
logging.critical(str(e))
return None