blob: 90626ff134a8871ebc54b6d083ffc89bc7a3cc2f [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 Liechti5fe3bdd2015-08-07 00:02:44 +020023class Serial(serial.Serial):
24 """Just inherit the native Serial port implementation and patch the port property."""
25
26 @serial.Serial.port.setter
27 def port(self, value):
cliechti6fa19112011-08-19 01:50:49 +000028 """translate port name before storing it"""
cliechti9a3809e2011-08-19 23:43:10 +000029 if isinstance(value, basestring) and value.startswith('hwgrep://'):
Chris Liechti3ad62fb2015-08-29 21:53:32 +020030 serial.Serial.port.__set__(self, self.from_url(value))
cliechti6fa19112011-08-19 01:50:49 +000031 else:
Chris Liechti5fe3bdd2015-08-07 00:02:44 +020032 serial.Serial.port.__set__(self, value)
cliechti6fa19112011-08-19 01:50:49 +000033
Chris Liechti3ad62fb2015-08-29 21:53:32 +020034 def from_url(self, url):
cliechti6fa19112011-08-19 01:50:49 +000035 """extract host and port from an URL string"""
Chris Liechtifbdd8a02015-08-09 02:37:45 +020036 if url.lower().startswith("hwgrep://"):
37 url = url[9:]
cliechti6fa19112011-08-19 01:50:49 +000038 # use a for loop to get the 1st element from the generator
39 for port, desc, hwid in serial.tools.list_ports.grep(url):
40 return port
41 else:
cliechti9a3809e2011-08-19 23:43:10 +000042 raise serial.SerialException('no ports found matching regexp %r' % (url,))
cliechti6fa19112011-08-19 01:50:49 +000043
cliechti6fa19112011-08-19 01:50:49 +000044# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
45if __name__ == '__main__':
46 #~ s = Serial('hwgrep://ttyS0')
47 s = Serial(None)
48 s.port = 'hwgrep://ttyS0'
Chris Liechti68340d72015-08-03 14:15:48 +020049 print(s)
cliechti6fa19112011-08-19 01:50:49 +000050