blob: 57c1c4e87f1ebfd2ae57b12fcf7a40fcac7689b7 [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)
44 return (''.join([parts.netloc, parts.path]), getattr(serial, class_name))
45
46# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
47if __name__ == '__main__':
48 s = serial_for_url('alt:///dev/ttyS0?class=PosixPollSerial')
49 print(s)