blob: 872080d2344d2a7232b92020842b7a01d86e0151 [file] [log] [blame]
cliechtid6bf52c2003-10-01 02:28:12 +00001#! python
cliechtid6bf52c2003-10-01 02:28:12 +00002#
Chris Liechti3e02f702015-12-16 23:06:04 +01003# Base class and support functions used by various backends.
4#
5# This file is part of pySerial. https://github.com/pyserial/pyserial
Chris Liechti06ed4a52016-09-03 23:53:12 +02006# (C) 2001-2016 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +02007#
8# SPDX-License-Identifier: BSD-3-Clause
cliechtid6bf52c2003-10-01 02:28:12 +00009
Chris Liechtief6b7b42015-08-06 22:19:26 +020010import io
Chris Liechticf29a352015-10-23 22:03:40 +020011import time
cliechtic323f1f2010-07-22 00:14:26 +000012
cliechti38077122013-10-16 02:57:27 +000013# ``memoryview`` was introduced in Python 2.7 and ``bytes(some_memoryview)``
14# isn't returning the contents (very unfortunate). Therefore we need special
15# cases and test for it. Ensure that there is a ``memoryview`` object for older
16# Python versions. This is easier than making every test dependent on its
17# existence.
18try:
19 memoryview
20except (NameError, AttributeError):
Chris Liechtia83408a2016-05-23 22:18:43 +020021 # implementation does not matter as we do not really use it.
cliechti38077122013-10-16 02:57:27 +000022 # it just must not inherit from something else we might care for.
Chris Liechti409e10b2016-02-10 22:40:34 +010023 class memoryview(object): # pylint: disable=redefined-builtin,invalid-name
cliechti38077122013-10-16 02:57:27 +000024 pass
25
Chris Liechti4a790ad2015-09-09 17:12:52 +020026try:
27 unicode
28except (NameError, AttributeError):
Chris Liechti409e10b2016-02-10 22:40:34 +010029 unicode = str # for Python 3, pylint: disable=redefined-builtin,invalid-name
Chris Liechti4a790ad2015-09-09 17:12:52 +020030
Chris Liechtibf9e3182016-04-22 21:31:09 +020031try:
Chris Liechtif41b4592016-05-11 15:11:27 +020032 basestring
Chris Liechtibf9e3182016-04-22 21:31:09 +020033except (NameError, AttributeError):
Chris Liechtif41b4592016-05-11 15:11:27 +020034 basestring = (str,) # for Python 3, pylint: disable=redefined-builtin,invalid-name
Chris Liechtibf9e3182016-04-22 21:31:09 +020035
cliechti38077122013-10-16 02:57:27 +000036
Chris Liechtif99cd5c2015-08-13 22:54:16 +020037# "for byte in data" fails for python3 as it returns ints instead of bytes
38def iterbytes(b):
39 """Iterate over bytes, returning bytes instead of ints (python3)"""
Chris Liechti12a439f2015-08-20 23:01:53 +020040 if isinstance(b, memoryview):
41 b = b.tobytes()
Chris Liechti9eaa40c2016-02-12 23:32:59 +010042 i = 0
Chris Liechti5eaaa4e2015-08-17 03:08:55 +020043 while True:
Chris Liechti9eaa40c2016-02-12 23:32:59 +010044 a = b[i:i + 1]
45 i += 1
Chris Liechti5eaaa4e2015-08-17 03:08:55 +020046 if a:
47 yield a
48 else:
49 break
50
Chris Liechti033f17c2015-08-30 21:28:04 +020051
cliechti38077122013-10-16 02:57:27 +000052# all Python versions prior 3.x convert ``str([17])`` to '[17]' instead of '\x11'
53# so a simple ``bytes(sequence)`` doesn't work for all versions
cliechti32c10332009-08-05 13:23:43 +000054def to_bytes(seq):
55 """convert a sequence to a bytes type"""
cliechti38077122013-10-16 02:57:27 +000056 if isinstance(seq, bytes):
57 return seq
58 elif isinstance(seq, bytearray):
59 return bytes(seq)
60 elif isinstance(seq, memoryview):
61 return seq.tobytes()
Chris Liechti4a790ad2015-09-09 17:12:52 +020062 elif isinstance(seq, unicode):
Chris Liechti984c5c52016-02-15 23:48:45 +010063 raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))
cliechti38077122013-10-16 02:57:27 +000064 else:
Chris Liechti143ff762016-09-14 18:01:45 +020065 # handle list of integers and bytes (one or more items) for Python 2 and 3
66 return bytes(bytearray(seq))
67
cliechti32c10332009-08-05 13:23:43 +000068
69# create control bytes
Chris Liechticf29a352015-10-23 22:03:40 +020070XON = to_bytes([17])
cliechti32c10332009-08-05 13:23:43 +000071XOFF = to_bytes([19])
cliechti4a567a02009-07-27 22:09:31 +000072
cliechti8e99b6f2010-07-21 15:46:39 +000073CR = to_bytes([13])
74LF = to_bytes([10])
75
cliechtia3a811f2009-07-29 21:59:03 +000076
cliechti0d6029a2008-06-21 01:28:46 +000077PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
cliechti58b481c2009-02-16 20:42:32 +000078STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO = (1, 1.5, 2)
cliechti14b274a2009-02-07 00:27:05 +000079FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8)
cliechtid6bf52c2003-10-01 02:28:12 +000080
81PARITY_NAMES = {
Chris Liechti033f17c2015-08-30 21:28:04 +020082 PARITY_NONE: 'None',
83 PARITY_EVEN: 'Even',
84 PARITY_ODD: 'Odd',
85 PARITY_MARK: 'Mark',
cliechti4a567a02009-07-27 22:09:31 +000086 PARITY_SPACE: 'Space',
cliechtid6bf52c2003-10-01 02:28:12 +000087}
88
cliechti1dbe4b62002-02-14 02:49:25 +000089
cliechti4a567a02009-07-27 22:09:31 +000090class SerialException(IOError):
cliechtid6bf52c2003-10-01 02:28:12 +000091 """Base class for serial port related exceptions."""
cliechti7fe54d52002-03-03 20:11:47 +000092
cliechtid6bf52c2003-10-01 02:28:12 +000093
cliechti62611612004-04-20 01:55:43 +000094class SerialTimeoutException(SerialException):
95 """Write timeouts give an exception"""
96
cliechti4a567a02009-07-27 22:09:31 +000097
cliechti4b20ec62012-08-16 01:04:44 +000098writeTimeoutError = SerialTimeoutException('Write timeout')
99portNotOpenError = SerialException('Attempting to use a port that is not open')
cliechti62611612004-04-20 01:55:43 +0000100
cliechtif81362e2009-07-25 03:44:33 +0000101
Chris Liechti935a2622016-08-30 23:39:15 +0200102class Timeout(object):
103 """\
Chris Liechti514f76c2016-09-02 22:32:37 +0200104 Abstraction for timeout operations. Using time.monotonic() if available
105 or time.time() in all other cases.
Chris Liechti06ed4a52016-09-03 23:53:12 +0200106
107 The class can also be initialized with 0 or None, in order to support
108 non-blocking and fully blocking I/O operations. The attributes
109 is_non_blocking and is_infinite are set accordingly.
Chris Liechti935a2622016-08-30 23:39:15 +0200110 """
Chris Liechti514f76c2016-09-02 22:32:37 +0200111 if hasattr(time, 'monotonic'):
112 # Timeout implementation with time.monotonic(). This function is only
113 # supported by Python 3.3 and above. It returns a time in seconds
114 # (float) just as time.time(), but is not affected by system clock
115 # adjustments.
116 TIME = time.monotonic
117 else:
118 # Timeout implementation with time.time(). This is compatible with all
119 # Python versions but has issues if the clock is adjusted while the
120 # timeout is running.
121 TIME = time.time
122
Chris Liechti935a2622016-08-30 23:39:15 +0200123 def __init__(self, duration):
124 """Initialize a timeout with given duration"""
125 self.is_infinite = (duration is None)
126 self.is_non_blocking = (duration == 0)
Chris Liechti03513322016-09-04 23:35:53 +0200127 self.duration = duration
Chris Liechti935a2622016-08-30 23:39:15 +0200128 if duration is not None:
Chris Liechti514f76c2016-09-02 22:32:37 +0200129 self.target_time = self.TIME() + duration
Chris Liechti935a2622016-08-30 23:39:15 +0200130 else:
131 self.target_time = None
132
133 def expired(self):
Chris Liechti06ed4a52016-09-03 23:53:12 +0200134 """Return a boolean, telling if the timeout has expired"""
Chris Liechti03513322016-09-04 23:35:53 +0200135 return self.target_time is not None and self.time_left() <= 0
Chris Liechti935a2622016-08-30 23:39:15 +0200136
137 def time_left(self):
138 """Return how many seconds are left until the timeout expires"""
139 if self.is_non_blocking:
140 return 0
141 elif self.is_infinite:
142 return None
143 else:
Chris Liechti03513322016-09-04 23:35:53 +0200144 delta = self.target_time - self.TIME()
145 if delta > self.duration:
146 # clock jumped, recalculate
147 self.target_time = self.TIME() + self.duration
148 return self.duration
149 else:
150 return max(0, delta)
Chris Liechti935a2622016-08-30 23:39:15 +0200151
Chris Liechtif0197252016-09-01 19:48:03 +0200152 def restart(self, duration):
Chris Liechti06ed4a52016-09-03 23:53:12 +0200153 """\
154 Restart a timeout, only supported if a timeout was already set up
155 before.
156 """
Chris Liechti03513322016-09-04 23:35:53 +0200157 self.duration = duration
Chris Liechti514f76c2016-09-02 22:32:37 +0200158 self.target_time = self.TIME() + duration
Chris Liechtif0197252016-09-01 19:48:03 +0200159
Chris Liechti935a2622016-08-30 23:39:15 +0200160
Chris Liechtief6b7b42015-08-06 22:19:26 +0200161class SerialBase(io.RawIOBase):
cliechti7d448562014-08-03 21:57:45 +0000162 """\
163 Serial port base class. Provides __init__ function and properties to
164 get/set port settings.
165 """
cliechti14b274a2009-02-07 00:27:05 +0000166
cliechtidfec0c82009-07-21 01:35:41 +0000167 # default values, may be overridden in subclasses that do not support all values
cliechtif81362e2009-07-25 03:44:33 +0000168 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
169 9600, 19200, 38400, 57600, 115200, 230400, 460800, 500000,
170 576000, 921600, 1000000, 1152000, 1500000, 2000000, 2500000,
171 3000000, 3500000, 4000000)
cliechtid6bf52c2003-10-01 02:28:12 +0000172 BYTESIZES = (FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS)
Chris Liechticf29a352015-10-23 22:03:40 +0200173 PARITIES = (PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE)
174 STOPBITS = (STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO)
cliechti14b274a2009-02-07 00:27:05 +0000175
cliechtid6bf52c2003-10-01 02:28:12 +0000176 def __init__(self,
Chris Liechtid6bcaaf2016-02-01 22:55:26 +0100177 port=None,
178 baudrate=9600,
179 bytesize=EIGHTBITS,
180 parity=PARITY_NONE,
181 stopbits=STOPBITS_ONE,
182 timeout=None,
183 xonxoff=False,
184 rtscts=False,
185 write_timeout=None,
186 dsrdtr=False,
187 inter_byte_timeout=None,
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100188 **kwargs):
cliechti7d448562014-08-03 21:57:45 +0000189 """\
Chris Liechtid6bcaaf2016-02-01 22:55:26 +0100190 Initialize comm port object. If a "port" is given, then the port will be
cliechti7d448562014-08-03 21:57:45 +0000191 opened immediately. Otherwise a Serial port object in closed state
192 is returned.
193 """
cliechtid6bf52c2003-10-01 02:28:12 +0000194
Chris Liechti033f17c2015-08-30 21:28:04 +0200195 self.is_open = False
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100196 self.portstr = None
197 self.name = None
Chris Liechtic14bba82016-01-02 23:23:11 +0100198 # correct values are assigned below through properties
199 self._port = None
200 self._baudrate = None
201 self._bytesize = None
202 self._parity = None
203 self._stopbits = None
204 self._timeout = None
205 self._write_timeout = None
206 self._xonxoff = None
207 self._rtscts = None
208 self._dsrdtr = None
209 self._inter_byte_timeout = None
Chris Liechti033f17c2015-08-30 21:28:04 +0200210 self._rs485_mode = None # disabled by default
Chris Liechtif7534c82016-05-07 23:35:54 +0200211 self._rts_state = True
212 self._dtr_state = True
Chris Liechtief1fe252015-08-27 23:25:21 +0200213 self._break_state = False
cliechti14b274a2009-02-07 00:27:05 +0000214
215 # assign values using get/set methods using the properties feature
Chris Liechti033f17c2015-08-30 21:28:04 +0200216 self.port = port
cliechtid6bf52c2003-10-01 02:28:12 +0000217 self.baudrate = baudrate
218 self.bytesize = bytesize
Chris Liechti033f17c2015-08-30 21:28:04 +0200219 self.parity = parity
cliechtid6bf52c2003-10-01 02:28:12 +0000220 self.stopbits = stopbits
Chris Liechti033f17c2015-08-30 21:28:04 +0200221 self.timeout = timeout
Chris Liechti518b0d32015-08-30 02:20:39 +0200222 self.write_timeout = write_timeout
Chris Liechti033f17c2015-08-30 21:28:04 +0200223 self.xonxoff = xonxoff
224 self.rtscts = rtscts
225 self.dsrdtr = dsrdtr
Chris Liechtib5331752015-10-24 01:34:11 +0200226 self.inter_byte_timeout = inter_byte_timeout
Chris Liechtic14bba82016-01-02 23:23:11 +0100227 # watch for backward compatible kwargs
228 if 'writeTimeout' in kwargs:
229 self.write_timeout = kwargs.pop('writeTimeout')
230 if 'interCharTimeout' in kwargs:
231 self.inter_byte_timeout = kwargs.pop('interCharTimeout')
232 if kwargs:
Chris Liechti984c5c52016-02-15 23:48:45 +0100233 raise ValueError('unexpected keyword arguments: {!r}'.format(kwargs))
cliechti14b274a2009-02-07 00:27:05 +0000234
cliechtid6bf52c2003-10-01 02:28:12 +0000235 if port is not None:
236 self.open()
237
cliechtid6bf52c2003-10-01 02:28:12 +0000238 # - - - - - - - - - - - - - - - - - - - - - - - -
239
Chris Liechtia51b0bc2015-12-10 21:14:45 +0100240 # to be implemented by subclasses:
241 # def open(self):
242 # def close(self):
Chris Liechti5e763ca2015-12-09 13:01:26 +0100243
244 # - - - - - - - - - - - - - - - - - - - - - - - -
245
Chris Liechti779b1a22015-08-04 14:54:22 +0200246 @property
247 def port(self):
248 """\
249 Get the current port setting. The value that was passed on init or using
Chris Liechtibf9e3182016-04-22 21:31:09 +0200250 setPort() is passed back.
Chris Liechti779b1a22015-08-04 14:54:22 +0200251 """
252 return self._port
253
254 @port.setter
255 def port(self, port):
cliechti7d448562014-08-03 21:57:45 +0000256 """\
Chris Liechtibf9e3182016-04-22 21:31:09 +0200257 Change the port.
cliechti7d448562014-08-03 21:57:45 +0000258 """
Chris Liechtif41b4592016-05-11 15:11:27 +0200259 if port is not None and not isinstance(port, basestring):
Chris Liechtibf9e3182016-04-22 21:31:09 +0200260 raise ValueError('"port" must be None or a string, not {}'.format(type(port)))
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200261 was_open = self.is_open
262 if was_open:
263 self.close()
Chris Liechti68340d72015-08-03 14:15:48 +0200264 self.portstr = port
cliechtid6bf52c2003-10-01 02:28:12 +0000265 self._port = port
cliechtif81362e2009-07-25 03:44:33 +0000266 self.name = self.portstr
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200267 if was_open:
268 self.open()
cliechti14b274a2009-02-07 00:27:05 +0000269
Chris Liechti779b1a22015-08-04 14:54:22 +0200270 @property
271 def baudrate(self):
272 """Get the current baud rate setting."""
273 return self._baudrate
cliechtid6bf52c2003-10-01 02:28:12 +0000274
Chris Liechti779b1a22015-08-04 14:54:22 +0200275 @baudrate.setter
276 def baudrate(self, baudrate):
cliechti7d448562014-08-03 21:57:45 +0000277 """\
278 Change baud rate. It raises a ValueError if the port is open and the
cliechti2750b832009-07-28 00:13:52 +0000279 baud rate is not possible. If the port is closed, then the value is
cliechti7d448562014-08-03 21:57:45 +0000280 accepted and the exception is raised when the port is opened.
281 """
cliechti107db8d2004-01-15 01:20:23 +0000282 try:
cliechtie30868d2013-10-16 15:35:11 +0000283 b = int(baudrate)
cliechti107db8d2004-01-15 01:20:23 +0000284 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100285 raise ValueError("Not a valid baudrate: {!r}".format(baudrate))
cliechti107db8d2004-01-15 01:20:23 +0000286 else:
Chris Liechtia83408a2016-05-23 22:18:43 +0200287 if b < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100288 raise ValueError("Not a valid baudrate: {!r}".format(baudrate))
cliechtie30868d2013-10-16 15:35:11 +0000289 self._baudrate = b
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200290 if self.is_open:
291 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000292
Chris Liechti779b1a22015-08-04 14:54:22 +0200293 @property
294 def bytesize(self):
295 """Get the current byte size setting."""
296 return self._bytesize
cliechtid6bf52c2003-10-01 02:28:12 +0000297
Chris Liechti779b1a22015-08-04 14:54:22 +0200298 @bytesize.setter
299 def bytesize(self, bytesize):
cliechtid6bf52c2003-10-01 02:28:12 +0000300 """Change byte size."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200301 if bytesize not in self.BYTESIZES:
Chris Liechti984c5c52016-02-15 23:48:45 +0100302 raise ValueError("Not a valid byte size: {!r}".format(bytesize))
cliechtid6bf52c2003-10-01 02:28:12 +0000303 self._bytesize = bytesize
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200304 if self.is_open:
305 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000306
Chris Liechti779b1a22015-08-04 14:54:22 +0200307 @property
308 def parity(self):
309 """Get the current parity setting."""
310 return self._parity
311
312 @parity.setter
313 def parity(self, parity):
cliechtid6bf52c2003-10-01 02:28:12 +0000314 """Change parity setting."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200315 if parity not in self.PARITIES:
Chris Liechti984c5c52016-02-15 23:48:45 +0100316 raise ValueError("Not a valid parity: {!r}".format(parity))
cliechtid6bf52c2003-10-01 02:28:12 +0000317 self._parity = parity
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200318 if self.is_open:
319 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000320
Chris Liechti779b1a22015-08-04 14:54:22 +0200321 @property
322 def stopbits(self):
323 """Get the current stop bits setting."""
324 return self._stopbits
325
326 @stopbits.setter
327 def stopbits(self, stopbits):
cliechti4a567a02009-07-27 22:09:31 +0000328 """Change stop bits size."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200329 if stopbits not in self.STOPBITS:
Chris Liechti984c5c52016-02-15 23:48:45 +0100330 raise ValueError("Not a valid stop bit size: {!r}".format(stopbits))
cliechtid6bf52c2003-10-01 02:28:12 +0000331 self._stopbits = stopbits
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200332 if self.is_open:
333 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000334
Chris Liechti779b1a22015-08-04 14:54:22 +0200335 @property
336 def timeout(self):
337 """Get the current timeout setting."""
338 return self._timeout
cliechtid6bf52c2003-10-01 02:28:12 +0000339
Chris Liechti779b1a22015-08-04 14:54:22 +0200340 @timeout.setter
341 def timeout(self, timeout):
cliechtid6bf52c2003-10-01 02:28:12 +0000342 """Change timeout setting."""
343 if timeout is not None:
cliechtid6bf52c2003-10-01 02:28:12 +0000344 try:
cliechti14b274a2009-02-07 00:27:05 +0000345 timeout + 1 # test if it's a number, will throw a TypeError if not...
cliechtid6bf52c2003-10-01 02:28:12 +0000346 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100347 raise ValueError("Not a valid timeout: {!r}".format(timeout))
Chris Liechticf29a352015-10-23 22:03:40 +0200348 if timeout < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100349 raise ValueError("Not a valid timeout: {!r}".format(timeout))
cliechtid6bf52c2003-10-01 02:28:12 +0000350 self._timeout = timeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200351 if self.is_open:
352 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000353
Chris Liechti779b1a22015-08-04 14:54:22 +0200354 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200355 def write_timeout(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000356 """Get the current timeout setting."""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200357 return self._write_timeout
cliechti14b274a2009-02-07 00:27:05 +0000358
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200359 @write_timeout.setter
360 def write_timeout(self, timeout):
cliechti62611612004-04-20 01:55:43 +0000361 """Change timeout setting."""
362 if timeout is not None:
Chris Liechti033f17c2015-08-30 21:28:04 +0200363 if timeout < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100364 raise ValueError("Not a valid timeout: {!r}".format(timeout))
cliechti62611612004-04-20 01:55:43 +0000365 try:
Chris Liechti033f17c2015-08-30 21:28:04 +0200366 timeout + 1 # test if it's a number, will throw a TypeError if not...
cliechti62611612004-04-20 01:55:43 +0000367 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100368 raise ValueError("Not a valid timeout: {!r}".format(timeout))
cliechti14b274a2009-02-07 00:27:05 +0000369
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200370 self._write_timeout = timeout
371 if self.is_open:
372 self._reconfigure_port()
373
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200374 @property
Chris Liechti518b0d32015-08-30 02:20:39 +0200375 def inter_byte_timeout(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200376 """Get the current inter-character timeout setting."""
Chris Liechti96242372015-09-02 02:49:49 +0200377 return self._inter_byte_timeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200378
Chris Liechti518b0d32015-08-30 02:20:39 +0200379 @inter_byte_timeout.setter
380 def inter_byte_timeout(self, ic_timeout):
381 """Change inter-byte timeout setting."""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200382 if ic_timeout is not None:
Chris Liechti033f17c2015-08-30 21:28:04 +0200383 if ic_timeout < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100384 raise ValueError("Not a valid timeout: {!r}".format(ic_timeout))
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200385 try:
386 ic_timeout + 1 # test if it's a number, will throw a TypeError if not...
387 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100388 raise ValueError("Not a valid timeout: {!r}".format(ic_timeout))
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200389
Chris Liechti518b0d32015-08-30 02:20:39 +0200390 self._inter_byte_timeout = ic_timeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200391 if self.is_open:
392 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000393
Chris Liechti779b1a22015-08-04 14:54:22 +0200394 @property
395 def xonxoff(self):
396 """Get the current XON/XOFF setting."""
397 return self._xonxoff
cliechtid6bf52c2003-10-01 02:28:12 +0000398
Chris Liechti779b1a22015-08-04 14:54:22 +0200399 @xonxoff.setter
400 def xonxoff(self, xonxoff):
cliechti4a567a02009-07-27 22:09:31 +0000401 """Change XON/XOFF setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000402 self._xonxoff = xonxoff
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200403 if self.is_open:
404 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000405
Chris Liechti779b1a22015-08-04 14:54:22 +0200406 @property
407 def rtscts(self):
408 """Get the current RTS/CTS flow control setting."""
409 return self._rtscts
cliechtid6bf52c2003-10-01 02:28:12 +0000410
Chris Liechti779b1a22015-08-04 14:54:22 +0200411 @rtscts.setter
412 def rtscts(self, rtscts):
cliechti4a567a02009-07-27 22:09:31 +0000413 """Change RTS/CTS flow control setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000414 self._rtscts = rtscts
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200415 if self.is_open:
416 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000417
Chris Liechti779b1a22015-08-04 14:54:22 +0200418 @property
419 def dsrdtr(self):
420 """Get the current DSR/DTR flow control setting."""
421 return self._dsrdtr
cliechtid6bf52c2003-10-01 02:28:12 +0000422
Chris Liechti779b1a22015-08-04 14:54:22 +0200423 @dsrdtr.setter
424 def dsrdtr(self, dsrdtr=None):
cliechtif46e0a82005-05-19 15:24:57 +0000425 """Change DsrDtr flow control setting."""
426 if dsrdtr is None:
cliechti14b274a2009-02-07 00:27:05 +0000427 # if not set, keep backwards compatibility and follow rtscts setting
cliechtif46e0a82005-05-19 15:24:57 +0000428 self._dsrdtr = self._rtscts
429 else:
cliechti14b274a2009-02-07 00:27:05 +0000430 # if defined independently, follow its value
cliechtif46e0a82005-05-19 15:24:57 +0000431 self._dsrdtr = dsrdtr
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200432 if self.is_open:
433 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000434
Chris Liechti779b1a22015-08-04 14:54:22 +0200435 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200436 def rts(self):
437 return self._rts_state
cliechti679bfa62008-06-20 23:58:15 +0000438
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200439 @rts.setter
440 def rts(self, value):
441 self._rts_state = value
442 if self.is_open:
443 self._update_rts_state()
cliechti14b274a2009-02-07 00:27:05 +0000444
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200445 @property
446 def dtr(self):
447 return self._dtr_state
cliechti14b274a2009-02-07 00:27:05 +0000448
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200449 @dtr.setter
450 def dtr(self, value):
451 self._dtr_state = value
452 if self.is_open:
453 self._update_dtr_state()
454
455 @property
456 def break_condition(self):
457 return self._break_state
458
459 @break_condition.setter
460 def break_condition(self, value):
461 self._break_state = value
462 if self.is_open:
463 self._update_break_state()
cliechti679bfa62008-06-20 23:58:15 +0000464
cliechti4065dce2009-08-10 00:55:46 +0000465 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti33f0ec52015-08-06 16:37:21 +0200466 # functions useful for RS-485 adapters
467
468 @property
469 def rs485_mode(self):
470 """\
471 Enable RS485 mode and apply new settings, set to None to disable.
472 See serial.rs485.RS485Settings for more info about the value.
473 """
474 return self._rs485_mode
475
476 @rs485_mode.setter
477 def rs485_mode(self, rs485_settings):
478 self._rs485_mode = rs485_settings
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200479 if self.is_open:
480 self._reconfigure_port()
Chris Liechti33f0ec52015-08-06 16:37:21 +0200481
482 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechti4065dce2009-08-10 00:55:46 +0000483
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200484 _SAVED_SETTINGS = ('baudrate', 'bytesize', 'parity', 'stopbits', 'xonxoff',
Chris Liechti033f17c2015-08-30 21:28:04 +0200485 'dsrdtr', 'rtscts', 'timeout', 'write_timeout',
Chris Liechti1c3249f2015-09-01 02:31:36 +0200486 'inter_byte_timeout')
cliechti4065dce2009-08-10 00:55:46 +0000487
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200488 def get_settings(self):
cliechti7d448562014-08-03 21:57:45 +0000489 """\
490 Get current port settings as a dictionary. For use with
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200491 apply_settings().
cliechti7d448562014-08-03 21:57:45 +0000492 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200493 return dict([(key, getattr(self, '_' + key)) for key in self._SAVED_SETTINGS])
cliechti4065dce2009-08-10 00:55:46 +0000494
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200495 def apply_settings(self, d):
cliechti7d448562014-08-03 21:57:45 +0000496 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200497 Apply stored settings from a dictionary returned from
498 get_settings(). It's allowed to delete keys from the dictionary. These
cliechti7d448562014-08-03 21:57:45 +0000499 values will simply left unchanged.
500 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200501 for key in self._SAVED_SETTINGS:
Chris Liechti033f17c2015-08-30 21:28:04 +0200502 if key in d and d[key] != getattr(self, '_' + key): # check against internal "_" value
cliechti4065dce2009-08-10 00:55:46 +0000503 setattr(self, key, d[key]) # set non "_" value to use properties write function
cliechti679bfa62008-06-20 23:58:15 +0000504
cliechtid6bf52c2003-10-01 02:28:12 +0000505 # - - - - - - - - - - - - - - - - - - - - - - - -
506
507 def __repr__(self):
508 """String representation of the current port settings and its state."""
Chris Liechti984c5c52016-02-15 23:48:45 +0100509 return '{name}<id=0x{id:x}, open={p.is_open}>(port={p.portstr!r}, ' \
510 'baudrate={p.baudrate!r}, bytesize={p.bytesize!r}, parity={p.parity!r}, ' \
511 'stopbits={p.stopbits!r}, timeout={p.timeout!r}, xonxoff={p.xonxoff!r}, ' \
512 'rtscts={p.rtscts!r}, dsrdtr={p.dsrdtr!r})'.format(
513 name=self.__class__.__name__, id=id(self), p=self)
cliechtid6bf52c2003-10-01 02:28:12 +0000514
cliechti4a567a02009-07-27 22:09:31 +0000515 # - - - - - - - - - - - - - - - - - - - - - - - -
516 # compatibility with io library
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100517 # pylint: disable=invalid-name,missing-docstring
cliechti4a567a02009-07-27 22:09:31 +0000518
Chris Liechti033f17c2015-08-30 21:28:04 +0200519 def readable(self):
520 return True
521
522 def writable(self):
523 return True
524
525 def seekable(self):
526 return False
527
cliechti4a567a02009-07-27 22:09:31 +0000528 def readinto(self, b):
529 data = self.read(len(b))
530 n = len(data)
531 try:
532 b[:n] = data
Chris Liechti68340d72015-08-03 14:15:48 +0200533 except TypeError as err:
cliechti4a567a02009-07-27 22:09:31 +0000534 import array
535 if not isinstance(b, array.array):
536 raise err
537 b[:n] = array.array('b', data)
538 return n
cliechtif81362e2009-07-25 03:44:33 +0000539
Chris Liechti70b89232015-08-04 03:00:52 +0200540 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti779b1a22015-08-04 14:54:22 +0200541 # context manager
542
543 def __enter__(self):
544 return self
545
546 def __exit__(self, *args, **kwargs):
547 self.close()
548
549 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtief1fe252015-08-27 23:25:21 +0200550
551 def send_break(self, duration=0.25):
552 """\
553 Send break condition. Timed, returns to idle state after given
554 duration.
555 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200556 if not self.is_open:
557 raise portNotOpenError
Chris Liechtief1fe252015-08-27 23:25:21 +0200558 self.break_condition = True
559 time.sleep(duration)
560 self.break_condition = False
561
562 # - - - - - - - - - - - - - - - - - - - - - - - -
563 # backwards compatibility / deprecated functions
564
565 def flushInput(self):
566 self.reset_input_buffer()
567
568 def flushOutput(self):
569 self.reset_output_buffer()
570
571 def inWaiting(self):
572 return self.in_waiting
573
574 def sendBreak(self, duration=0.25):
575 self.send_break(duration)
576
577 def setRTS(self, value=1):
578 self.rts = value
579
580 def setDTR(self, value=1):
581 self.dtr = value
582
583 def getCTS(self):
584 return self.cts
585
586 def getDSR(self):
587 return self.dsr
588
589 def getRI(self):
590 return self.ri
591
592 def getCD(self):
593 return self.cd
594
Chris Liechti0eba2a62016-04-06 02:55:51 +0200595 def setPort(self, port):
596 self.port = port
597
Chris Liechtief1fe252015-08-27 23:25:21 +0200598 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200599 def writeTimeout(self):
600 return self.write_timeout
601
602 @writeTimeout.setter
603 def writeTimeout(self, timeout):
604 self.write_timeout = timeout
Chris Liechtief1fe252015-08-27 23:25:21 +0200605
606 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200607 def interCharTimeout(self):
Chris Liechti96242372015-09-02 02:49:49 +0200608 return self.inter_byte_timeout
Chris Liechtief1fe252015-08-27 23:25:21 +0200609
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200610 @interCharTimeout.setter
611 def interCharTimeout(self, interCharTimeout):
Chris Liechti96242372015-09-02 02:49:49 +0200612 self.inter_byte_timeout = interCharTimeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200613
614 def getSettingsDict(self):
615 return self.get_settings()
616
617 def applySettingsDict(self, d):
618 self.apply_settings(d)
619
620 def isOpen(self):
Chris Liechti16843852015-09-22 23:24:35 +0200621 return self.is_open
Chris Liechtief1fe252015-08-27 23:25:21 +0200622
623 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti70b89232015-08-04 03:00:52 +0200624 # additional functionality
625
David Howlett240f8fc2015-10-28 12:32:09 +0000626 def read_all(self):
Chris Liechti03cb8ed2015-10-30 23:37:24 +0100627 """\
628 Read all bytes currently available in the buffer of the OS.
629 """
David Howlett240f8fc2015-10-28 12:32:09 +0000630 return self.read(self.in_waiting)
631
Chris Liechti70b89232015-08-04 03:00:52 +0200632 def read_until(self, terminator=LF, size=None):
633 """\
634 Read until a termination sequence is found ('\n' by default), the size
635 is exceeded or until timeout occurs.
636 """
637 lenterm = len(terminator)
638 line = bytearray()
Chris Liechti6f03c0b2016-12-22 23:51:34 +0100639 timeout = Timeout(self._timeout)
Chris Liechti70b89232015-08-04 03:00:52 +0200640 while True:
641 c = self.read(1)
642 if c:
643 line += c
644 if line[-lenterm:] == terminator:
645 break
646 if size is not None and len(line) >= size:
647 break
648 else:
649 break
Chris Liechti6f03c0b2016-12-22 23:51:34 +0100650 if timeout.expired():
651 break
Chris Liechti70b89232015-08-04 03:00:52 +0200652 return bytes(line)
653
Chris Liechti70b89232015-08-04 03:00:52 +0200654 def iread_until(self, *args, **kwargs):
655 """\
656 Read lines, implemented as generator. It will raise StopIteration on
657 timeout (empty read).
658 """
659 while True:
660 line = self.read_until(*args, **kwargs)
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200661 if not line:
662 break
Chris Liechti70b89232015-08-04 03:00:52 +0200663 yield line
cliechtif81362e2009-07-25 03:44:33 +0000664
Chris Liechti779b1a22015-08-04 14:54:22 +0200665
666# - - - - - - - - - - - - - - - - - - - - - - - - -
cliechtid6bf52c2003-10-01 02:28:12 +0000667if __name__ == '__main__':
cliechtif81362e2009-07-25 03:44:33 +0000668 import sys
cliechtid6bf52c2003-10-01 02:28:12 +0000669 s = SerialBase()
Chris Liechti984c5c52016-02-15 23:48:45 +0100670 sys.stdout.write('port name: {}\n'.format(s.name))
671 sys.stdout.write('baud rates: {}\n'.format(s.BAUDRATES))
672 sys.stdout.write('byte sizes: {}\n'.format(s.BYTESIZES))
673 sys.stdout.write('parities: {}\n'.format(s.PARITIES))
674 sys.stdout.write('stop bits: {}\n'.format(s.STOPBITS))
675 sys.stdout.write('{}\n'.format(s))