blob: af1646a514b378bf76ecd9055f9fc380570ba299 [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
Chris Liechtiad11d172015-10-18 01:02:17 +020019import serial
20
21try:
22 import urlparse
23except ImportError:
24 import urllib.parse as urlparse
25
26
27def serial_class_for_url(url):
28 """extract host and port from an URL string"""
29 parts = urlparse.urlsplit(url)
30 if parts.scheme != 'alt':
31 raise serial.SerialException('expected a string in the form "alt://port[?option[=value][&option[=value]]]": not starting with alt:// (%r)' % (parts.scheme,))
32 class_name = 'Serial'
33 try:
34 for option, values in urlparse.parse_qs(parts.query, True).items():
35 if option == 'class':
36 class_name = values[0]
37 else:
38 raise ValueError('unknown option: %r' % (option,))
39 except ValueError as e:
40 raise serial.SerialException('expected a string in the form "alt://port[?option[=value][&option[=value]]]": %s' % e)
Chris Liechti7f4b4ee2016-01-16 23:21:42 +010041 if not hasattr(serial, class_name):
42 raise ValueError('unknown class: %r' % (class_name,))
43 cls = getattr(serial, class_name)
44 if not issubclass(cls, serial.Serial):
45 raise ValueError('class %r is not an instance of Serial' % (class_name,))
46 return (''.join([parts.netloc, parts.path]), cls)
Chris Liechtiad11d172015-10-18 01:02:17 +020047
48# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
49if __name__ == '__main__':
Chris Liechtib10daf42016-01-26 00:27:10 +010050 s = serial.serial_for_url('alt:///dev/ttyS0?class=PosixPollSerial')
Chris Liechtiad11d172015-10-18 01:02:17 +020051 print(s)