blob: 3a7a0e0c737e9efd32041ca9c1ef3da38bc018b9 [file] [log] [blame]
Chris Liechtiad11d172015-10-18 01:02:17 +02001#! 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
21import sys
22import time
23
24import serial
25
26try:
27 import urlparse
28except ImportError:
29 import urllib.parse as urlparse
30
31
32def 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# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
49if __name__ == '__main__':
50 s = serial_for_url('alt:///dev/ttyS0?class=PosixPollSerial')
51 print(s)