summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorChris Liechti <cliechti@gmx.net>2015-10-18 01:02:17 +0200
committerChris Liechti <cliechti@gmx.net>2015-10-18 01:02:17 +0200
commitad11d17d1ec44a5b3ff9eafa1732a1380d138cf9 (patch)
treed82e24eaa70f139a5916a6b68a7f66973c8f8dc5
parent4cf5470f6eefba1a2c61ee269b6b1a1097343927 (diff)
downloadpyserial-git-ad11d17d1ec44a5b3ff9eafa1732a1380d138cf9.tar.gz
serial_for_url: add new protocol that allows the selection of the Serial class
E.g. the posix platform has more than one implmenentation. This protocol now allows to select them without changing the application (well, if it's already using serial_for_url)
-rw-r--r--serial/urlhandler/protocol_alt.py51
1 files changed, 51 insertions, 0 deletions
diff --git a/serial/urlhandler/protocol_alt.py b/serial/urlhandler/protocol_alt.py
new file mode 100644
index 0000000..3a7a0e0
--- /dev/null
+++ b/serial/urlhandler/protocol_alt.py
@@ -0,0 +1,51 @@
+#! python
+#
+# Python Serial Port Extension for Win32, Linux, BSD, Jython
+# see __init__.py
+#
+# This module implements a special URL handler that allows selection of
+# alternate implementation provided by some backends.
+#
+# (C) 2015 Chris Liechti <cliechti@gmx.net>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+#
+# URL format: alt://port[?option[=value][&option[=value]]]
+# options:
+# - class=X used class named X instead of Serial
+#
+# example:
+# use poll based implementation on Posix (Linux):
+# python -m serial.tools.miniterm alt:///dev/ttyUSB0?class=PosixPollSerial
+
+import sys
+import time
+
+import serial
+
+try:
+ import urlparse
+except ImportError:
+ import urllib.parse as urlparse
+
+
+def serial_class_for_url(url):
+ """extract host and port from an URL string"""
+ parts = urlparse.urlsplit(url)
+ if parts.scheme != 'alt':
+ raise serial.SerialException('expected a string in the form "alt://port[?option[=value][&option[=value]]]": not starting with alt:// (%r)' % (parts.scheme,))
+ class_name = 'Serial'
+ try:
+ for option, values in urlparse.parse_qs(parts.query, True).items():
+ if option == 'class':
+ class_name = values[0]
+ else:
+ raise ValueError('unknown option: %r' % (option,))
+ except ValueError as e:
+ raise serial.SerialException('expected a string in the form "alt://port[?option[=value][&option[=value]]]": %s' % e)
+ return (''.join([parts.netloc, parts.path]), getattr(serial, class_name))
+
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+if __name__ == '__main__':
+ s = serial_for_url('alt:///dev/ttyS0?class=PosixPollSerial')
+ print(s)