|
| 1 | +import sys |
| 2 | +import glob |
| 3 | + |
| 4 | +try: |
| 5 | + import queue |
| 6 | +except ImportError: |
| 7 | + import Queue as queue |
| 8 | + |
| 9 | +import serial |
| 10 | + |
| 11 | + |
| 12 | +# From https://stackoverflow.com/questions/6517953/clear-all-items-from-the-queue |
| 13 | +class CustomQueue(queue.Queue): |
| 14 | + """ |
| 15 | + A custom queue subclass that provides a :meth:`clear` method. |
| 16 | + """ |
| 17 | + |
| 18 | + def clear(self): |
| 19 | + """ |
| 20 | + Clears all items from the queue. |
| 21 | + """ |
| 22 | + |
| 23 | + with self.mutex: |
| 24 | + unfinished = self.unfinished_tasks - len(self.queue) |
| 25 | + if unfinished <= 0: |
| 26 | + if unfinished < 0: |
| 27 | + raise ValueError('task_done() called too many times') |
| 28 | + self.all_tasks_done.notify_all() |
| 29 | + self.unfinished_tasks = unfinished |
| 30 | + self.queue.clear() |
| 31 | + self.not_full.notify_all() |
| 32 | + |
| 33 | + |
| 34 | +# From https://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python |
| 35 | +def get_serial_ports(): |
| 36 | + """ |
| 37 | + Lists serial ports. |
| 38 | + :return: ([str]) A list of available serial ports |
| 39 | + """ |
| 40 | + if sys.platform.startswith('win'): |
| 41 | + ports = ['COM%s' % (i + 1) for i in range(256)] |
| 42 | + elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): |
| 43 | + # this excludes your current terminal "/dev/tty" |
| 44 | + ports = glob.glob('/dev/tty[A-Za-z]*') |
| 45 | + elif sys.platform.startswith('darwin'): |
| 46 | + ports = glob.glob('/dev/tty.*') |
| 47 | + else: |
| 48 | + raise EnvironmentError('Unsupported platform') |
| 49 | + |
| 50 | + results = [] |
| 51 | + for port in ports: |
| 52 | + try: |
| 53 | + s = serial.Serial(port) |
| 54 | + s.close() |
| 55 | + results.append(port) |
| 56 | + except (OSError, serial.SerialException): |
| 57 | + pass |
| 58 | + return results |
| 59 | + |
| 60 | + |
| 61 | +def open_serial_port(serial_port=None, baudrate=115200, timeout=0, write_timeout=0): |
| 62 | + """ |
| 63 | + Try to open serial port with Arduino |
| 64 | + If not port is specified, it will be automatically detected |
| 65 | + :param serial_port: (str) |
| 66 | + :param baudrate: (int) |
| 67 | + :param timeout: (int) None -> blocking mode |
| 68 | + :param write_timeout: (int) |
| 69 | + :return: (Serial Object) |
| 70 | + """ |
| 71 | + # Open serial port (for communication with Arduino) |
| 72 | + if serial_port is None: |
| 73 | + serial_port = get_serial_ports()[-1] |
| 74 | + # timeout=0 non-blocking mode, return immediately in any case, returning zero or more, |
| 75 | + # up to the requested number of bytes |
| 76 | + return serial.Serial(port=serial_port, baudrate=baudrate, timeout=timeout, writeTimeout=write_timeout) |
0 commit comments