blob: f7bf2e7af859fb893e70590693b28ad28eb09035 [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>
cliechti6fa19112011-08-19 01:50:49 +000010# this is distributed under a free software license, see license.txt
11#
12# URL format: hwgrep://regexp
13
14import serial
15import serial.tools.list_ports
16
Chris Liechti5fe3bdd2015-08-07 00:02:44 +020017try:
18 basestring
19except NameError:
20 basestring = str # python 3
cliechti6fa19112011-08-19 01:50:49 +000021
Chris Liechti5fe3bdd2015-08-07 00:02:44 +020022class Serial(serial.Serial):
23 """Just inherit the native Serial port implementation and patch the port property."""
24
25 @serial.Serial.port.setter
26 def port(self, value):
cliechti6fa19112011-08-19 01:50:49 +000027 """translate port name before storing it"""
cliechti9a3809e2011-08-19 23:43:10 +000028 if isinstance(value, basestring) and value.startswith('hwgrep://'):
Chris Liechti5fe3bdd2015-08-07 00:02:44 +020029 serial.Serial.port.__set__(self, self.fromURL(value))
cliechti6fa19112011-08-19 01:50:49 +000030 else:
Chris Liechti5fe3bdd2015-08-07 00:02:44 +020031 serial.Serial.port.__set__(self, value)
cliechti6fa19112011-08-19 01:50:49 +000032
33 def fromURL(self, url):
34 """extract host and port from an URL string"""
35 if url.lower().startswith("hwgrep://"): url = url[9:]
36 # use a for loop to get the 1st element from the generator
37 for port, desc, hwid in serial.tools.list_ports.grep(url):
38 return port
39 else:
cliechti9a3809e2011-08-19 23:43:10 +000040 raise serial.SerialException('no ports found matching regexp %r' % (url,))
cliechti6fa19112011-08-19 01:50:49 +000041
cliechti6fa19112011-08-19 01:50:49 +000042# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
43if __name__ == '__main__':
44 #~ s = Serial('hwgrep://ttyS0')
45 s = Serial(None)
46 s.port = 'hwgrep://ttyS0'
Chris Liechti68340d72015-08-03 14:15:48 +020047 print(s)
cliechti6fa19112011-08-19 01:50:49 +000048