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 | # |
Chris Liechti | 5fe3bdd | 2015-08-07 00:02:44 +0200 | [diff] [blame] | 9 | # (C) 2011-2015 Chris Liechti <cliechti@gmx.net> |
cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 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 | |
Chris Liechti | 5fe3bdd | 2015-08-07 00:02:44 +0200 | [diff] [blame] | 17 | try: |
| 18 | basestring |
| 19 | except NameError: |
| 20 | basestring = str # python 3 |
cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 21 | |
Chris Liechti | 5fe3bdd | 2015-08-07 00:02:44 +0200 | [diff] [blame] | 22 | class 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): |
cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 27 | """translate port name before storing it""" |
cliechti | 9a3809e | 2011-08-19 23:43:10 +0000 | [diff] [blame] | 28 | if isinstance(value, basestring) and value.startswith('hwgrep://'): |
Chris Liechti | 5fe3bdd | 2015-08-07 00:02:44 +0200 | [diff] [blame] | 29 | serial.Serial.port.__set__(self, self.fromURL(value)) |
cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 30 | else: |
Chris Liechti | 5fe3bdd | 2015-08-07 00:02:44 +0200 | [diff] [blame] | 31 | serial.Serial.port.__set__(self, value) |
cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 32 | |
| 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: |
cliechti | 9a3809e | 2011-08-19 23:43:10 +0000 | [diff] [blame] | 40 | raise serial.SerialException('no ports found matching regexp %r' % (url,)) |
cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 41 | |
cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 42 | # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| 43 | if __name__ == '__main__': |
| 44 | #~ s = Serial('hwgrep://ttyS0') |
| 45 | s = Serial(None) |
| 46 | s.port = 'hwgrep://ttyS0' |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 47 | print(s) |
cliechti | 6fa1911 | 2011-08-19 01:50:49 +0000 | [diff] [blame] | 48 | |