blob: 547dc565b484118c5a3a18c3e6dd7efc6b3a0ce2 [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:
65 b = bytearray()
66 for item in seq:
Chris Liechti07447732015-08-05 00:39:12 +020067 # this one handles int and bytes in Python 2.7
68 # add conversion in case of Python 3.x
69 if isinstance(item, bytes):
70 item = ord(item)
71 b.append(item)
cliechti38077122013-10-16 02:57:27 +000072 return bytes(b)
cliechti32c10332009-08-05 13:23:43 +000073
74# create control bytes
Chris Liechticf29a352015-10-23 22:03:40 +020075XON = to_bytes([17])
cliechti32c10332009-08-05 13:23:43 +000076XOFF = to_bytes([19])
cliechti4a567a02009-07-27 22:09:31 +000077
cliechti8e99b6f2010-07-21 15:46:39 +000078CR = to_bytes([13])
79LF = to_bytes([10])
80
cliechtia3a811f2009-07-29 21:59:03 +000081
cliechti0d6029a2008-06-21 01:28:46 +000082PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
cliechti58b481c2009-02-16 20:42:32 +000083STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO = (1, 1.5, 2)
cliechti14b274a2009-02-07 00:27:05 +000084FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8)
cliechtid6bf52c2003-10-01 02:28:12 +000085
86PARITY_NAMES = {
Chris Liechti033f17c2015-08-30 21:28:04 +020087 PARITY_NONE: 'None',
88 PARITY_EVEN: 'Even',
89 PARITY_ODD: 'Odd',
90 PARITY_MARK: 'Mark',
cliechti4a567a02009-07-27 22:09:31 +000091 PARITY_SPACE: 'Space',
cliechtid6bf52c2003-10-01 02:28:12 +000092}
93
cliechti1dbe4b62002-02-14 02:49:25 +000094
cliechti4a567a02009-07-27 22:09:31 +000095class SerialException(IOError):
cliechtid6bf52c2003-10-01 02:28:12 +000096 """Base class for serial port related exceptions."""
cliechti7fe54d52002-03-03 20:11:47 +000097
cliechtid6bf52c2003-10-01 02:28:12 +000098
cliechti62611612004-04-20 01:55:43 +000099class SerialTimeoutException(SerialException):
100 """Write timeouts give an exception"""
101
cliechti4a567a02009-07-27 22:09:31 +0000102
cliechti4b20ec62012-08-16 01:04:44 +0000103writeTimeoutError = SerialTimeoutException('Write timeout')
104portNotOpenError = SerialException('Attempting to use a port that is not open')
cliechti62611612004-04-20 01:55:43 +0000105
cliechtif81362e2009-07-25 03:44:33 +0000106
Chris Liechti935a2622016-08-30 23:39:15 +0200107class Timeout(object):
108 """\
Chris Liechti514f76c2016-09-02 22:32:37 +0200109 Abstraction for timeout operations. Using time.monotonic() if available
110 or time.time() in all other cases.
Chris Liechti06ed4a52016-09-03 23:53:12 +0200111
112 The class can also be initialized with 0 or None, in order to support
113 non-blocking and fully blocking I/O operations. The attributes
114 is_non_blocking and is_infinite are set accordingly.
Chris Liechti935a2622016-08-30 23:39:15 +0200115 """
Chris Liechti514f76c2016-09-02 22:32:37 +0200116 if hasattr(time, 'monotonic'):
117 # Timeout implementation with time.monotonic(). This function is only
118 # supported by Python 3.3 and above. It returns a time in seconds
119 # (float) just as time.time(), but is not affected by system clock
120 # adjustments.
121 TIME = time.monotonic
122 else:
123 # Timeout implementation with time.time(). This is compatible with all
124 # Python versions but has issues if the clock is adjusted while the
125 # timeout is running.
126 TIME = time.time
127
Chris Liechti935a2622016-08-30 23:39:15 +0200128 def __init__(self, duration):
129 """Initialize a timeout with given duration"""
130 self.is_infinite = (duration is None)
131 self.is_non_blocking = (duration == 0)
Chris Liechti03513322016-09-04 23:35:53 +0200132 self.duration = duration
Chris Liechti935a2622016-08-30 23:39:15 +0200133 if duration is not None:
Chris Liechti514f76c2016-09-02 22:32:37 +0200134 self.target_time = self.TIME() + duration
Chris Liechti935a2622016-08-30 23:39:15 +0200135 else:
136 self.target_time = None
137
138 def expired(self):
Chris Liechti06ed4a52016-09-03 23:53:12 +0200139 """Return a boolean, telling if the timeout has expired"""
Chris Liechti03513322016-09-04 23:35:53 +0200140 return self.target_time is not None and self.time_left() <= 0
Chris Liechti935a2622016-08-30 23:39:15 +0200141
142 def time_left(self):
143 """Return how many seconds are left until the timeout expires"""
144 if self.is_non_blocking:
145 return 0
146 elif self.is_infinite:
147 return None
148 else:
Chris Liechti03513322016-09-04 23:35:53 +0200149 delta = self.target_time - self.TIME()
150 if delta > self.duration:
151 # clock jumped, recalculate
152 self.target_time = self.TIME() + self.duration
153 return self.duration
154 else:
155 return max(0, delta)
Chris Liechti935a2622016-08-30 23:39:15 +0200156
Chris Liechtif0197252016-09-01 19:48:03 +0200157 def restart(self, duration):
Chris Liechti06ed4a52016-09-03 23:53:12 +0200158 """\
159 Restart a timeout, only supported if a timeout was already set up
160 before.
161 """
Chris Liechti03513322016-09-04 23:35:53 +0200162 self.duration = duration
Chris Liechti514f76c2016-09-02 22:32:37 +0200163 self.target_time = self.TIME() + duration
Chris Liechtif0197252016-09-01 19:48:03 +0200164
Chris Liechti935a2622016-08-30 23:39:15 +0200165
Chris Liechtief6b7b42015-08-06 22:19:26 +0200166class SerialBase(io.RawIOBase):
cliechti7d448562014-08-03 21:57:45 +0000167 """\
168 Serial port base class. Provides __init__ function and properties to
169 get/set port settings.
170 """
cliechti14b274a2009-02-07 00:27:05 +0000171
cliechtidfec0c82009-07-21 01:35:41 +0000172 # default values, may be overridden in subclasses that do not support all values
cliechtif81362e2009-07-25 03:44:33 +0000173 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
174 9600, 19200, 38400, 57600, 115200, 230400, 460800, 500000,
175 576000, 921600, 1000000, 1152000, 1500000, 2000000, 2500000,
176 3000000, 3500000, 4000000)
cliechtid6bf52c2003-10-01 02:28:12 +0000177 BYTESIZES = (FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS)
Chris Liechticf29a352015-10-23 22:03:40 +0200178 PARITIES = (PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE)
179 STOPBITS = (STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO)
cliechti14b274a2009-02-07 00:27:05 +0000180
cliechtid6bf52c2003-10-01 02:28:12 +0000181 def __init__(self,
Chris Liechtid6bcaaf2016-02-01 22:55:26 +0100182 port=None,
183 baudrate=9600,
184 bytesize=EIGHTBITS,
185 parity=PARITY_NONE,
186 stopbits=STOPBITS_ONE,
187 timeout=None,
188 xonxoff=False,
189 rtscts=False,
190 write_timeout=None,
191 dsrdtr=False,
192 inter_byte_timeout=None,
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100193 **kwargs):
cliechti7d448562014-08-03 21:57:45 +0000194 """\
Chris Liechtid6bcaaf2016-02-01 22:55:26 +0100195 Initialize comm port object. If a "port" is given, then the port will be
cliechti7d448562014-08-03 21:57:45 +0000196 opened immediately. Otherwise a Serial port object in closed state
197 is returned.
198 """
cliechtid6bf52c2003-10-01 02:28:12 +0000199
Chris Liechti033f17c2015-08-30 21:28:04 +0200200 self.is_open = False
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100201 self.portstr = None
202 self.name = None
Chris Liechtic14bba82016-01-02 23:23:11 +0100203 # correct values are assigned below through properties
204 self._port = None
205 self._baudrate = None
206 self._bytesize = None
207 self._parity = None
208 self._stopbits = None
209 self._timeout = None
210 self._write_timeout = None
211 self._xonxoff = None
212 self._rtscts = None
213 self._dsrdtr = None
214 self._inter_byte_timeout = None
Chris Liechti033f17c2015-08-30 21:28:04 +0200215 self._rs485_mode = None # disabled by default
Chris Liechtif7534c82016-05-07 23:35:54 +0200216 self._rts_state = True
217 self._dtr_state = True
Chris Liechtief1fe252015-08-27 23:25:21 +0200218 self._break_state = False
cliechti14b274a2009-02-07 00:27:05 +0000219
220 # assign values using get/set methods using the properties feature
Chris Liechti033f17c2015-08-30 21:28:04 +0200221 self.port = port
cliechtid6bf52c2003-10-01 02:28:12 +0000222 self.baudrate = baudrate
223 self.bytesize = bytesize
Chris Liechti033f17c2015-08-30 21:28:04 +0200224 self.parity = parity
cliechtid6bf52c2003-10-01 02:28:12 +0000225 self.stopbits = stopbits
Chris Liechti033f17c2015-08-30 21:28:04 +0200226 self.timeout = timeout
Chris Liechti518b0d32015-08-30 02:20:39 +0200227 self.write_timeout = write_timeout
Chris Liechti033f17c2015-08-30 21:28:04 +0200228 self.xonxoff = xonxoff
229 self.rtscts = rtscts
230 self.dsrdtr = dsrdtr
Chris Liechtib5331752015-10-24 01:34:11 +0200231 self.inter_byte_timeout = inter_byte_timeout
Chris Liechtic14bba82016-01-02 23:23:11 +0100232 # watch for backward compatible kwargs
233 if 'writeTimeout' in kwargs:
234 self.write_timeout = kwargs.pop('writeTimeout')
235 if 'interCharTimeout' in kwargs:
236 self.inter_byte_timeout = kwargs.pop('interCharTimeout')
237 if kwargs:
Chris Liechti984c5c52016-02-15 23:48:45 +0100238 raise ValueError('unexpected keyword arguments: {!r}'.format(kwargs))
cliechti14b274a2009-02-07 00:27:05 +0000239
cliechtid6bf52c2003-10-01 02:28:12 +0000240 if port is not None:
241 self.open()
242
cliechtid6bf52c2003-10-01 02:28:12 +0000243 # - - - - - - - - - - - - - - - - - - - - - - - -
244
Chris Liechtia51b0bc2015-12-10 21:14:45 +0100245 # to be implemented by subclasses:
246 # def open(self):
247 # def close(self):
Chris Liechti5e763ca2015-12-09 13:01:26 +0100248
249 # - - - - - - - - - - - - - - - - - - - - - - - -
250
Chris Liechti779b1a22015-08-04 14:54:22 +0200251 @property
252 def port(self):
253 """\
254 Get the current port setting. The value that was passed on init or using
Chris Liechtibf9e3182016-04-22 21:31:09 +0200255 setPort() is passed back.
Chris Liechti779b1a22015-08-04 14:54:22 +0200256 """
257 return self._port
258
259 @port.setter
260 def port(self, port):
cliechti7d448562014-08-03 21:57:45 +0000261 """\
Chris Liechtibf9e3182016-04-22 21:31:09 +0200262 Change the port.
cliechti7d448562014-08-03 21:57:45 +0000263 """
Chris Liechtif41b4592016-05-11 15:11:27 +0200264 if port is not None and not isinstance(port, basestring):
Chris Liechtibf9e3182016-04-22 21:31:09 +0200265 raise ValueError('"port" must be None or a string, not {}'.format(type(port)))
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200266 was_open = self.is_open
267 if was_open:
268 self.close()
Chris Liechti68340d72015-08-03 14:15:48 +0200269 self.portstr = port
cliechtid6bf52c2003-10-01 02:28:12 +0000270 self._port = port
cliechtif81362e2009-07-25 03:44:33 +0000271 self.name = self.portstr
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200272 if was_open:
273 self.open()
cliechti14b274a2009-02-07 00:27:05 +0000274
Chris Liechti779b1a22015-08-04 14:54:22 +0200275 @property
276 def baudrate(self):
277 """Get the current baud rate setting."""
278 return self._baudrate
cliechtid6bf52c2003-10-01 02:28:12 +0000279
Chris Liechti779b1a22015-08-04 14:54:22 +0200280 @baudrate.setter
281 def baudrate(self, baudrate):
cliechti7d448562014-08-03 21:57:45 +0000282 """\
283 Change baud rate. It raises a ValueError if the port is open and the
cliechti2750b832009-07-28 00:13:52 +0000284 baud rate is not possible. If the port is closed, then the value is
cliechti7d448562014-08-03 21:57:45 +0000285 accepted and the exception is raised when the port is opened.
286 """
cliechti107db8d2004-01-15 01:20:23 +0000287 try:
cliechtie30868d2013-10-16 15:35:11 +0000288 b = int(baudrate)
cliechti107db8d2004-01-15 01:20:23 +0000289 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100290 raise ValueError("Not a valid baudrate: {!r}".format(baudrate))
cliechti107db8d2004-01-15 01:20:23 +0000291 else:
Chris Liechtia83408a2016-05-23 22:18:43 +0200292 if b < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100293 raise ValueError("Not a valid baudrate: {!r}".format(baudrate))
cliechtie30868d2013-10-16 15:35:11 +0000294 self._baudrate = b
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200295 if self.is_open:
296 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000297
Chris Liechti779b1a22015-08-04 14:54:22 +0200298 @property
299 def bytesize(self):
300 """Get the current byte size setting."""
301 return self._bytesize
cliechtid6bf52c2003-10-01 02:28:12 +0000302
Chris Liechti779b1a22015-08-04 14:54:22 +0200303 @bytesize.setter
304 def bytesize(self, bytesize):
cliechtid6bf52c2003-10-01 02:28:12 +0000305 """Change byte size."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200306 if bytesize not in self.BYTESIZES:
Chris Liechti984c5c52016-02-15 23:48:45 +0100307 raise ValueError("Not a valid byte size: {!r}".format(bytesize))
cliechtid6bf52c2003-10-01 02:28:12 +0000308 self._bytesize = bytesize
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200309 if self.is_open:
310 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000311
Chris Liechti779b1a22015-08-04 14:54:22 +0200312 @property
313 def parity(self):
314 """Get the current parity setting."""
315 return self._parity
316
317 @parity.setter
318 def parity(self, parity):
cliechtid6bf52c2003-10-01 02:28:12 +0000319 """Change parity setting."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200320 if parity not in self.PARITIES:
Chris Liechti984c5c52016-02-15 23:48:45 +0100321 raise ValueError("Not a valid parity: {!r}".format(parity))
cliechtid6bf52c2003-10-01 02:28:12 +0000322 self._parity = parity
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200323 if self.is_open:
324 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000325
Chris Liechti779b1a22015-08-04 14:54:22 +0200326 @property
327 def stopbits(self):
328 """Get the current stop bits setting."""
329 return self._stopbits
330
331 @stopbits.setter
332 def stopbits(self, stopbits):
cliechti4a567a02009-07-27 22:09:31 +0000333 """Change stop bits size."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200334 if stopbits not in self.STOPBITS:
Chris Liechti984c5c52016-02-15 23:48:45 +0100335 raise ValueError("Not a valid stop bit size: {!r}".format(stopbits))
cliechtid6bf52c2003-10-01 02:28:12 +0000336 self._stopbits = stopbits
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200337 if self.is_open:
338 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000339
Chris Liechti779b1a22015-08-04 14:54:22 +0200340 @property
341 def timeout(self):
342 """Get the current timeout setting."""
343 return self._timeout
cliechtid6bf52c2003-10-01 02:28:12 +0000344
Chris Liechti779b1a22015-08-04 14:54:22 +0200345 @timeout.setter
346 def timeout(self, timeout):
cliechtid6bf52c2003-10-01 02:28:12 +0000347 """Change timeout setting."""
348 if timeout is not None:
cliechtid6bf52c2003-10-01 02:28:12 +0000349 try:
cliechti14b274a2009-02-07 00:27:05 +0000350 timeout + 1 # test if it's a number, will throw a TypeError if not...
cliechtid6bf52c2003-10-01 02:28:12 +0000351 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100352 raise ValueError("Not a valid timeout: {!r}".format(timeout))
Chris Liechticf29a352015-10-23 22:03:40 +0200353 if timeout < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100354 raise ValueError("Not a valid timeout: {!r}".format(timeout))
cliechtid6bf52c2003-10-01 02:28:12 +0000355 self._timeout = timeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200356 if self.is_open:
357 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000358
Chris Liechti779b1a22015-08-04 14:54:22 +0200359 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200360 def write_timeout(self):
cliechtid6bf52c2003-10-01 02:28:12 +0000361 """Get the current timeout setting."""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200362 return self._write_timeout
cliechti14b274a2009-02-07 00:27:05 +0000363
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200364 @write_timeout.setter
365 def write_timeout(self, timeout):
cliechti62611612004-04-20 01:55:43 +0000366 """Change timeout setting."""
367 if timeout is not None:
Chris Liechti033f17c2015-08-30 21:28:04 +0200368 if timeout < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100369 raise ValueError("Not a valid timeout: {!r}".format(timeout))
cliechti62611612004-04-20 01:55:43 +0000370 try:
Chris Liechti033f17c2015-08-30 21:28:04 +0200371 timeout + 1 # test if it's a number, will throw a TypeError if not...
cliechti62611612004-04-20 01:55:43 +0000372 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100373 raise ValueError("Not a valid timeout: {!r}".format(timeout))
cliechti14b274a2009-02-07 00:27:05 +0000374
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200375 self._write_timeout = timeout
376 if self.is_open:
377 self._reconfigure_port()
378
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200379 @property
Chris Liechti518b0d32015-08-30 02:20:39 +0200380 def inter_byte_timeout(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200381 """Get the current inter-character timeout setting."""
Chris Liechti96242372015-09-02 02:49:49 +0200382 return self._inter_byte_timeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200383
Chris Liechti518b0d32015-08-30 02:20:39 +0200384 @inter_byte_timeout.setter
385 def inter_byte_timeout(self, ic_timeout):
386 """Change inter-byte timeout setting."""
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200387 if ic_timeout is not None:
Chris Liechti033f17c2015-08-30 21:28:04 +0200388 if ic_timeout < 0:
Chris Liechti984c5c52016-02-15 23:48:45 +0100389 raise ValueError("Not a valid timeout: {!r}".format(ic_timeout))
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200390 try:
391 ic_timeout + 1 # test if it's a number, will throw a TypeError if not...
392 except TypeError:
Chris Liechti984c5c52016-02-15 23:48:45 +0100393 raise ValueError("Not a valid timeout: {!r}".format(ic_timeout))
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200394
Chris Liechti518b0d32015-08-30 02:20:39 +0200395 self._inter_byte_timeout = ic_timeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200396 if self.is_open:
397 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000398
Chris Liechti779b1a22015-08-04 14:54:22 +0200399 @property
400 def xonxoff(self):
401 """Get the current XON/XOFF setting."""
402 return self._xonxoff
cliechtid6bf52c2003-10-01 02:28:12 +0000403
Chris Liechti779b1a22015-08-04 14:54:22 +0200404 @xonxoff.setter
405 def xonxoff(self, xonxoff):
cliechti4a567a02009-07-27 22:09:31 +0000406 """Change XON/XOFF setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000407 self._xonxoff = xonxoff
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200408 if self.is_open:
409 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000410
Chris Liechti779b1a22015-08-04 14:54:22 +0200411 @property
412 def rtscts(self):
413 """Get the current RTS/CTS flow control setting."""
414 return self._rtscts
cliechtid6bf52c2003-10-01 02:28:12 +0000415
Chris Liechti779b1a22015-08-04 14:54:22 +0200416 @rtscts.setter
417 def rtscts(self, rtscts):
cliechti4a567a02009-07-27 22:09:31 +0000418 """Change RTS/CTS flow control setting."""
cliechtid6bf52c2003-10-01 02:28:12 +0000419 self._rtscts = rtscts
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200420 if self.is_open:
421 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000422
Chris Liechti779b1a22015-08-04 14:54:22 +0200423 @property
424 def dsrdtr(self):
425 """Get the current DSR/DTR flow control setting."""
426 return self._dsrdtr
cliechtid6bf52c2003-10-01 02:28:12 +0000427
Chris Liechti779b1a22015-08-04 14:54:22 +0200428 @dsrdtr.setter
429 def dsrdtr(self, dsrdtr=None):
cliechtif46e0a82005-05-19 15:24:57 +0000430 """Change DsrDtr flow control setting."""
431 if dsrdtr is None:
cliechti14b274a2009-02-07 00:27:05 +0000432 # if not set, keep backwards compatibility and follow rtscts setting
cliechtif46e0a82005-05-19 15:24:57 +0000433 self._dsrdtr = self._rtscts
434 else:
cliechti14b274a2009-02-07 00:27:05 +0000435 # if defined independently, follow its value
cliechtif46e0a82005-05-19 15:24:57 +0000436 self._dsrdtr = dsrdtr
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200437 if self.is_open:
438 self._reconfigure_port()
cliechti14b274a2009-02-07 00:27:05 +0000439
Chris Liechti779b1a22015-08-04 14:54:22 +0200440 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200441 def rts(self):
442 return self._rts_state
cliechti679bfa62008-06-20 23:58:15 +0000443
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200444 @rts.setter
445 def rts(self, value):
446 self._rts_state = value
447 if self.is_open:
448 self._update_rts_state()
cliechti14b274a2009-02-07 00:27:05 +0000449
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200450 @property
451 def dtr(self):
452 return self._dtr_state
cliechti14b274a2009-02-07 00:27:05 +0000453
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200454 @dtr.setter
455 def dtr(self, value):
456 self._dtr_state = value
457 if self.is_open:
458 self._update_dtr_state()
459
460 @property
461 def break_condition(self):
462 return self._break_state
463
464 @break_condition.setter
465 def break_condition(self, value):
466 self._break_state = value
467 if self.is_open:
468 self._update_break_state()
cliechti679bfa62008-06-20 23:58:15 +0000469
cliechti4065dce2009-08-10 00:55:46 +0000470 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti33f0ec52015-08-06 16:37:21 +0200471 # functions useful for RS-485 adapters
472
473 @property
474 def rs485_mode(self):
475 """\
476 Enable RS485 mode and apply new settings, set to None to disable.
477 See serial.rs485.RS485Settings for more info about the value.
478 """
479 return self._rs485_mode
480
481 @rs485_mode.setter
482 def rs485_mode(self, rs485_settings):
483 self._rs485_mode = rs485_settings
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200484 if self.is_open:
485 self._reconfigure_port()
Chris Liechti33f0ec52015-08-06 16:37:21 +0200486
487 # - - - - - - - - - - - - - - - - - - - - - - - -
cliechti4065dce2009-08-10 00:55:46 +0000488
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200489 _SAVED_SETTINGS = ('baudrate', 'bytesize', 'parity', 'stopbits', 'xonxoff',
Chris Liechti033f17c2015-08-30 21:28:04 +0200490 'dsrdtr', 'rtscts', 'timeout', 'write_timeout',
Chris Liechti1c3249f2015-09-01 02:31:36 +0200491 'inter_byte_timeout')
cliechti4065dce2009-08-10 00:55:46 +0000492
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200493 def get_settings(self):
cliechti7d448562014-08-03 21:57:45 +0000494 """\
495 Get current port settings as a dictionary. For use with
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200496 apply_settings().
cliechti7d448562014-08-03 21:57:45 +0000497 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200498 return dict([(key, getattr(self, '_' + key)) for key in self._SAVED_SETTINGS])
cliechti4065dce2009-08-10 00:55:46 +0000499
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200500 def apply_settings(self, d):
cliechti7d448562014-08-03 21:57:45 +0000501 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200502 Apply stored settings from a dictionary returned from
503 get_settings(). It's allowed to delete keys from the dictionary. These
cliechti7d448562014-08-03 21:57:45 +0000504 values will simply left unchanged.
505 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200506 for key in self._SAVED_SETTINGS:
Chris Liechti033f17c2015-08-30 21:28:04 +0200507 if key in d and d[key] != getattr(self, '_' + key): # check against internal "_" value
cliechti4065dce2009-08-10 00:55:46 +0000508 setattr(self, key, d[key]) # set non "_" value to use properties write function
cliechti679bfa62008-06-20 23:58:15 +0000509
cliechtid6bf52c2003-10-01 02:28:12 +0000510 # - - - - - - - - - - - - - - - - - - - - - - - -
511
512 def __repr__(self):
513 """String representation of the current port settings and its state."""
Chris Liechti984c5c52016-02-15 23:48:45 +0100514 return '{name}<id=0x{id:x}, open={p.is_open}>(port={p.portstr!r}, ' \
515 'baudrate={p.baudrate!r}, bytesize={p.bytesize!r}, parity={p.parity!r}, ' \
516 'stopbits={p.stopbits!r}, timeout={p.timeout!r}, xonxoff={p.xonxoff!r}, ' \
517 'rtscts={p.rtscts!r}, dsrdtr={p.dsrdtr!r})'.format(
518 name=self.__class__.__name__, id=id(self), p=self)
cliechtid6bf52c2003-10-01 02:28:12 +0000519
cliechti4a567a02009-07-27 22:09:31 +0000520 # - - - - - - - - - - - - - - - - - - - - - - - -
521 # compatibility with io library
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100522 # pylint: disable=invalid-name,missing-docstring
cliechti4a567a02009-07-27 22:09:31 +0000523
Chris Liechti033f17c2015-08-30 21:28:04 +0200524 def readable(self):
525 return True
526
527 def writable(self):
528 return True
529
530 def seekable(self):
531 return False
532
cliechti4a567a02009-07-27 22:09:31 +0000533 def readinto(self, b):
534 data = self.read(len(b))
535 n = len(data)
536 try:
537 b[:n] = data
Chris Liechti68340d72015-08-03 14:15:48 +0200538 except TypeError as err:
cliechti4a567a02009-07-27 22:09:31 +0000539 import array
540 if not isinstance(b, array.array):
541 raise err
542 b[:n] = array.array('b', data)
543 return n
cliechtif81362e2009-07-25 03:44:33 +0000544
Chris Liechti70b89232015-08-04 03:00:52 +0200545 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti779b1a22015-08-04 14:54:22 +0200546 # context manager
547
548 def __enter__(self):
549 return self
550
551 def __exit__(self, *args, **kwargs):
552 self.close()
553
554 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtief1fe252015-08-27 23:25:21 +0200555
556 def send_break(self, duration=0.25):
557 """\
558 Send break condition. Timed, returns to idle state after given
559 duration.
560 """
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200561 if not self.is_open:
562 raise portNotOpenError
Chris Liechtief1fe252015-08-27 23:25:21 +0200563 self.break_condition = True
564 time.sleep(duration)
565 self.break_condition = False
566
567 # - - - - - - - - - - - - - - - - - - - - - - - -
568 # backwards compatibility / deprecated functions
569
570 def flushInput(self):
571 self.reset_input_buffer()
572
573 def flushOutput(self):
574 self.reset_output_buffer()
575
576 def inWaiting(self):
577 return self.in_waiting
578
579 def sendBreak(self, duration=0.25):
580 self.send_break(duration)
581
582 def setRTS(self, value=1):
583 self.rts = value
584
585 def setDTR(self, value=1):
586 self.dtr = value
587
588 def getCTS(self):
589 return self.cts
590
591 def getDSR(self):
592 return self.dsr
593
594 def getRI(self):
595 return self.ri
596
597 def getCD(self):
598 return self.cd
599
Chris Liechti0eba2a62016-04-06 02:55:51 +0200600 def setPort(self, port):
601 self.port = port
602
Chris Liechtief1fe252015-08-27 23:25:21 +0200603 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200604 def writeTimeout(self):
605 return self.write_timeout
606
607 @writeTimeout.setter
608 def writeTimeout(self, timeout):
609 self.write_timeout = timeout
Chris Liechtief1fe252015-08-27 23:25:21 +0200610
611 @property
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200612 def interCharTimeout(self):
Chris Liechti96242372015-09-02 02:49:49 +0200613 return self.inter_byte_timeout
Chris Liechtief1fe252015-08-27 23:25:21 +0200614
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200615 @interCharTimeout.setter
616 def interCharTimeout(self, interCharTimeout):
Chris Liechti96242372015-09-02 02:49:49 +0200617 self.inter_byte_timeout = interCharTimeout
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200618
619 def getSettingsDict(self):
620 return self.get_settings()
621
622 def applySettingsDict(self, d):
623 self.apply_settings(d)
624
625 def isOpen(self):
Chris Liechti16843852015-09-22 23:24:35 +0200626 return self.is_open
Chris Liechtief1fe252015-08-27 23:25:21 +0200627
628 # - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti70b89232015-08-04 03:00:52 +0200629 # additional functionality
630
David Howlett240f8fc2015-10-28 12:32:09 +0000631 def read_all(self):
Chris Liechti03cb8ed2015-10-30 23:37:24 +0100632 """\
633 Read all bytes currently available in the buffer of the OS.
634 """
David Howlett240f8fc2015-10-28 12:32:09 +0000635 return self.read(self.in_waiting)
636
Chris Liechti70b89232015-08-04 03:00:52 +0200637 def read_until(self, terminator=LF, size=None):
638 """\
639 Read until a termination sequence is found ('\n' by default), the size
640 is exceeded or until timeout occurs.
641 """
642 lenterm = len(terminator)
643 line = bytearray()
644 while True:
645 c = self.read(1)
646 if c:
647 line += c
648 if line[-lenterm:] == terminator:
649 break
650 if size is not None and len(line) >= size:
651 break
652 else:
653 break
654 return bytes(line)
655
Chris Liechti70b89232015-08-04 03:00:52 +0200656 def iread_until(self, *args, **kwargs):
657 """\
658 Read lines, implemented as generator. It will raise StopIteration on
659 timeout (empty read).
660 """
661 while True:
662 line = self.read_until(*args, **kwargs)
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200663 if not line:
664 break
Chris Liechti70b89232015-08-04 03:00:52 +0200665 yield line
cliechtif81362e2009-07-25 03:44:33 +0000666
Chris Liechti779b1a22015-08-04 14:54:22 +0200667
668# - - - - - - - - - - - - - - - - - - - - - - - - -
cliechtid6bf52c2003-10-01 02:28:12 +0000669if __name__ == '__main__':
cliechtif81362e2009-07-25 03:44:33 +0000670 import sys
cliechtid6bf52c2003-10-01 02:28:12 +0000671 s = SerialBase()
Chris Liechti984c5c52016-02-15 23:48:45 +0100672 sys.stdout.write('port name: {}\n'.format(s.name))
673 sys.stdout.write('baud rates: {}\n'.format(s.BAUDRATES))
674 sys.stdout.write('byte sizes: {}\n'.format(s.BYTESIZES))
675 sys.stdout.write('parities: {}\n'.format(s.PARITIES))
676 sys.stdout.write('stop bits: {}\n'.format(s.STOPBITS))
677 sys.stdout.write('{}\n'.format(s))