blob: 6c818132eea2e86d9cca1329577adaa88efe9537 [file] [log] [blame]
Chris Liechtiad11d172015-10-18 01:02:17 +02001#! python
2#
Chris Liechti3e02f702015-12-16 23:06:04 +01003# This module implements a special URL handler that allows selecting an
Chris Liechtiad11d172015-10-18 01:02:17 +02004# alternate implementation provided by some backends.
5#
Chris Liechti3e02f702015-12-16 23:06:04 +01006# This file is part of pySerial. https://github.com/pyserial/pyserial
Chris Liechtiad11d172015-10-18 01:02:17 +02007# (C) 2015 Chris Liechti <cliechti@gmx.net>
8#
9# SPDX-License-Identifier: BSD-3-Clause
10#
11# URL format: alt://port[?option[=value][&option[=value]]]
12# options:
13# - class=X used class named X instead of Serial
14#
15# example:
16# use poll based implementation on Posix (Linux):
17# python -m serial.tools.miniterm alt:///dev/ttyUSB0?class=PosixPollSerial
18
19import sys
20import time
21
22import serial
23
24try:
25 import urlparse
26except ImportError:
27 import urllib.parse as urlparse
28
29
30def serial_class_for_url(url):
31 """extract host and port from an URL string"""
32 parts = urlparse.urlsplit(url)
33 if parts.scheme != 'alt':
34 raise serial.SerialException('expected a string in the form "alt://port[?option[=value][&option[=value]]]": not starting with alt:// (%r)' % (parts.scheme,))
35 class_name = 'Serial'
36 try:
37 for option, values in urlparse.parse_qs(parts.query, True).items():
38 if option == 'class':
39 class_name = values[0]
40 else:
41 raise ValueError('unknown option: %r' % (option,))
42 except ValueError as e:
43 raise serial.SerialException('expected a string in the form "alt://port[?option[=value][&option[=value]]]": %s' % e)
Chris Liechti7f4b4ee2016-01-16 23:21:42 +010044 if not hasattr(serial, class_name):
45 raise ValueError('unknown class: %r' % (class_name,))
46 cls = getattr(serial, class_name)
47 if not issubclass(cls, serial.Serial):
48 raise ValueError('class %r is not an instance of Serial' % (class_name,))
49 return (''.join([parts.netloc, parts.path]), cls)
Chris Liechtiad11d172015-10-18 01:02:17 +020050
51# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
52if __name__ == '__main__':
53 s = serial_for_url('alt:///dev/ttyS0?class=PosixPollSerial')
54 print(s)