Chris Liechti | ad11d17 | 2015-10-18 01:02:17 +0200 | [diff] [blame] | 1 | #! python |
| 2 | # |
| 3 | # Python Serial Port Extension for Win32, Linux, BSD, Jython |
| 4 | # see __init__.py |
| 5 | # |
| 6 | # This module implements a special URL handler that allows selection of |
| 7 | # alternate implementation provided by some backends. |
| 8 | # |
| 9 | # (C) 2015 Chris Liechti <cliechti@gmx.net> |
| 10 | # |
| 11 | # SPDX-License-Identifier: BSD-3-Clause |
| 12 | # |
| 13 | # URL format: alt://port[?option[=value][&option[=value]]] |
| 14 | # options: |
| 15 | # - class=X used class named X instead of Serial |
| 16 | # |
| 17 | # example: |
| 18 | # use poll based implementation on Posix (Linux): |
| 19 | # python -m serial.tools.miniterm alt:///dev/ttyUSB0?class=PosixPollSerial |
| 20 | |
| 21 | import sys |
| 22 | import time |
| 23 | |
| 24 | import serial |
| 25 | |
| 26 | try: |
| 27 | import urlparse |
| 28 | except ImportError: |
| 29 | import urllib.parse as urlparse |
| 30 | |
| 31 | |
| 32 | def serial_class_for_url(url): |
| 33 | """extract host and port from an URL string""" |
| 34 | parts = urlparse.urlsplit(url) |
| 35 | if parts.scheme != 'alt': |
| 36 | raise serial.SerialException('expected a string in the form "alt://port[?option[=value][&option[=value]]]": not starting with alt:// (%r)' % (parts.scheme,)) |
| 37 | class_name = 'Serial' |
| 38 | try: |
| 39 | for option, values in urlparse.parse_qs(parts.query, True).items(): |
| 40 | if option == 'class': |
| 41 | class_name = values[0] |
| 42 | else: |
| 43 | raise ValueError('unknown option: %r' % (option,)) |
| 44 | except ValueError as e: |
| 45 | raise serial.SerialException('expected a string in the form "alt://port[?option[=value][&option[=value]]]": %s' % e) |
| 46 | return (''.join([parts.netloc, parts.path]), getattr(serial, class_name)) |
| 47 | |
| 48 | # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| 49 | if __name__ == '__main__': |
| 50 | s = serial_for_url('alt:///dev/ttyS0?class=PosixPollSerial') |
| 51 | print(s) |