cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 1 | #! 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 | # |
| 9 | # (C) 2011 Chris Liechti <cliechti@gmx.net> |
| 10 | # this is distributed under a free software license, see license.txt |
| 11 | # |
| 12 | # URL format: hwgrep://regexp |
| 13 | |
| 14 | import serial |
| 15 | import serial.tools.list_ports |
| 16 | |
| 17 | class Serial(serial.Serial): |
| 18 | """Just inherit the native Serial port implementation and patch the open function.""" |
| 19 | |
| 20 | def setPort(self, value): |
| 21 | """translate port name before storing it""" |
cliechti | 9a3809e | 2011-08-19 23:43:10 +0000 | [diff] [blame] | 22 | if isinstance(value, basestring) and value.startswith('hwgrep://'): |
cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 23 | serial.Serial.setPort(self, self.fromURL(value)) |
| 24 | else: |
| 25 | serial.Serial.setPort(self, value) |
| 26 | |
| 27 | def fromURL(self, url): |
| 28 | """extract host and port from an URL string""" |
| 29 | if url.lower().startswith("hwgrep://"): url = url[9:] |
| 30 | # use a for loop to get the 1st element from the generator |
| 31 | for port, desc, hwid in serial.tools.list_ports.grep(url): |
| 32 | return port |
| 33 | else: |
cliechti | 9a3809e | 2011-08-19 23:43:10 +0000 | [diff] [blame] | 34 | raise serial.SerialException('no ports found matching regexp %r' % (url,)) |
cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 35 | |
| 36 | # override property |
| 37 | port = property(serial.Serial.getPort, setPort, doc="Port setting") |
| 38 | |
| 39 | # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| 40 | if __name__ == '__main__': |
| 41 | #~ s = Serial('hwgrep://ttyS0') |
| 42 | s = Serial(None) |
| 43 | s.port = 'hwgrep://ttyS0' |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 44 | print(s) |
cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 45 | |