blob: 7d51752ff05e315397c26f9046da44bf76af0ba9 [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,
Rob Gaddi636cc642017-02-24 11:39:46 -0800188 exclusive=None,
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100189 **kwargs):
cliechti7d448562014-08-03 21:57:45 +0000190 """\
Chris Liechtid6bcaaf2016-02-01 22:55:26 +0100191 Initialize comm port object. If a "port" is given, then the port will be
cliechti7d448562014-08-03 21:57:45 +0000192 opened immediately. Otherwise a Serial port object in closed state
193 is returned.
194 """
cliechtid6bf52c2003-10-01 02:28:12 +0000195
Chris Liechti033f17c2015-08-30 21:28:04 +0200196 self.is_open = False
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100197 self.portstr = None
198 self.name = None
Chris Liechtic14bba82016-01-02 23:23:11 +0100199 # correct values are assigned below through properties
200 self._port = None
201 self._baudrate = None
202 self._bytesize = None
203 self._parity = None
204 self._stopbits = None
205 self._timeout = None
206 self._write_timeout = None
207 self._xonxoff = None
208 self._rtscts = None
209 self._dsrdtr = None
210 self._inter_byte_timeout = None
Chris Liechti033f17c2015-08-30 21:28:04 +0200211 self._rs485_mode = None # disabled by default
Chris Liechtif7534c82016-05-07 23:35:54 +0200212 self._rts_state = True
213 self._dtr_state = True
Chris Liechtief1fe252015-08-27 23:25:21 +0200214 self._break_state = False
Rob Gaddi636cc642017-02-24 11:39:46 -0800215 self._exclusive = None
cliechti14b274a2009-02-07 00:27:05 +0000216
217 # assign values using get/set methods using the properties feature
Chris Liechti033f17c2015-08-30 21:28:04 +0200218 self.port = port
cliechtid6bf52c2003-10-01 02:28:12 +0000219 self.baudrate = baudrate
220 self.bytesize = bytesize
Chris Liechti033f17c2015-08-30 21:28:04 +0200221 self.parity = parity
cliechtid6bf52c2003-10-01 02:28:12 +0000222 self.stopbits = stopbits
Chris Liechti033f17c2015-08-30 21:28:04 +0200223 self.timeout = timeout
Chris Liechti518b0d32015-08-30 02:20:39 +0200224 self.write_timeout = write_timeout
Chris Liechti033f17c2015-08-30 21:28:04 +0200225 self.xonxoff = xonxoff
226 self.rtscts = rtscts
227 self.dsrdtr = dsrdtr
Chris Liechtib5331752015-10-24 01:34:11 +0200228 self.inter_byte_timeout = inter_byte_timeout
Rob Gaddi636cc642017-02-24 11:39:46 -0800229 self.exclusive = exclusive
Chris Liechti1c4bc812017-03-08 02:44:04 +0100230
Chris Liechtic14bba82016-01-02 23:23:11 +0100231 # watch for backward compatible kwargs
232 if 'writeTimeout' in kwargs:
233 self.write_timeout = kwargs.pop('writeTimeout')
234 if 'interCharTimeout' in kwargs:
235 self.inter_byte_timeout = kwargs.pop('interCharTimeout')
236 if kwargs:
Chris Liechti984c5c52016-02-15 23:48:45 +0100237 raise ValueError('unexpected keyword arguments: {!r}'.format(kwargs))
cliechti14b274a2009-02-07 00:27:05 +0000238
cliechtid6bf52c2003-10-01 02:28:12 +0000239 if port is not None:
240 self.open()
241
cliechtid6bf52c2003-10-01 02:28:12 +0000242 # - - - - - - - - - - - - - - - - - - - - - - - -
243
Chris Liechtia51b0bc2015-12-10 21:14:45 +0100244 # to be implemented by subclasses:
245 # def open(self):
246 # def close(self):
Chris Liechti5e763ca2015-12-09 13:01:26 +0100247
248 # - - - - - - - - - - - - - - - - - - - - - - - -
249
Chris Liechti779b1a22015-08-04 14:54:22 +0200250 @property
251 def port(self):
252 """\
253 Get the current port setting. The value that was passed on init or using
Chris Liechtibf9e3182016-04-22 21:31:09 +0200254 setPort() is passed back.
Chris Liechti779b1a22015-08-04 14:54:22 +0200255 """
256 return self._port
257
258 @port.setter
259 def port(self, port):
cliechti7d448562014-08-03 21:57:45 +0000260 """\
Chris Liechtibf9e3182016-04-22 21:31:09 +0200261 Change the port.
cliechti7d448562014-08-03 21:57:45 +0000262 """
Chris Liechtif41b4592016-05-11 15:11:27 +0200263 if port is not None and not isinstance(port, basestring):
Chris Liechtibf9e3182016-04-22 21:31:09 +0200264 raise ValueError('"port" must be None or a string, not {}'.format(type(port)))
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200265 was_open = self.is_open
266 if was_open:
267 self.close()
Chris Liechti68340d72015-08-03 14:15:48 +0200268 self.portstr = port
cliechtid6bf52c2003-10-01 02:28:12 +0000269 self._port = port
cliechtif81362e2009-07-25 03:44:33 +0000270 self.name = self.portstr
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200271 if was_open:
272 self.open()
cliechti14b274a2009-02-07 00:27:05 +0000273
Chris Liechti779b1a22015-08-04 14:54:22 +0200274 @property
275 def baudrate(self):
276 """Get the current baud rate setting."""
277 return self._baudrate
cliechtid6bf52c2003-10-01 02:28:12 +0000278
Chris Liechti779b1a22015-08-04 14:54:22 +0200279 @baudrate.setter
280 def baudrate(self, baudrate):
cliechti7d448562014-08-03 21:57:45 +0000281 """\
282 Change baud rate. It raises a ValueError if the port is open and the
cliechti2750b832009-07-28 00:13:52 +0000283 baud rate is not possible. If the port is closed, then the value is
cliechti7d448562014-08-03 21:57:45 +0000284 accepted and the exception is raised when the port is opened.
285 """
cliechti107db8d2004-01-15 01:20:23 +0000286 try:
cliechtie30868d2013-10-16 15:35:11 +0000287 b = int(baudrate)
cliechti107db8d2004-01-15 01:20:23 +0000288 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100289 raise ValueError("Not a valid baudrate: {!r}".format(baudrate))
cliechti107db8d2004-01-15 01:20:23 +0000290 else:
Chris Liechtia83408a2016-05-23 22:18:43 +0200291 if b < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100292 raise ValueError("Not a valid baudrate: {!r}".format(baudrate))
cliechtie30868d2013-10-16 15:35:11 +0000293 self._baudrate = b
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200294 if self.is_open:
295 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000296
Chris Liechti779b1a22015-08-04 14:54:22 +0200297 @property
298 def bytesize(self):
299 """Get the current byte size setting."""
300 return self._bytesize
cliechtid6bf52c2003-10-01 02:28:12 +0000301
Chris Liechti779b1a22015-08-04 14:54:22 +0200302 @bytesize.setter
303 def bytesize(self, bytesize):
cliechtid6bf52c2003-10-01 02:28:12 +0000304 """Change byte size."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200305 if bytesize not in self.BYTESIZES:
Chris Liechti984c5c52016-02-15 23:48:45 +0100306 raise ValueError("Not a valid byte size: {!r}".format(bytesize))
cliechtid6bf52c2003-10-01 02:28:12 +0000307 self._bytesize = bytesize
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200308 if self.is_open:
309 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000310
Chris Liechti779b1a22015-08-04 14:54:22 +0200311 @property
Rob Gaddi636cc642017-02-24 11:39:46 -0800312 def exclusive(self):
313 """Get the current exclusive access setting."""
314 return self._exclusive
Chris Liechti1c4bc812017-03-08 02:44:04 +0100315
Rob Gaddi636cc642017-02-24 11:39:46 -0800316 @exclusive.setter
317 def exclusive(self, exclusive):
318 """Change the exclusive access setting."""
319 self._exclusive = exclusive
320 if self.is_open:
321 self._reconfigure_port()
322
323 @property
Chris Liechti779b1a22015-08-04 14:54:22 +0200324 def parity(self):
325 """Get the current parity setting."""
326 return self._parity
327
328 @parity.setter
329 def parity(self, parity):
cliechtid6bf52c2003-10-01 02:28:12 +0000330 """Change parity setting."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200331 if parity not in self.PARITIES:
Chris Liechti984c5c52016-02-15 23:48:45 +0100332 raise ValueError("Not a valid parity: {!r}".format(parity))
cliechtid6bf52c2003-10-01 02:28:12 +0000333 self._parity = parity
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200334 if self.is_open:
335 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000336
Chris Liechti779b1a22015-08-04 14:54:22 +0200337 @property
338 def stopbits(self):
339 """Get the current stop bits setting."""
340 return self._stopbits
341
342 @stopbits.setter
343 def stopbits(self, stopbits):
cliechti4a567a02009-07-27 22:09:31 +0000344 """Change stop bits size."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200345 if stopbits not in self.STOPBITS:
Chris Liechti984c5c52016-02-15 23:48:45 +0100346 raise ValueError("Not a valid stop bit size: {!r}".format(stopbits))
cliechtid6bf52c2003-10-01 02:28:12 +0000347 self._stopbits = stopbits
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200348 if self.is_open:
349 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000350
Chris Liechti779b1a22015-08-04 14:54:22 +0200351 @property
352 def timeout(self):
353 """Get the current timeout setting."""
354 return self._timeout
cliechtid6bf52c2003-10-01 02:28:12 +0000355
Chris Liechti779b1a22015-08-04 14:54:22 +0200356 @timeout.setter
357 def timeout(self, timeout):
cliechtid6bf52c2003-10-01 02:28:12 +0000358 """Change timeout setting."""
359 if timeout is not None:
cliechtid6bf52c2003-10-01 02:28:12 +0000360 try:
cliechti14b274a2009-02-07 00:27:05 +0000361 timeout + 1 # test if it's a number, will throw a TypeError if not...
cliechtid6bf52c2003-10-01 02:28:12 +0000362 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100363 raise ValueError("Not a valid timeout: {!r}".format(timeout))
Chris Liechticf29a352015-10-23 22:03:40 +0200364 if timeout < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100365 raise ValueError("Not a valid timeout: {!r}".format(timeout))
cliechtid6bf52c2003-10-01 02:28:12 +0000366 self._timeout = timeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200367 if self.is_open:
368 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000369
Chris Liechti779b1a22015-08-04 14:54:22 +0200370 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200371 def write_timeout(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000372 """Get the current timeout setting."""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200373 return self._write_timeout
cliechti14b274a2009-02-07 00:27:05 +0000374
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200375 @write_timeout.setter
376 def write_timeout(self, timeout):
cliechti62611612004-04-20 01:55:43 +0000377 """Change timeout setting."""
378 if timeout is not None:
Chris Liechti033f17c2015-08-30 21:28:04 +0200379 if timeout < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100380 raise ValueError("Not a valid timeout: {!r}".format(timeout))
cliechti62611612004-04-20 01:55:43 +0000381 try:
Chris Liechti033f17c2015-08-30 21:28:04 +0200382 timeout + 1 # test if it's a number, will throw a TypeError if not...
cliechti62611612004-04-20 01:55:43 +0000383 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100384 raise ValueError("Not a valid timeout: {!r}".format(timeout))
cliechti14b274a2009-02-07 00:27:05 +0000385
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200386 self._write_timeout = timeout
387 if self.is_open:
388 self._reconfigure_port()
389
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200390 @property
Chris Liechti518b0d32015-08-30 02:20:39 +0200391 def inter_byte_timeout(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200392 """Get the current inter-character timeout setting."""
Chris Liechti96242372015-09-02 02:49:49 +0200393 return self._inter_byte_timeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200394
Chris Liechti518b0d32015-08-30 02:20:39 +0200395 @inter_byte_timeout.setter
396 def inter_byte_timeout(self, ic_timeout):
397 """Change inter-byte timeout setting."""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200398 if ic_timeout is not None:
Chris Liechti033f17c2015-08-30 21:28:04 +0200399 if ic_timeout < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100400 raise ValueError("Not a valid timeout: {!r}".format(ic_timeout))
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200401 try:
402 ic_timeout + 1 # test if it's a number, will throw a TypeError if not...
403 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100404 raise ValueError("Not a valid timeout: {!r}".format(ic_timeout))
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200405
Chris Liechti518b0d32015-08-30 02:20:39 +0200406 self._inter_byte_timeout = ic_timeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200407 if self.is_open:
408 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000409
Chris Liechti779b1a22015-08-04 14:54:22 +0200410 @property
411 def xonxoff(self):
412 """Get the current XON/XOFF setting."""
413 return self._xonxoff
cliechtid6bf52c2003-10-01 02:28:12 +0000414
Chris Liechti779b1a22015-08-04 14:54:22 +0200415 @xonxoff.setter
416 def xonxoff(self, xonxoff):
cliechti4a567a02009-07-27 22:09:31 +0000417 """Change XON/XOFF setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000418 self._xonxoff = xonxoff
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200419 if self.is_open:
420 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000421
Chris Liechti779b1a22015-08-04 14:54:22 +0200422 @property
423 def rtscts(self):
424 """Get the current RTS/CTS flow control setting."""
425 return self._rtscts
cliechtid6bf52c2003-10-01 02:28:12 +0000426
Chris Liechti779b1a22015-08-04 14:54:22 +0200427 @rtscts.setter
428 def rtscts(self, rtscts):
cliechti4a567a02009-07-27 22:09:31 +0000429 """Change RTS/CTS flow control setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000430 self._rtscts = rtscts
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200431 if self.is_open:
432 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000433
Chris Liechti779b1a22015-08-04 14:54:22 +0200434 @property
435 def dsrdtr(self):
436 """Get the current DSR/DTR flow control setting."""
437 return self._dsrdtr
cliechtid6bf52c2003-10-01 02:28:12 +0000438
Chris Liechti779b1a22015-08-04 14:54:22 +0200439 @dsrdtr.setter
440 def dsrdtr(self, dsrdtr=None):
cliechtif46e0a82005-05-19 15:24:57 +0000441 """Change DsrDtr flow control setting."""
442 if dsrdtr is None:
cliechti14b274a2009-02-07 00:27:05 +0000443 # if not set, keep backwards compatibility and follow rtscts setting
cliechtif46e0a82005-05-19 15:24:57 +0000444 self._dsrdtr = self._rtscts
445 else:
cliechti14b274a2009-02-07 00:27:05 +0000446 # if defined independently, follow its value
cliechtif46e0a82005-05-19 15:24:57 +0000447 self._dsrdtr = dsrdtr
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200448 if self.is_open:
449 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000450
Chris Liechti779b1a22015-08-04 14:54:22 +0200451 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200452 def rts(self):
453 return self._rts_state
cliechti679bfa62008-06-20 23:58:15 +0000454
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200455 @rts.setter
456 def rts(self, value):
457 self._rts_state = value
458 if self.is_open:
459 self._update_rts_state()
cliechti14b274a2009-02-07 00:27:05 +0000460
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200461 @property
462 def dtr(self):
463 return self._dtr_state
cliechti14b274a2009-02-07 00:27:05 +0000464
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200465 @dtr.setter
466 def dtr(self, value):
467 self._dtr_state = value
468 if self.is_open:
469 self._update_dtr_state()
470
471 @property
472 def break_condition(self):
473 return self._break_state
474
475 @break_condition.setter
476 def break_condition(self, value):
477 self._break_state = value
478 if self.is_open:
479 self._update_break_state()
cliechti679bfa62008-06-20 23:58:15 +0000480
cliechti4065dce2009-08-10 00:55:46 +0000481 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti33f0ec52015-08-06 16:37:21 +0200482 # functions useful for RS-485 adapters
483
484 @property
485 def rs485_mode(self):
486 """\
487 Enable RS485 mode and apply new settings, set to None to disable.
488 See serial.rs485.RS485Settings for more info about the value.
489 """
490 return self._rs485_mode
491
492 @rs485_mode.setter
493 def rs485_mode(self, rs485_settings):
494 self._rs485_mode = rs485_settings
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200495 if self.is_open:
496 self._reconfigure_port()
Chris Liechti33f0ec52015-08-06 16:37:21 +0200497
498 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechti4065dce2009-08-10 00:55:46 +0000499
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200500 _SAVED_SETTINGS = ('baudrate', 'bytesize', 'parity', 'stopbits', 'xonxoff',
Chris Liechti033f17c2015-08-30 21:28:04 +0200501 'dsrdtr', 'rtscts', 'timeout', 'write_timeout',
Chris Liechti1c3249f2015-09-01 02:31:36 +0200502 'inter_byte_timeout')
cliechti4065dce2009-08-10 00:55:46 +0000503
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200504 def get_settings(self):
cliechti7d448562014-08-03 21:57:45 +0000505 """\
506 Get current port settings as a dictionary. For use with
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200507 apply_settings().
cliechti7d448562014-08-03 21:57:45 +0000508 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200509 return dict([(key, getattr(self, '_' + key)) for key in self._SAVED_SETTINGS])
cliechti4065dce2009-08-10 00:55:46 +0000510
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200511 def apply_settings(self, d):
cliechti7d448562014-08-03 21:57:45 +0000512 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200513 Apply stored settings from a dictionary returned from
514 get_settings(). It's allowed to delete keys from the dictionary. These
cliechti7d448562014-08-03 21:57:45 +0000515 values will simply left unchanged.
516 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200517 for key in self._SAVED_SETTINGS:
Chris Liechti033f17c2015-08-30 21:28:04 +0200518 if key in d and d[key] != getattr(self, '_' + key): # check against internal "_" value
cliechti4065dce2009-08-10 00:55:46 +0000519 setattr(self, key, d[key]) # set non "_" value to use properties write function
cliechti679bfa62008-06-20 23:58:15 +0000520
cliechtid6bf52c2003-10-01 02:28:12 +0000521 # - - - - - - - - - - - - - - - - - - - - - - - -
522
523 def __repr__(self):
524 """String representation of the current port settings and its state."""
Chris Liechti984c5c52016-02-15 23:48:45 +0100525 return '{name}<id=0x{id:x}, open={p.is_open}>(port={p.portstr!r}, ' \
526 'baudrate={p.baudrate!r}, bytesize={p.bytesize!r}, parity={p.parity!r}, ' \
527 'stopbits={p.stopbits!r}, timeout={p.timeout!r}, xonxoff={p.xonxoff!r}, ' \
528 'rtscts={p.rtscts!r}, dsrdtr={p.dsrdtr!r})'.format(
529 name=self.__class__.__name__, id=id(self), p=self)
cliechtid6bf52c2003-10-01 02:28:12 +0000530
cliechti4a567a02009-07-27 22:09:31 +0000531 # - - - - - - - - - - - - - - - - - - - - - - - -
532 # compatibility with io library
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100533 # pylint: disable=invalid-name,missing-docstring
cliechti4a567a02009-07-27 22:09:31 +0000534
Chris Liechti033f17c2015-08-30 21:28:04 +0200535 def readable(self):
536 return True
537
538 def writable(self):
539 return True
540
541 def seekable(self):
542 return False
543
cliechti4a567a02009-07-27 22:09:31 +0000544 def readinto(self, b):
545 data = self.read(len(b))
546 n = len(data)
547 try:
548 b[:n] = data
Chris Liechti68340d72015-08-03 14:15:48 +0200549 except TypeError as err:
cliechti4a567a02009-07-27 22:09:31 +0000550 import array
551 if not isinstance(b, array.array):
552 raise err
553 b[:n] = array.array('b', data)
554 return n
cliechtif81362e2009-07-25 03:44:33 +0000555
Chris Liechti70b89232015-08-04 03:00:52 +0200556 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti779b1a22015-08-04 14:54:22 +0200557 # context manager
558
559 def __enter__(self):
Guillaume Galeazzi48a5ce12017-06-28 16:21:46 +0200560 if not self.is_open:
561 self.open()
Chris Liechti779b1a22015-08-04 14:54:22 +0200562 return self
563
564 def __exit__(self, *args, **kwargs):
565 self.close()
566
567 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtief1fe252015-08-27 23:25:21 +0200568
569 def send_break(self, duration=0.25):
570 """\
571 Send break condition. Timed, returns to idle state after given
572 duration.
573 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200574 if not self.is_open:
575 raise portNotOpenError
Chris Liechtief1fe252015-08-27 23:25:21 +0200576 self.break_condition = True
577 time.sleep(duration)
578 self.break_condition = False
579
580 # - - - - - - - - - - - - - - - - - - - - - - - -
581 # backwards compatibility / deprecated functions
582
583 def flushInput(self):
584 self.reset_input_buffer()
585
586 def flushOutput(self):
587 self.reset_output_buffer()
588
589 def inWaiting(self):
590 return self.in_waiting
591
592 def sendBreak(self, duration=0.25):
593 self.send_break(duration)
594
595 def setRTS(self, value=1):
596 self.rts = value
597
598 def setDTR(self, value=1):
599 self.dtr = value
600
601 def getCTS(self):
602 return self.cts
603
604 def getDSR(self):
605 return self.dsr
606
607 def getRI(self):
608 return self.ri
609
610 def getCD(self):
611 return self.cd
612
Chris Liechti0eba2a62016-04-06 02:55:51 +0200613 def setPort(self, port):
614 self.port = port
615
Chris Liechtief1fe252015-08-27 23:25:21 +0200616 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200617 def writeTimeout(self):
618 return self.write_timeout
619
620 @writeTimeout.setter
621 def writeTimeout(self, timeout):
622 self.write_timeout = timeout
Chris Liechtief1fe252015-08-27 23:25:21 +0200623
624 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200625 def interCharTimeout(self):
Chris Liechti96242372015-09-02 02:49:49 +0200626 return self.inter_byte_timeout
Chris Liechtief1fe252015-08-27 23:25:21 +0200627
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200628 @interCharTimeout.setter
629 def interCharTimeout(self, interCharTimeout):
Chris Liechti96242372015-09-02 02:49:49 +0200630 self.inter_byte_timeout = interCharTimeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200631
632 def getSettingsDict(self):
633 return self.get_settings()
634
635 def applySettingsDict(self, d):
636 self.apply_settings(d)
637
638 def isOpen(self):
Chris Liechti16843852015-09-22 23:24:35 +0200639 return self.is_open
Chris Liechtief1fe252015-08-27 23:25:21 +0200640
641 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti70b89232015-08-04 03:00:52 +0200642 # additional functionality
643
David Howlett240f8fc2015-10-28 12:32:09 +0000644 def read_all(self):
Chris Liechti03cb8ed2015-10-30 23:37:24 +0100645 """\
646 Read all bytes currently available in the buffer of the OS.
647 """
David Howlett240f8fc2015-10-28 12:32:09 +0000648 return self.read(self.in_waiting)
649
Chris Liechti70b89232015-08-04 03:00:52 +0200650 def read_until(self, terminator=LF, size=None):
651 """\
652 Read until a termination sequence is found ('\n' by default), the size
653 is exceeded or until timeout occurs.
654 """
655 lenterm = len(terminator)
656 line = bytearray()
Chris Liechti6f03c0b2016-12-22 23:51:34 +0100657 timeout = Timeout(self._timeout)
Chris Liechti70b89232015-08-04 03:00:52 +0200658 while True:
659 c = self.read(1)
660 if c:
661 line += c
662 if line[-lenterm:] == terminator:
663 break
664 if size is not None and len(line) >= size:
665 break
666 else:
667 break
Chris Liechti6f03c0b2016-12-22 23:51:34 +0100668 if timeout.expired():
669 break
Chris Liechti70b89232015-08-04 03:00:52 +0200670 return bytes(line)
671
Chris Liechti70b89232015-08-04 03:00:52 +0200672 def iread_until(self, *args, **kwargs):
673 """\
674 Read lines, implemented as generator. It will raise StopIteration on
675 timeout (empty read).
676 """
677 while True:
678 line = self.read_until(*args, **kwargs)
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200679 if not line:
680 break
Chris Liechti70b89232015-08-04 03:00:52 +0200681 yield line
cliechtif81362e2009-07-25 03:44:33 +0000682
Chris Liechti779b1a22015-08-04 14:54:22 +0200683
684# - - - - - - - - - - - - - - - - - - - - - - - - -
cliechtid6bf52c2003-10-01 02:28:12 +0000685if __name__ == '__main__':
cliechtif81362e2009-07-25 03:44:33 +0000686 import sys
cliechtid6bf52c2003-10-01 02:28:12 +0000687 s = SerialBase()
Chris Liechti984c5c52016-02-15 23:48:45 +0100688 sys.stdout.write('port name: {}\n'.format(s.name))
689 sys.stdout.write('baud rates: {}\n'.format(s.BAUDRATES))
690 sys.stdout.write('byte sizes: {}\n'.format(s.BYTESIZES))
691 sys.stdout.write('parities: {}\n'.format(s.PARITIES))
692 sys.stdout.write('stop bits: {}\n'.format(s.STOPBITS))
693 sys.stdout.write('{}\n'.format(s))