# 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)