blob: ef98ea7f3d7b88ffa407a9ad92644c2ca1bd9038 [file] [log] [blame]
cliechti6fa19112011-08-19 01:50:49 +00001#! python
2#
cliechti6fa19112011-08-19 01:50:49 +00003# This module implements a special URL handler that uses the port listing to
4# find ports by searching the string descriptions.
5#
Chris Liechti3e02f702015-12-16 23:06:04 +01006# This file is part of pySerial. https://github.com/pyserial/pyserial
Chris Liechti5fe3bdd2015-08-07 00:02:44 +02007# (C) 2011-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +02008#
9# SPDX-License-Identifier: BSD-3-Clause
cliechti6fa19112011-08-19 01:50:49 +000010#
11# URL format: hwgrep://regexp
12
13import serial
14import serial.tools.list_ports
15
Chris Liechti5fe3bdd2015-08-07 00:02:44 +020016try:
17 basestring
18except NameError:
19 basestring = str # python 3
cliechti6fa19112011-08-19 01:50:49 +000020
Chris Liechti033f17c2015-08-30 21:28:04 +020021
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 Liechti3ad62fb2015-08-29 21:53:32 +020029 serial.Serial.port.__set__(self, self.from_url(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
Chris Liechti3ad62fb2015-08-29 21:53:32 +020033 def from_url(self, url):
cliechti6fa19112011-08-19 01:50:49 +000034 """extract host and port from an URL string"""
Chris Liechtifbdd8a02015-08-09 02:37:45 +020035 if url.lower().startswith("hwgrep://"):
36 url = url[9:]
cliechti6fa19112011-08-19 01:50:49 +000037 # use a for loop to get the 1st element from the generator
38 for port, desc, hwid in serial.tools.list_ports.grep(url):
39 return port
40 else:
cliechti9a3809e2011-08-19 23:43:10 +000041 raise serial.SerialException('no ports found matching regexp %r' % (url,))
cliechti6fa19112011-08-19 01:50:49 +000042
cliechti6fa19112011-08-19 01:50:49 +000043# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
44if __name__ == '__main__':
cliechti6fa19112011-08-19 01:50:49 +000045 s = Serial(None)
46 s.port = 'hwgrep://ttyS0'
Chris Liechti68340d72015-08-03 14:15:48 +020047 print(s)