blob: 6f31efecbddaabe33d511cd9e06704ab44b91be7 [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001#! python
2#
3# Base class and support functions used by various backends.
4#
5# This file is part of pySerial. https://github.com/pyserial/pyserial
6# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
7#
8# SPDX-License-Identifier: BSD-3-Clause
9
10import io
11import time
12
13# ``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):
21 # implementation does not matter as we do not realy use it.
22 # it just must not inherit from something else we might care for.
23 class memoryview(object):
24 pass
25
26try:
27 unicode
28except (NameError, AttributeError):
29 unicode = str # for Python 3
30
31
32# "for byte in data" fails for python3 as it returns ints instead of bytes
33def iterbytes(b):
34 """Iterate over bytes, returning bytes instead of ints (python3)"""
35 if isinstance(b, memoryview):
36 b = b.tobytes()
37 x = 0
38 while True:
39 a = b[x:x + 1]
40 x += 1
41 if a:
42 yield a
43 else:
44 break
45
46
47# all Python versions prior 3.x convert ``str([17])`` to '[17]' instead of '\x11'
48# so a simple ``bytes(sequence)`` doesn't work for all versions
49def to_bytes(seq):
50 """convert a sequence to a bytes type"""
51 if isinstance(seq, bytes):
52 return seq
53 elif isinstance(seq, bytearray):
54 return bytes(seq)
55 elif isinstance(seq, memoryview):
56 return seq.tobytes()
57 elif isinstance(seq, unicode):
58 raise TypeError('unicode strings are not supported, please encode to bytes: %r' % (seq,))
59 else:
60 b = bytearray()
61 for item in seq:
62 # this one handles int and bytes in Python 2.7
63 # add conversion in case of Python 3.x
64 if isinstance(item, bytes):
65 item = ord(item)
66 b.append(item)
67 return bytes(b)
68
69# create control bytes
70XON = to_bytes([17])
71XOFF = to_bytes([19])
72
73CR = to_bytes([13])
74LF = to_bytes([10])
75
76
77PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
78STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO = (1, 1.5, 2)
79FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8)
80
81PARITY_NAMES = {
82 PARITY_NONE: 'None',
83 PARITY_EVEN: 'Even',
84 PARITY_ODD: 'Odd',
85 PARITY_MARK: 'Mark',
86 PARITY_SPACE: 'Space',
87}
88
89
90class SerialException(IOError):
91 """Base class for serial port related exceptions."""
92
93
94class SerialTimeoutException(SerialException):
95 """Write timeouts give an exception"""
96
97
98writeTimeoutError = SerialTimeoutException('Write timeout')
99portNotOpenError = SerialException('Attempting to use a port that is not open')
100
101
102class SerialBase(io.RawIOBase):
103 """\
104 Serial port base class. Provides __init__ function and properties to
105 get/set port settings.
106 """
107
108 # default values, may be overridden in subclasses that do not support all values
109 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
110 9600, 19200, 38400, 57600, 115200, 230400, 460800, 500000,
111 576000, 921600, 1000000, 1152000, 1500000, 2000000, 2500000,
112 3000000, 3500000, 4000000)
113 BYTESIZES = (FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS)
114 PARITIES = (PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE)
115 STOPBITS = (STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO)
116
117 def __init__(self,
118 port=None, # number of device, numbering starts at
119 # zero. if everything fails, the user
120 # can specify a device string, note
121 # that this isn't portable anymore
122 # port will be opened if one is specified
123 baudrate=9600, # baud rate
124 bytesize=EIGHTBITS, # number of data bits
125 parity=PARITY_NONE, # enable parity checking
126 stopbits=STOPBITS_ONE, # number of stop bits
127 timeout=None, # set a timeout value, None to wait forever
128 xonxoff=False, # enable software flow control
129 rtscts=False, # enable RTS/CTS flow control
130 write_timeout=None, # set a timeout for writes
131 dsrdtr=False, # None: use rtscts setting, dsrdtr override if True or False
132 inter_byte_timeout=None, # Inter-character timeout, None to disable
133 **kwargs
134 ):
135 """\
136 Initialize comm port object. If a port is given, then the port will be
137 opened immediately. Otherwise a Serial port object in closed state
138 is returned.
139 """
140
141 self.is_open = False
142 # correct values are assigned below through properties
143 self._port = None
144 self._baudrate = None
145 self._bytesize = None
146 self._parity = None
147 self._stopbits = None
148 self._timeout = None
149 self._write_timeout = None
150 self._xonxoff = None
151 self._rtscts = None
152 self._dsrdtr = None
153 self._inter_byte_timeout = None
154 self._rs485_mode = None # disabled by default
155 self._rts_state = True
156 self._dtr_state = True
157 self._break_state = False
158
159 # assign values using get/set methods using the properties feature
160 self.port = port
161 self.baudrate = baudrate
162 self.bytesize = bytesize
163 self.parity = parity
164 self.stopbits = stopbits
165 self.timeout = timeout
166 self.write_timeout = write_timeout
167 self.xonxoff = xonxoff
168 self.rtscts = rtscts
169 self.dsrdtr = dsrdtr
170 self.inter_byte_timeout = inter_byte_timeout
171 # watch for backward compatible kwargs
172 if 'writeTimeout' in kwargs:
173 self.write_timeout = kwargs.pop('writeTimeout')
174 if 'interCharTimeout' in kwargs:
175 self.inter_byte_timeout = kwargs.pop('interCharTimeout')
176 if kwargs:
177 raise ValueError('unexpected keyword arguments: %r' % (kwargs,))
178
179 if port is not None:
180 self.open()
181
182 # - - - - - - - - - - - - - - - - - - - - - - - -
183
184 # to be implemented by subclasses:
185 # def open(self):
186 # def close(self):
187
188 # - - - - - - - - - - - - - - - - - - - - - - - -
189
190 @property
191 def port(self):
192 """\
193 Get the current port setting. The value that was passed on init or using
194 setPort() is passed back. See also the attribute portstr which contains
195 the name of the port as a string.
196 """
197 return self._port
198
199 @port.setter
200 def port(self, port):
201 """\
202 Change the port. The attribute portstr is set to a string that
203 contains the name of the port.
204 """
205
206 was_open = self.is_open
207 if was_open:
208 self.close()
209 self.portstr = port
210 self._port = port
211 self.name = self.portstr
212 if was_open:
213 self.open()
214
215
216 @property
217 def baudrate(self):
218 """Get the current baud rate setting."""
219 return self._baudrate
220
221 @baudrate.setter
222 def baudrate(self, baudrate):
223 """\
224 Change baud rate. It raises a ValueError if the port is open and the
225 baud rate is not possible. If the port is closed, then the value is
226 accepted and the exception is raised when the port is opened.
227 """
228 try:
229 b = int(baudrate)
230 except TypeError:
231 raise ValueError("Not a valid baudrate: %r" % (baudrate,))
232 else:
233 if b <= 0:
234 raise ValueError("Not a valid baudrate: %r" % (baudrate,))
235 self._baudrate = b
236 if self.is_open:
237 self._reconfigure_port()
238
239
240 @property
241 def bytesize(self):
242 """Get the current byte size setting."""
243 return self._bytesize
244
245 @bytesize.setter
246 def bytesize(self, bytesize):
247 """Change byte size."""
248 if bytesize not in self.BYTESIZES:
249 raise ValueError("Not a valid byte size: %r" % (bytesize,))
250 self._bytesize = bytesize
251 if self.is_open:
252 self._reconfigure_port()
253
254
255
256 @property
257 def parity(self):
258 """Get the current parity setting."""
259 return self._parity
260
261 @parity.setter
262 def parity(self, parity):
263 """Change parity setting."""
264 if parity not in self.PARITIES:
265 raise ValueError("Not a valid parity: %r" % (parity,))
266 self._parity = parity
267 if self.is_open:
268 self._reconfigure_port()
269
270
271
272 @property
273 def stopbits(self):
274 """Get the current stop bits setting."""
275 return self._stopbits
276
277 @stopbits.setter
278 def stopbits(self, stopbits):
279 """Change stop bits size."""
280 if stopbits not in self.STOPBITS:
281 raise ValueError("Not a valid stop bit size: %r" % (stopbits,))
282 self._stopbits = stopbits
283 if self.is_open:
284 self._reconfigure_port()
285
286
287 @property
288 def timeout(self):
289 """Get the current timeout setting."""
290 return self._timeout
291
292 @timeout.setter
293 def timeout(self, timeout):
294 """Change timeout setting."""
295 if timeout is not None:
296 try:
297 timeout + 1 # test if it's a number, will throw a TypeError if not...
298 except TypeError:
299 raise ValueError("Not a valid timeout: %r" % (timeout,))
300 if timeout < 0:
301 raise ValueError("Not a valid timeout: %r" % (timeout,))
302 self._timeout = timeout
303 if self.is_open:
304 self._reconfigure_port()
305
306
307 @property
308 def write_timeout(self):
309 """Get the current timeout setting."""
310 return self._write_timeout
311
312 @write_timeout.setter
313 def write_timeout(self, timeout):
314 """Change timeout setting."""
315 if timeout is not None:
316 if timeout < 0:
317 raise ValueError("Not a valid timeout: %r" % (timeout,))
318 try:
319 timeout + 1 # test if it's a number, will throw a TypeError if not...
320 except TypeError:
321 raise ValueError("Not a valid timeout: %r" % timeout)
322
323 self._write_timeout = timeout
324 if self.is_open:
325 self._reconfigure_port()
326
327
328 @property
329 def inter_byte_timeout(self):
330 """Get the current inter-character timeout setting."""
331 return self._inter_byte_timeout
332
333 @inter_byte_timeout.setter
334 def inter_byte_timeout(self, ic_timeout):
335 """Change inter-byte timeout setting."""
336 if ic_timeout is not None:
337 if ic_timeout < 0:
338 raise ValueError("Not a valid timeout: %r" % ic_timeout)
339 try:
340 ic_timeout + 1 # test if it's a number, will throw a TypeError if not...
341 except TypeError:
342 raise ValueError("Not a valid timeout: %r" % ic_timeout)
343
344 self._inter_byte_timeout = ic_timeout
345 if self.is_open:
346 self._reconfigure_port()
347
348
349 @property
350 def xonxoff(self):
351 """Get the current XON/XOFF setting."""
352 return self._xonxoff
353
354 @xonxoff.setter
355 def xonxoff(self, xonxoff):
356 """Change XON/XOFF setting."""
357 self._xonxoff = xonxoff
358 if self.is_open:
359 self._reconfigure_port()
360
361
362 @property
363 def rtscts(self):
364 """Get the current RTS/CTS flow control setting."""
365 return self._rtscts
366
367 @rtscts.setter
368 def rtscts(self, rtscts):
369 """Change RTS/CTS flow control setting."""
370 self._rtscts = rtscts
371 if self.is_open:
372 self._reconfigure_port()
373
374
375 @property
376 def dsrdtr(self):
377 """Get the current DSR/DTR flow control setting."""
378 return self._dsrdtr
379
380 @dsrdtr.setter
381 def dsrdtr(self, dsrdtr=None):
382 """Change DsrDtr flow control setting."""
383 if dsrdtr is None:
384 # if not set, keep backwards compatibility and follow rtscts setting
385 self._dsrdtr = self._rtscts
386 else:
387 # if defined independently, follow its value
388 self._dsrdtr = dsrdtr
389 if self.is_open:
390 self._reconfigure_port()
391
392
393 @property
394 def rts(self):
395 return self._rts_state
396
397 @rts.setter
398 def rts(self, value):
399 self._rts_state = value
400 if self.is_open:
401 self._update_rts_state()
402
403 @property
404 def dtr(self):
405 return self._dtr_state
406
407 @dtr.setter
408 def dtr(self, value):
409 self._dtr_state = value
410 if self.is_open:
411 self._update_dtr_state()
412
413 @property
414 def break_condition(self):
415 return self._break_state
416
417 @break_condition.setter
418 def break_condition(self, value):
419 self._break_state = value
420 if self.is_open:
421 self._update_break_state()
422
423 # - - - - - - - - - - - - - - - - - - - - - - - -
424 # functions useful for RS-485 adapters
425
426 @property
427 def rs485_mode(self):
428 """\
429 Enable RS485 mode and apply new settings, set to None to disable.
430 See serial.rs485.RS485Settings for more info about the value.
431 """
432 return self._rs485_mode
433
434 @rs485_mode.setter
435 def rs485_mode(self, rs485_settings):
436 self._rs485_mode = rs485_settings
437 if self.is_open:
438 self._reconfigure_port()
439
440 # - - - - - - - - - - - - - - - - - - - - - - - -
441
442 _SAVED_SETTINGS = ('baudrate', 'bytesize', 'parity', 'stopbits', 'xonxoff',
443 'dsrdtr', 'rtscts', 'timeout', 'write_timeout',
444 'inter_byte_timeout')
445
446 def get_settings(self):
447 """\
448 Get current port settings as a dictionary. For use with
449 apply_settings().
450 """
451 return dict([(key, getattr(self, '_' + key)) for key in self._SAVED_SETTINGS])
452
453 def apply_settings(self, d):
454 """\
455 Apply stored settings from a dictionary returned from
456 get_settings(). It's allowed to delete keys from the dictionary. These
457 values will simply left unchanged.
458 """
459 for key in self._SAVED_SETTINGS:
460 if key in d and d[key] != getattr(self, '_' + key): # check against internal "_" value
461 setattr(self, key, d[key]) # set non "_" value to use properties write function
462
463 # - - - - - - - - - - - - - - - - - - - - - - - -
464
465 def __repr__(self):
466 """String representation of the current port settings and its state."""
467 return "%s<id=0x%x, open=%s>(port=%r, baudrate=%r, bytesize=%r, parity=%r, stopbits=%r, timeout=%r, xonxoff=%r, rtscts=%r, dsrdtr=%r)" % (
468 self.__class__.__name__,
469 id(self),
470 self.is_open,
471 self.portstr,
472 self.baudrate,
473 self.bytesize,
474 self.parity,
475 self.stopbits,
476 self.timeout,
477 self.xonxoff,
478 self.rtscts,
479 self.dsrdtr,
480 )
481
482 # - - - - - - - - - - - - - - - - - - - - - - - -
483 # compatibility with io library
484
485 def readable(self):
486 return True
487
488 def writable(self):
489 return True
490
491 def seekable(self):
492 return False
493
494 def readinto(self, b):
495 data = self.read(len(b))
496 n = len(data)
497 try:
498 b[:n] = data
499 except TypeError as err:
500 import array
501 if not isinstance(b, array.array):
502 raise err
503 b[:n] = array.array('b', data)
504 return n
505
506 # - - - - - - - - - - - - - - - - - - - - - - - -
507 # context manager
508
509 def __enter__(self):
510 return self
511
512 def __exit__(self, *args, **kwargs):
513 self.close()
514
515 # - - - - - - - - - - - - - - - - - - - - - - - -
516
517 def send_break(self, duration=0.25):
518 """\
519 Send break condition. Timed, returns to idle state after given
520 duration.
521 """
522 if not self.is_open:
523 raise portNotOpenError
524 self.break_condition = True
525 time.sleep(duration)
526 self.break_condition = False
527
528 # - - - - - - - - - - - - - - - - - - - - - - - -
529 # backwards compatibility / deprecated functions
530
531 def flushInput(self):
532 self.reset_input_buffer()
533
534 def flushOutput(self):
535 self.reset_output_buffer()
536
537 def inWaiting(self):
538 return self.in_waiting
539
540 def sendBreak(self, duration=0.25):
541 self.send_break(duration)
542
543 def setRTS(self, value=1):
544 self.rts = value
545
546 def setDTR(self, value=1):
547 self.dtr = value
548
549 def getCTS(self):
550 return self.cts
551
552 def getDSR(self):
553 return self.dsr
554
555 def getRI(self):
556 return self.ri
557
558 def getCD(self):
559 return self.cd
560
561 @property
562 def writeTimeout(self):
563 return self.write_timeout
564
565 @writeTimeout.setter
566 def writeTimeout(self, timeout):
567 self.write_timeout = timeout
568
569 @property
570 def interCharTimeout(self):
571 return self.inter_byte_timeout
572
573 @interCharTimeout.setter
574 def interCharTimeout(self, interCharTimeout):
575 self.inter_byte_timeout = interCharTimeout
576
577 def getSettingsDict(self):
578 return self.get_settings()
579
580 def applySettingsDict(self, d):
581 self.apply_settings(d)
582
583 def isOpen(self):
584 return self.is_open
585
586 # - - - - - - - - - - - - - - - - - - - - - - - -
587 # additional functionality
588
589 def read_all(self):
590 """\
591 Read all bytes currently available in the buffer of the OS.
592 """
593 return self.read(self.in_waiting)
594
595 def read_until(self, terminator=LF, size=None):
596 """\
597 Read until a termination sequence is found ('\n' by default), the size
598 is exceeded or until timeout occurs.
599 """
600 lenterm = len(terminator)
601 line = bytearray()
602 while True:
603 c = self.read(1)
604 if c:
605 line += c
606 if line[-lenterm:] == terminator:
607 break
608 if size is not None and len(line) >= size:
609 break
610 else:
611 break
612 return bytes(line)
613
614 def iread_until(self, *args, **kwargs):
615 """\
616 Read lines, implemented as generator. It will raise StopIteration on
617 timeout (empty read).
618 """
619 while True:
620 line = self.read_until(*args, **kwargs)
621 if not line:
622 break
623 yield line
624
625
626# - - - - - - - - - - - - - - - - - - - - - - - - -
627if __name__ == '__main__':
628 import sys
629 s = SerialBase()
630 sys.stdout.write('port name: %s\n' % s.name)
631 sys.stdout.write('baud rates: %s\n' % s.BAUDRATES)
632 sys.stdout.write('byte sizes: %s\n' % s.BYTESIZES)
633 sys.stdout.write('parities: %s\n' % s.PARITIES)
634 sys.stdout.write('stop bits: %s\n' % s.STOPBITS)
635 sys.stdout.write('%s\n' % s)