blob: e184ec588ef6dce277fdf0b78d7b743e9fdc5b91 [file] [log] [blame]
cliechti6fa19112011-08-19 01:50:49 +00001#! 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 uses the port listing to
7# find ports by searching the string descriptions.
8#
Chris Liechti5fe3bdd2015-08-07 00:02:44 +02009# (C) 2011-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +020010#
11# SPDX-License-Identifier: BSD-3-Clause
cliechti6fa19112011-08-19 01:50:49 +000012#
13# URL format: hwgrep://regexp
14
15import serial
16import serial.tools.list_ports
17
Chris Liechti5fe3bdd2015-08-07 00:02:44 +020018try:
19 basestring
20except NameError:
21 basestring = str # python 3
cliechti6fa19112011-08-19 01:50:49 +000022
Chris Liechti033f17c2015-08-30 21:28:04 +020023
Chris Liechti5fe3bdd2015-08-07 00:02:44 +020024class Serial(serial.Serial):
25 """Just inherit the native Serial port implementation and patch the port property."""
26
27 @serial.Serial.port.setter
28 def port(self, value):
cliechti6fa19112011-08-19 01:50:49 +000029 """translate port name before storing it"""
cliechti9a3809e2011-08-19 23:43:10 +000030 if isinstance(value, basestring) and value.startswith('hwgrep://'):
Chris Liechti3ad62fb2015-08-29 21:53:32 +020031 serial.Serial.port.__set__(self, self.from_url(value))
cliechti6fa19112011-08-19 01:50:49 +000032 else:
Chris Liechti5fe3bdd2015-08-07 00:02:44 +020033 serial.Serial.port.__set__(self, value)
cliechti6fa19112011-08-19 01:50:49 +000034
Chris Liechti3ad62fb2015-08-29 21:53:32 +020035 def from_url(self, url):
cliechti6fa19112011-08-19 01:50:49 +000036 """extract host and port from an URL string"""
Chris Liechtifbdd8a02015-08-09 02:37:45 +020037 if url.lower().startswith("hwgrep://"):
38 url = url[9:]
cliechti6fa19112011-08-19 01:50:49 +000039 # use a for loop to get the 1st element from the generator
40 for port, desc, hwid in serial.tools.list_ports.grep(url):
41 return port
42 else:
cliechti9a3809e2011-08-19 23:43:10 +000043 raise serial.SerialException('no ports found matching regexp %r' % (url,))
cliechti6fa19112011-08-19 01:50:49 +000044
cliechti6fa19112011-08-19 01:50:49 +000045# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
46if __name__ == '__main__':
cliechti6fa19112011-08-19 01:50:49 +000047 s = Serial(None)
48 s.port = 'hwgrep://ttyS0'
Chris Liechti68340d72015-08-03 14:15:48 +020049 print(s)