openrvdas.logger.readers.serial_reader
1#!/usr/bin/env python3 2 3import errno 4import logging 5 6# Don't freak out if pyserial isn't installed - unless they actually 7# try to instantiate a SerialReader 8try: 9 import serial 10 SERIAL_MODULE_FOUND = True 11except ModuleNotFoundError: 12 SERIAL_MODULE_FOUND = False 13 14from logger.readers.reader import Reader # noqa: E402 15 16 17################################################################################ 18class SerialReader(Reader): 19 """ 20 Read records from a serial port. 21 """ 22 23 def __init__(self, port, baudrate=9600, bytesize=8, parity='N', 24 stopbits=1, timeout=None, xonxoff=False, rtscts=False, 25 write_timeout=None, dsrdtr=False, inter_byte_timeout=None, 26 exclusive=True, max_bytes=None, eol=None, allow_empty=False, 27 encoding='utf-8', encoding_errors='ignore', **kwargs): 28 """If max_bytes is specified on initialization, read up to that many 29 bytes when read() is called. If eol is not specified, read() will 30 read up to the first newline it receives. In both cases, if 31 timeout is specified, it will return after timeout with as many 32 bytes as it has succeeded in reading. 33 34 By default, the SerialReader will read until it encounters a newline character. 35 This behavior may be overwritten by specifying 36 37 max_bytes - if specified, and write_timeout is None, read this many bytes per record. 38 If write_timeout is not None, it may return fewer bytes. 39 40 eol - if specified, read up until encountering the specified eol 41 42 By default, the SerialReader will assume that records are encoded in UTF-8, and will 43 ignore non unicode characters it encounters. These defaults may be changed by specifying 44 45 allow_empty - If True, preserve and return empty records 46 47 exclusive - True by default: take an exclusive lock on the port, so that 48 a second OpenRVDAS process opening the same port fails loudly 49 instead of silently splitting the byte stream with the first. 50 Serial data is divided between readers rather than copied to 51 each, so two readers on one port means both get partial data 52 and neither reports a problem. Pass False to allow shared 53 access. 54 55 Note the lock is advisory - pyserial implements it with 56 flock() - so it only excludes processes that also ask for 57 exclusivity. It will not stop a non-locking reader such as 58 'cat' or 'minicom' from taking bytes off the port. 59 60 encoding - 'utf-8' by default. If empty or None, do not attempt any decoding 61 and return raw bytes. Other possible encodings are listed in online 62 documentation here: 63 https://docs.python.org/3/library/codecs.html#standard-encodings 64 65 encoding_errors - 'ignore' by default. Other error strategies are 'strict', 66 'replace', and 'backslashreplace', described here: 67 https://docs.python.org/3/howto/unicode.html#encodings 68 69 command line example: 70 ``` 71 # Read serial port ttyr05 expecting a LF as end of record 72 logger/listener/listen.py --serial port=/dev/ttyr05,eol='\r' 73 ``` 74 config example: 75 ``` 76 class: SerialReader 77 kwargs: 78 baudrate: 4800 79 port: /dev/ttyr05 80 eol: \r 81 ``` 82 """ 83 super().__init__(encoding=encoding, encoding_errors=encoding_errors, **kwargs) 84 85 if not SERIAL_MODULE_FOUND: 86 raise RuntimeError('Serial port functionality not available. Please ' 87 'install Python module pyserial.') 88 try: 89 self.serial = serial.Serial(port=port, baudrate=baudrate, 90 bytesize=bytesize, parity=parity, 91 stopbits=stopbits, timeout=timeout, 92 xonxoff=xonxoff, rtscts=rtscts, 93 write_timeout=write_timeout, dsrdtr=dsrdtr, 94 inter_byte_timeout=inter_byte_timeout, 95 exclusive=exclusive) 96 except (serial.SerialException, serial.serialutil.SerialException) as e: 97 # A lock conflict means someone else already has the port. pyserial 98 # surfaces that as an errno on the exception; say what to do about 99 # it rather than leaving the reader to decode "Could not 100 # exclusively lock port". 101 if exclusive and e.errno in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK): 102 message = ( 103 f'Serial port {port} is already locked by another process; ' 104 f'not opening it a second time. Serial data is split ' 105 f'between readers rather than copied to each, so both ' 106 f'would get partial data. Is a logger already running on ' 107 f'this port? "fuser -v {port}" or "lsof {port}" will name ' 108 f'the process. If it is another copy of this logger, ' 109 f'several logger managers may be running: ' 110 f'"pgrep -fl logger_manager" lists them. To allow shared ' 111 f'access anyway, set ' 112 f'exclusive: false. Underlying error: {e}') 113 logging.fatal(message) 114 # Carry the guidance on the exception too, not just in the log: 115 # whoever sees the traceback shouldn't have to go find the log 116 # line to learn what to do about it. 117 raise serial.SerialException(message) from e 118 logging.fatal('Failed to open serial port %s: %s', port, e) 119 raise 120 121 self.max_bytes = max_bytes 122 self.encoding = encoding 123 self.allow_empty = allow_empty 124 self.encoding_errors = encoding_errors 125 126 # 'eol' comes in as a (probably escaped) string. We need to 127 # unescape it, which means converting to bytes and back. 128 # 129 # NOTE: This block is different from SerialWriter because we use 130 # readline() in here, which already looks for trailing '\n' and 131 # handles encoding itself. 132 # 133 if eol is not None and self.encoding: 134 eol = self._encode_str(eol, unescape=True) 135 self.eol = eol 136 137 ############################ 138 def read(self): 139 try: 140 if self.eol: 141 record = self.serial.read_until(expected=self.eol, size=self.max_bytes) 142 # read_until()'s record includes a trailing 'eol', strip it off 143 # 144 # NOTE: But don't use rstrip which just looks explicitly for 145 # whitespace 146 # 147 record = record.rsplit(self.eol)[0] 148 elif self.max_bytes: 149 # no stripping on this one, just use exactly what we got 150 record = self.serial.read(size=self.max_bytes) 151 else: 152 # readline()'s record includes the trailing '\n', strip it off 153 record = self.serial.readline().rstrip() 154 155 return self._decode_bytes(record, self.allow_empty) 156 157 except KeyboardInterrupt as e: 158 raise e 159 except serial.serialutil.SerialException as e: 160 logging.error(str(e)) 161 return None
19class SerialReader(Reader): 20 """ 21 Read records from a serial port. 22 """ 23 24 def __init__(self, port, baudrate=9600, bytesize=8, parity='N', 25 stopbits=1, timeout=None, xonxoff=False, rtscts=False, 26 write_timeout=None, dsrdtr=False, inter_byte_timeout=None, 27 exclusive=True, max_bytes=None, eol=None, allow_empty=False, 28 encoding='utf-8', encoding_errors='ignore', **kwargs): 29 """If max_bytes is specified on initialization, read up to that many 30 bytes when read() is called. If eol is not specified, read() will 31 read up to the first newline it receives. In both cases, if 32 timeout is specified, it will return after timeout with as many 33 bytes as it has succeeded in reading. 34 35 By default, the SerialReader will read until it encounters a newline character. 36 This behavior may be overwritten by specifying 37 38 max_bytes - if specified, and write_timeout is None, read this many bytes per record. 39 If write_timeout is not None, it may return fewer bytes. 40 41 eol - if specified, read up until encountering the specified eol 42 43 By default, the SerialReader will assume that records are encoded in UTF-8, and will 44 ignore non unicode characters it encounters. These defaults may be changed by specifying 45 46 allow_empty - If True, preserve and return empty records 47 48 exclusive - True by default: take an exclusive lock on the port, so that 49 a second OpenRVDAS process opening the same port fails loudly 50 instead of silently splitting the byte stream with the first. 51 Serial data is divided between readers rather than copied to 52 each, so two readers on one port means both get partial data 53 and neither reports a problem. Pass False to allow shared 54 access. 55 56 Note the lock is advisory - pyserial implements it with 57 flock() - so it only excludes processes that also ask for 58 exclusivity. It will not stop a non-locking reader such as 59 'cat' or 'minicom' from taking bytes off the port. 60 61 encoding - 'utf-8' by default. If empty or None, do not attempt any decoding 62 and return raw bytes. Other possible encodings are listed in online 63 documentation here: 64 https://docs.python.org/3/library/codecs.html#standard-encodings 65 66 encoding_errors - 'ignore' by default. Other error strategies are 'strict', 67 'replace', and 'backslashreplace', described here: 68 https://docs.python.org/3/howto/unicode.html#encodings 69 70 command line example: 71 ``` 72 # Read serial port ttyr05 expecting a LF as end of record 73 logger/listener/listen.py --serial port=/dev/ttyr05,eol='\r' 74 ``` 75 config example: 76 ``` 77 class: SerialReader 78 kwargs: 79 baudrate: 4800 80 port: /dev/ttyr05 81 eol: \r 82 ``` 83 """ 84 super().__init__(encoding=encoding, encoding_errors=encoding_errors, **kwargs) 85 86 if not SERIAL_MODULE_FOUND: 87 raise RuntimeError('Serial port functionality not available. Please ' 88 'install Python module pyserial.') 89 try: 90 self.serial = serial.Serial(port=port, baudrate=baudrate, 91 bytesize=bytesize, parity=parity, 92 stopbits=stopbits, timeout=timeout, 93 xonxoff=xonxoff, rtscts=rtscts, 94 write_timeout=write_timeout, dsrdtr=dsrdtr, 95 inter_byte_timeout=inter_byte_timeout, 96 exclusive=exclusive) 97 except (serial.SerialException, serial.serialutil.SerialException) as e: 98 # A lock conflict means someone else already has the port. pyserial 99 # surfaces that as an errno on the exception; say what to do about 100 # it rather than leaving the reader to decode "Could not 101 # exclusively lock port". 102 if exclusive and e.errno in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK): 103 message = ( 104 f'Serial port {port} is already locked by another process; ' 105 f'not opening it a second time. Serial data is split ' 106 f'between readers rather than copied to each, so both ' 107 f'would get partial data. Is a logger already running on ' 108 f'this port? "fuser -v {port}" or "lsof {port}" will name ' 109 f'the process. If it is another copy of this logger, ' 110 f'several logger managers may be running: ' 111 f'"pgrep -fl logger_manager" lists them. To allow shared ' 112 f'access anyway, set ' 113 f'exclusive: false. Underlying error: {e}') 114 logging.fatal(message) 115 # Carry the guidance on the exception too, not just in the log: 116 # whoever sees the traceback shouldn't have to go find the log 117 # line to learn what to do about it. 118 raise serial.SerialException(message) from e 119 logging.fatal('Failed to open serial port %s: %s', port, e) 120 raise 121 122 self.max_bytes = max_bytes 123 self.encoding = encoding 124 self.allow_empty = allow_empty 125 self.encoding_errors = encoding_errors 126 127 # 'eol' comes in as a (probably escaped) string. We need to 128 # unescape it, which means converting to bytes and back. 129 # 130 # NOTE: This block is different from SerialWriter because we use 131 # readline() in here, which already looks for trailing '\n' and 132 # handles encoding itself. 133 # 134 if eol is not None and self.encoding: 135 eol = self._encode_str(eol, unescape=True) 136 self.eol = eol 137 138 ############################ 139 def read(self): 140 try: 141 if self.eol: 142 record = self.serial.read_until(expected=self.eol, size=self.max_bytes) 143 # read_until()'s record includes a trailing 'eol', strip it off 144 # 145 # NOTE: But don't use rstrip which just looks explicitly for 146 # whitespace 147 # 148 record = record.rsplit(self.eol)[0] 149 elif self.max_bytes: 150 # no stripping on this one, just use exactly what we got 151 record = self.serial.read(size=self.max_bytes) 152 else: 153 # readline()'s record includes the trailing '\n', strip it off 154 record = self.serial.readline().rstrip() 155 156 return self._decode_bytes(record, self.allow_empty) 157 158 except KeyboardInterrupt as e: 159 raise e 160 except serial.serialutil.SerialException as e: 161 logging.error(str(e)) 162 return None
Read records from a serial port.
24 def __init__(self, port, baudrate=9600, bytesize=8, parity='N', 25 stopbits=1, timeout=None, xonxoff=False, rtscts=False, 26 write_timeout=None, dsrdtr=False, inter_byte_timeout=None, 27 exclusive=True, max_bytes=None, eol=None, allow_empty=False, 28 encoding='utf-8', encoding_errors='ignore', **kwargs): 29 """If max_bytes is specified on initialization, read up to that many 30 bytes when read() is called. If eol is not specified, read() will 31 read up to the first newline it receives. In both cases, if 32 timeout is specified, it will return after timeout with as many 33 bytes as it has succeeded in reading. 34 35 By default, the SerialReader will read until it encounters a newline character. 36 This behavior may be overwritten by specifying 37 38 max_bytes - if specified, and write_timeout is None, read this many bytes per record. 39 If write_timeout is not None, it may return fewer bytes. 40 41 eol - if specified, read up until encountering the specified eol 42 43 By default, the SerialReader will assume that records are encoded in UTF-8, and will 44 ignore non unicode characters it encounters. These defaults may be changed by specifying 45 46 allow_empty - If True, preserve and return empty records 47 48 exclusive - True by default: take an exclusive lock on the port, so that 49 a second OpenRVDAS process opening the same port fails loudly 50 instead of silently splitting the byte stream with the first. 51 Serial data is divided between readers rather than copied to 52 each, so two readers on one port means both get partial data 53 and neither reports a problem. Pass False to allow shared 54 access. 55 56 Note the lock is advisory - pyserial implements it with 57 flock() - so it only excludes processes that also ask for 58 exclusivity. It will not stop a non-locking reader such as 59 'cat' or 'minicom' from taking bytes off the port. 60 61 encoding - 'utf-8' by default. If empty or None, do not attempt any decoding 62 and return raw bytes. Other possible encodings are listed in online 63 documentation here: 64 https://docs.python.org/3/library/codecs.html#standard-encodings 65 66 encoding_errors - 'ignore' by default. Other error strategies are 'strict', 67 'replace', and 'backslashreplace', described here: 68 https://docs.python.org/3/howto/unicode.html#encodings 69 70 command line example: 71 ``` 72 # Read serial port ttyr05 expecting a LF as end of record 73 logger/listener/listen.py --serial port=/dev/ttyr05,eol='\r' 74 ``` 75 config example: 76 ``` 77 class: SerialReader 78 kwargs: 79 baudrate: 4800 80 port: /dev/ttyr05 81 eol: \r 82 ``` 83 """ 84 super().__init__(encoding=encoding, encoding_errors=encoding_errors, **kwargs) 85 86 if not SERIAL_MODULE_FOUND: 87 raise RuntimeError('Serial port functionality not available. Please ' 88 'install Python module pyserial.') 89 try: 90 self.serial = serial.Serial(port=port, baudrate=baudrate, 91 bytesize=bytesize, parity=parity, 92 stopbits=stopbits, timeout=timeout, 93 xonxoff=xonxoff, rtscts=rtscts, 94 write_timeout=write_timeout, dsrdtr=dsrdtr, 95 inter_byte_timeout=inter_byte_timeout, 96 exclusive=exclusive) 97 except (serial.SerialException, serial.serialutil.SerialException) as e: 98 # A lock conflict means someone else already has the port. pyserial 99 # surfaces that as an errno on the exception; say what to do about 100 # it rather than leaving the reader to decode "Could not 101 # exclusively lock port". 102 if exclusive and e.errno in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK): 103 message = ( 104 f'Serial port {port} is already locked by another process; ' 105 f'not opening it a second time. Serial data is split ' 106 f'between readers rather than copied to each, so both ' 107 f'would get partial data. Is a logger already running on ' 108 f'this port? "fuser -v {port}" or "lsof {port}" will name ' 109 f'the process. If it is another copy of this logger, ' 110 f'several logger managers may be running: ' 111 f'"pgrep -fl logger_manager" lists them. To allow shared ' 112 f'access anyway, set ' 113 f'exclusive: false. Underlying error: {e}') 114 logging.fatal(message) 115 # Carry the guidance on the exception too, not just in the log: 116 # whoever sees the traceback shouldn't have to go find the log 117 # line to learn what to do about it. 118 raise serial.SerialException(message) from e 119 logging.fatal('Failed to open serial port %s: %s', port, e) 120 raise 121 122 self.max_bytes = max_bytes 123 self.encoding = encoding 124 self.allow_empty = allow_empty 125 self.encoding_errors = encoding_errors 126 127 # 'eol' comes in as a (probably escaped) string. We need to 128 # unescape it, which means converting to bytes and back. 129 # 130 # NOTE: This block is different from SerialWriter because we use 131 # readline() in here, which already looks for trailing '\n' and 132 # handles encoding itself. 133 # 134 if eol is not None and self.encoding: 135 eol = self._encode_str(eol, unescape=True) 136 self.eol = eol
If max_bytes is specified on initialization, read up to that many bytes when read() is called. If eol is not specified, read() will read up to the first newline it receives. In both cases, if timeout is specified, it will return after timeout with as many bytes as it has succeeded in reading.
By default, the SerialReader will read until it encounters a newline character. This behavior may be overwritten by specifying
max_bytes - if specified, and write_timeout is None, read this many bytes per record. If write_timeout is not None, it may return fewer bytes.
eol - if specified, read up until encountering the specified eol
By default, the SerialReader will assume that records are encoded in UTF-8, and will ignore non unicode characters it encounters. These defaults may be changed by specifying
allow_empty - If True, preserve and return empty records
exclusive - True by default: take an exclusive lock on the port, so that a second OpenRVDAS process opening the same port fails loudly instead of silently splitting the byte stream with the first. Serial data is divided between readers rather than copied to each, so two readers on one port means both get partial data and neither reports a problem. Pass False to allow shared access.
Note the lock is advisory - pyserial implements it with
flock() - so it only excludes processes that also ask for
exclusivity. It will not stop a non-locking reader such as
'cat' or 'minicom' from taking bytes off the port.
encoding - 'utf-8' by default. If empty or None, do not attempt any decoding and return raw bytes. Other possible encodings are listed in online documentation here: https://docs.python.org/3/library/codecs.html#standard-encodings
encoding_errors - 'ignore' by default. Other error strategies are 'strict', 'replace', and 'backslashreplace', described here: https://docs.python.org/3/howto/unicode.html#encodings
command line example:
# Read serial port ttyr05 expecting a LF as end of record
logger/listener/listen.py --serial port=/dev/ttyr05,eol='
'
config example:
class: SerialReader
kwargs:
baudrate: 4800
port: /dev/ttyr05
eol:
139 def read(self): 140 try: 141 if self.eol: 142 record = self.serial.read_until(expected=self.eol, size=self.max_bytes) 143 # read_until()'s record includes a trailing 'eol', strip it off 144 # 145 # NOTE: But don't use rstrip which just looks explicitly for 146 # whitespace 147 # 148 record = record.rsplit(self.eol)[0] 149 elif self.max_bytes: 150 # no stripping on this one, just use exactly what we got 151 record = self.serial.read(size=self.max_bytes) 152 else: 153 # readline()'s record includes the trailing '\n', strip it off 154 record = self.serial.readline().rstrip() 155 156 return self._decode_bytes(record, self.allow_empty) 157 158 except KeyboardInterrupt as e: 159 raise e 160 except serial.serialutil.SerialException as e: 161 logging.error(str(e)) 162 return None
read() should return None when there are no more records.