openrvdas.logger.writers.serial_writer
1#!/usr/bin/env python3 2 3import errno 4import logging 5 6from typing import Union 7 8# Don't freak out if pyserial isn't installed - unless they actually 9# try to instantiate a SerialWriter 10try: 11 import serial 12 SERIAL_MODULE_FOUND = True 13except ModuleNotFoundError: 14 SERIAL_MODULE_FOUND = False 15 16from logger.writers.writer import Writer # noqa: E402 17 18 19################################################################################ 20class SerialWriter(Writer): 21 """ 22 Writes records to a serial port. 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, eol='\n', **kwargs): 28 """ 29 By default, the SerialWriter write records to the specified serial port encoded by UTF-8 30 and will ignore non unicode characters it encounters. These defaults may be changed by 31 specifying. 32 33 eol - if specified, append to end of records to signify end of line, 34 otherwise use \n 35 36 exclusive - True by default: take an exclusive lock on the port, so that 37 a second OpenRVDAS process opening the same port fails loudly 38 rather than interleaving its output with this one's. Pass False 39 to allow shared access. 40 41 Note the lock is advisory - pyserial implements it with 42 flock() - so it only excludes processes that also ask for 43 exclusivity. 44 45 encoding - 'utf-8' by default. If empty or None, will throw type error. 46 Other possible encodings are listed in online documentation here: 47 https://docs.python.org/3/library/codecs.html#standard-encodings 48 49 encoding_errors - 'ignore' by default. Other error strategies are 'strict', 50 'replace', and 'backslashreplace', described here: 51 https://docs.python.org/3/howto/unicode.html#encodings 52 quiet - allows for the logger to silence warnings if not all the bits were succesfully 53 written to the serial port. 54 """ 55 super().__init__(**kwargs) # processes 'quiet', encodings and type hints 56 57 if not SERIAL_MODULE_FOUND: 58 raise RuntimeError('Serial port functionality not available. Please ' 59 'install Python module pyserial.') 60 try: 61 self.serial = serial.Serial(port=port, baudrate=baudrate, 62 bytesize=bytesize, parity=parity, 63 stopbits=stopbits, timeout=timeout, 64 xonxoff=xonxoff, rtscts=rtscts, 65 write_timeout=write_timeout, dsrdtr=dsrdtr, 66 inter_byte_timeout=inter_byte_timeout, 67 exclusive=exclusive) 68 except serial.SerialException as e: 69 # A lock conflict means someone else already has the port. Say what 70 # to do about it rather than leaving the reader to decode 71 # "Could not exclusively lock port". 72 if exclusive and e.errno in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK): 73 raise serial.SerialException( 74 f'Serial port {port} is already locked by another process; ' 75 f'not opening it a second time. Is a logger already writing ' 76 f'to this port? "fuser -v {port}" or "lsof {port}" will name ' 77 f'the process. If it is another copy of this logger, ' 78 f'several logger managers may be running: ' 79 f'"pgrep -fl logger_manager" lists them. To allow shared ' 80 f'access anyway, set ' 81 f'exclusive: false. Underlying error: {e}') 82 raise serial.SerialException(f'Failed to open serial port {port}: {e}') 83 84 # 'eol' comes in as a (probably escaped) string. We need to 85 # unescape it, which means converting to bytes and back. 86 if eol: 87 if self.encoding: 88 # NOTE: Technically, it's safe to call _unescape_str() with no 89 # encoding, it just returns the str/bytes/thing 90 # unmodified. But why tempt fate, right? 91 eol = self._unescape_str(eol) 92 else: 93 # if encoding has been set to '' or None, we're dealing with raw/binary 94 # output. encode eol so we can append it safely in write() 95 eol = eol.encode() 96 self.eol = eol 97 98 ############################ 99 def write(self, record: Union[str, bytes]): 100 101 # See if it's something we can process, and if not, try digesting 102 if not self.can_process_record(record): # inherited from BaseModule() 103 self.digest_record(record) # inherited from BaseModule() 104 return 105 106 try: 107 if self.eol: 108 record += self.eol 109 written = self.serial.write(self._encode_str(record)) 110 if not written and not self.quiet: 111 logging.error("Not all bits written") 112 except KeyboardInterrupt as e: 113 raise e 114 except TypeError as e: 115 raise e 116 except serial.serialutil.SerialException as e: 117 logging.error(str(e))
21class SerialWriter(Writer): 22 """ 23 Writes records to a serial port. 24 """ 25 def __init__(self, port, baudrate=9600, bytesize=8, parity='N', 26 stopbits=1, timeout=None, xonxoff=False, rtscts=False, 27 write_timeout=None, dsrdtr=False, inter_byte_timeout=None, 28 exclusive=True, eol='\n', **kwargs): 29 """ 30 By default, the SerialWriter write records to the specified serial port encoded by UTF-8 31 and will ignore non unicode characters it encounters. These defaults may be changed by 32 specifying. 33 34 eol - if specified, append to end of records to signify end of line, 35 otherwise use \n 36 37 exclusive - True by default: take an exclusive lock on the port, so that 38 a second OpenRVDAS process opening the same port fails loudly 39 rather than interleaving its output with this one's. Pass False 40 to allow shared access. 41 42 Note the lock is advisory - pyserial implements it with 43 flock() - so it only excludes processes that also ask for 44 exclusivity. 45 46 encoding - 'utf-8' by default. If empty or None, will throw type error. 47 Other possible encodings are listed in online documentation here: 48 https://docs.python.org/3/library/codecs.html#standard-encodings 49 50 encoding_errors - 'ignore' by default. Other error strategies are 'strict', 51 'replace', and 'backslashreplace', described here: 52 https://docs.python.org/3/howto/unicode.html#encodings 53 quiet - allows for the logger to silence warnings if not all the bits were succesfully 54 written to the serial port. 55 """ 56 super().__init__(**kwargs) # processes 'quiet', encodings and type hints 57 58 if not SERIAL_MODULE_FOUND: 59 raise RuntimeError('Serial port functionality not available. Please ' 60 'install Python module pyserial.') 61 try: 62 self.serial = serial.Serial(port=port, baudrate=baudrate, 63 bytesize=bytesize, parity=parity, 64 stopbits=stopbits, timeout=timeout, 65 xonxoff=xonxoff, rtscts=rtscts, 66 write_timeout=write_timeout, dsrdtr=dsrdtr, 67 inter_byte_timeout=inter_byte_timeout, 68 exclusive=exclusive) 69 except serial.SerialException as e: 70 # A lock conflict means someone else already has the port. Say what 71 # to do about it rather than leaving the reader to decode 72 # "Could not exclusively lock port". 73 if exclusive and e.errno in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK): 74 raise serial.SerialException( 75 f'Serial port {port} is already locked by another process; ' 76 f'not opening it a second time. Is a logger already writing ' 77 f'to this port? "fuser -v {port}" or "lsof {port}" will name ' 78 f'the process. If it is another copy of this logger, ' 79 f'several logger managers may be running: ' 80 f'"pgrep -fl logger_manager" lists them. To allow shared ' 81 f'access anyway, set ' 82 f'exclusive: false. Underlying error: {e}') 83 raise serial.SerialException(f'Failed to open serial port {port}: {e}') 84 85 # 'eol' comes in as a (probably escaped) string. We need to 86 # unescape it, which means converting to bytes and back. 87 if eol: 88 if self.encoding: 89 # NOTE: Technically, it's safe to call _unescape_str() with no 90 # encoding, it just returns the str/bytes/thing 91 # unmodified. But why tempt fate, right? 92 eol = self._unescape_str(eol) 93 else: 94 # if encoding has been set to '' or None, we're dealing with raw/binary 95 # output. encode eol so we can append it safely in write() 96 eol = eol.encode() 97 self.eol = eol 98 99 ############################ 100 def write(self, record: Union[str, bytes]): 101 102 # See if it's something we can process, and if not, try digesting 103 if not self.can_process_record(record): # inherited from BaseModule() 104 self.digest_record(record) # inherited from BaseModule() 105 return 106 107 try: 108 if self.eol: 109 record += self.eol 110 written = self.serial.write(self._encode_str(record)) 111 if not written and not self.quiet: 112 logging.error("Not all bits written") 113 except KeyboardInterrupt as e: 114 raise e 115 except TypeError as e: 116 raise e 117 except serial.serialutil.SerialException as e: 118 logging.error(str(e))
Writes records to a serial port.
25 def __init__(self, port, baudrate=9600, bytesize=8, parity='N', 26 stopbits=1, timeout=None, xonxoff=False, rtscts=False, 27 write_timeout=None, dsrdtr=False, inter_byte_timeout=None, 28 exclusive=True, eol='\n', **kwargs): 29 """ 30 By default, the SerialWriter write records to the specified serial port encoded by UTF-8 31 and will ignore non unicode characters it encounters. These defaults may be changed by 32 specifying. 33 34 eol - if specified, append to end of records to signify end of line, 35 otherwise use \n 36 37 exclusive - True by default: take an exclusive lock on the port, so that 38 a second OpenRVDAS process opening the same port fails loudly 39 rather than interleaving its output with this one's. Pass False 40 to allow shared access. 41 42 Note the lock is advisory - pyserial implements it with 43 flock() - so it only excludes processes that also ask for 44 exclusivity. 45 46 encoding - 'utf-8' by default. If empty or None, will throw type error. 47 Other possible encodings are listed in online documentation here: 48 https://docs.python.org/3/library/codecs.html#standard-encodings 49 50 encoding_errors - 'ignore' by default. Other error strategies are 'strict', 51 'replace', and 'backslashreplace', described here: 52 https://docs.python.org/3/howto/unicode.html#encodings 53 quiet - allows for the logger to silence warnings if not all the bits were succesfully 54 written to the serial port. 55 """ 56 super().__init__(**kwargs) # processes 'quiet', encodings and type hints 57 58 if not SERIAL_MODULE_FOUND: 59 raise RuntimeError('Serial port functionality not available. Please ' 60 'install Python module pyserial.') 61 try: 62 self.serial = serial.Serial(port=port, baudrate=baudrate, 63 bytesize=bytesize, parity=parity, 64 stopbits=stopbits, timeout=timeout, 65 xonxoff=xonxoff, rtscts=rtscts, 66 write_timeout=write_timeout, dsrdtr=dsrdtr, 67 inter_byte_timeout=inter_byte_timeout, 68 exclusive=exclusive) 69 except serial.SerialException as e: 70 # A lock conflict means someone else already has the port. Say what 71 # to do about it rather than leaving the reader to decode 72 # "Could not exclusively lock port". 73 if exclusive and e.errno in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK): 74 raise serial.SerialException( 75 f'Serial port {port} is already locked by another process; ' 76 f'not opening it a second time. Is a logger already writing ' 77 f'to this port? "fuser -v {port}" or "lsof {port}" will name ' 78 f'the process. If it is another copy of this logger, ' 79 f'several logger managers may be running: ' 80 f'"pgrep -fl logger_manager" lists them. To allow shared ' 81 f'access anyway, set ' 82 f'exclusive: false. Underlying error: {e}') 83 raise serial.SerialException(f'Failed to open serial port {port}: {e}') 84 85 # 'eol' comes in as a (probably escaped) string. We need to 86 # unescape it, which means converting to bytes and back. 87 if eol: 88 if self.encoding: 89 # NOTE: Technically, it's safe to call _unescape_str() with no 90 # encoding, it just returns the str/bytes/thing 91 # unmodified. But why tempt fate, right? 92 eol = self._unescape_str(eol) 93 else: 94 # if encoding has been set to '' or None, we're dealing with raw/binary 95 # output. encode eol so we can append it safely in write() 96 eol = eol.encode() 97 self.eol = eol
By default, the SerialWriter write records to the specified serial port encoded by UTF-8 and will ignore non unicode characters it encounters. These defaults may be changed by specifying.
eol - if specified, append to end of records to signify end of line, otherwise use
exclusive - True by default: take an exclusive lock on the port, so that a second OpenRVDAS process opening the same port fails loudly rather than interleaving its output with this one's. 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.
encoding - 'utf-8' by default. If empty or None, will throw type error. 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 quiet - allows for the logger to silence warnings if not all the bits were succesfully written to the serial port.
100 def write(self, record: Union[str, bytes]): 101 102 # See if it's something we can process, and if not, try digesting 103 if not self.can_process_record(record): # inherited from BaseModule() 104 self.digest_record(record) # inherited from BaseModule() 105 return 106 107 try: 108 if self.eol: 109 record += self.eol 110 written = self.serial.write(self._encode_str(record)) 111 if not written and not self.quiet: 112 logging.error("Not all bits written") 113 except KeyboardInterrupt as e: 114 raise e 115 except TypeError as e: 116 raise e 117 except serial.serialutil.SerialException as e: 118 logging.error(str(e))
Core method - write a record that we've been passed.