From 3b3bee8c8749d174c829709d01cabb7c62832132 Mon Sep 17 00:00:00 2001 From: Kienan Stewart Date: Sat, 13 Dec 2014 12:58:34 -0500 Subject: [PATCH] listing serial ports, cleaned up exception return in threaded reader and proper port closing when the loop breaks --- temp_log.py | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/temp_log.py b/temp_log.py index a8e8cfb..d245daf 100755 --- a/temp_log.py +++ b/temp_log.py @@ -1,5 +1,7 @@ #! /usr/bin/env python +import glob import io +import platform import Queue import serial import sys @@ -8,6 +10,28 @@ import time defaultSerialPort = '/dev/ttyACM0' defaultVersion = 0 +def list_serial_ports(): + """Lists serial ports, taken from http://stackoverflow.com/questions/11303850/what-is-the-cross-platform-method-of-enumerating-serial-ports-in-python-includi""" + system_name = platform.system() + if system_name == "Windows": + # Scan for available ports. + available = [] + for i in range(256): + try: + s = serial.Serial(i) + available.append(i) + s.close() + except serial.SerialException: + pass + return available + elif system_name == "Darwin": + # Mac + return glob.glob('/dev/tty*') + glob.glob('/dev/cu*') + else: + # Assume Linux or something else + return glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*') + + class ParseException(Exception): """Parser Exceptions""" pass @@ -29,10 +53,13 @@ def parse_line(line, version = defaultVersion): def threaded_reader(source, dataQueue, commandQueue): - import kivy.logger - ser = serial.Serial(source, baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) - sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser)) - ser.isOpen() + try: + ser = serial.Serial(source, baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) + sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser)) + ser.isOpen() + except Exception, e: + dataQueue.put({'exception' : str(e)}) + return buffer = '' runTime = '' cmd = '' @@ -47,12 +74,12 @@ def threaded_reader(source, dataQueue, commandQueue): data = parse_line(ser.readline(), defaultVersion) runTime = time.time() except Exception, e: - kivy.logger.Logger.exception(e) - continue + dataQueue.put({'exception' : str(e)}) if data and runTime: item = {'time' : runTime, 'data' : data} - kivy.logger.Logger.debug(str(item)) dataQueue.put(item) + # close out the fds + ser.close() def main(args = sys.argv):