openrvdas.logger.readers.polled_serial_reader
No module-level documentation available.
1#!/usr/bin/env python3 2 3import logging 4import time 5from itertools import cycle 6 7# Don't freak out if pyserial isn't installed - unless they actually 8# try to instantiate a SerialReader 9try: 10 import serial 11 SERIAL_MODULE_FOUND = True 12except ModuleNotFoundError: 13 SERIAL_MODULE_FOUND = False 14 15from logger.readers.serial_reader import SerialReader # noqa: E402 16 17 18############################ 19def is_string_or_list_of_strings(cmd): 20 if isinstance(cmd, str): 21 return True 22 elif isinstance(cmd, list): 23 return all(isinstance(item, str) for item in cmd) 24 return False 25 26 27############################ 28def is_dict_of_lists_of_strings(cmd): 29 if not isinstance(cmd, dict): 30 return False 31 32 # So we have a dict. Check that all values are either strings 33 # or lists of strings 34 for value in cmd.values(): 35 if isinstance(value, str): 36 continue 37 elif (isinstance(value, list) and 38 all(isinstance(item, str) for item in value)): 39 continue 40 else: 41 return False 42 43 # If got this far, it all checks out 44 return True 45 46 47################################################################################ 48class PolledSerialReader(SerialReader): 49 """ 50 Read text records from a serial port. 51 """ 52 53 def __init__(self, port, baudrate=9600, bytesize=8, parity='N', 54 stopbits=1, timeout=None, xonxoff=False, rtscts=False, 55 write_timeout=None, dsrdtr=False, inter_byte_timeout=None, 56 exclusive=True, max_bytes=None, eol=None, 57 encoding='utf-8', encoding_errors='ignore', 58 start_cmd=None, pre_read_cmd=None, stop_cmd=None, **kwargs): 59 """Extends the standard serial reader by allowing the user to define 60 strings to send to the serial host on startup, before each read and 61 just prior to the reader being destroyed. 62 63 Notable arguments: 64 ``` 65 start_cmd 66 If not None, may be string or list of strings. If a single string, 67 it is sent to the serial port as soon as it is opened. If a list of 68 strings, each string in the list is sent in sequence. 69 70 stop_cmd 71 Much as start_cmd, but is sent when the PolledSerialReader is closed 72 or destroyed. 73 74 pre_read_cmd 75 Much as start_cmd and stop_cmd, except the string or list of strings 76 are sent each time the PolledSerialReader's read() method is called, 77 prior to trying to read from the port. 78 79 In addition to a string or list of strings, pre_read_cmd may be a *dict* 80 of lists of strings: 81 82 pre_read_cmd: 83 key1: ['command 1_1', 'command 1_2] 84 key2: ['command 2_1', 'command 2_2] 85 key3: ... 86 ... 87 The first time read() is called, the strings associated with key1 will be 88 sent. The second time, those associated with key2, and so on. When the end 89 of the dict is reached, it will start again with key1. 90 91 timeout <seconds> 92 If timeout is specified, then the serial read will time out after this many 93 seconds. It will then reissue the pre_read_cmds, if there is one, and try 94 reading again. If there is a dict of pre_read_cmds, it will progress to the 95 next one in the dict. 96 97 exclusive 98 True by default, as for SerialReader - take an exclusive lock on the 99 port so a second OpenRVDAS process opening it fails loudly rather 100 than silently splitting the byte stream. This reader is the case 101 that most wants the lock: it writes commands to the same port it 102 reads from, so another process taking bytes off it would break the 103 command/response pairing rather than merely thinning the data. 104 105 Note that bidirectional use needs no exception here - reads and 106 writes go through the same open port, so there is only one lock 107 holder. Set False only if something outside OpenRVDAS must share 108 the port. 109 ``` 110 For all of these arguments, a special string, ``__PAUSE__``, is recognized. If 111 followed by a number (e.g. ``__PAUSE__ 5``), it will be interpreted as a command 112 to pause for that many seconds prior to sending the next command. If no number 113 is given, it will pause for one second. 114 """ 115 # Can we even run this? 116 if not SERIAL_MODULE_FOUND: 117 raise RuntimeError('Serial port functionality not available. Please ' 118 'install Python module pyserial.') 119 120 # Type check our pre_read commands 121 if start_cmd and not is_string_or_list_of_strings(start_cmd): 122 raise ValueError('PolledSerialReader start_cmd must either be None, ' 123 f'a string, or a list of strings. Found: {start_cmd}') 124 if stop_cmd and not is_string_or_list_of_strings(stop_cmd): 125 raise ValueError('PolledSerialReader stop_cmd must either be None, ' 126 f'a string, or a list of strings. Found: {stop_cmd}') 127 if pre_read_cmd and not (is_string_or_list_of_strings(pre_read_cmd) or 128 is_dict_of_lists_of_strings(pre_read_cmd)): 129 raise ValueError('PolledSerialReader pre_read_cmd must either be None, ' 130 'a string, or a list of strings, or a dict of lists of ' 131 f'strings. Found: {pre_read_cmd}') 132 133 # Okay, let's go and build 134 super().__init__(port=port, baudrate=baudrate, bytesize=bytesize, 135 parity=parity, stopbits=stopbits, timeout=timeout, 136 xonxoff=xonxoff, rtscts=rtscts, write_timeout=write_timeout, 137 dsrdtr=dsrdtr, inter_byte_timeout=inter_byte_timeout, 138 exclusive=exclusive, max_bytes=max_bytes, eol=eol, 139 encoding=encoding, encoding_errors=encoding_errors, **kwargs) 140 141 self.start_cmd = start_cmd 142 self.pre_read_cmd = pre_read_cmd 143 self.stop_cmd = stop_cmd 144 145 if isinstance(pre_read_cmd, dict): 146 self.command_cycle = cycle(pre_read_cmd.items()) 147 148 if self.start_cmd: 149 try: 150 if isinstance(self.start_cmd, list): # list of commands 151 for cmd in self.start_cmd: 152 self._send_command(cmd) 153 else: 154 self._send_command(start_cmd) 155 except serial.serialutil.SerialException as e: 156 logging.error(str(e)) 157 158 ############################ 159 def _send_command(self, cmd): 160 """Check if command is a 'pause'; if so, sleep, otherwise send it to serial port.""" 161 logging.debug(f'Sending {cmd}') 162 if cmd.find('__PAUSE__') == 0: 163 pause_cmd = cmd.split() 164 if len(pause_cmd) == 1: 165 pause_length = 1 166 elif len(pause_cmd) == 2: 167 try: 168 pause_length = float(pause_cmd[1]) 169 except ValueError: 170 raise ValueError('__PAUSE__ interval in PolledSerialReader must be ' 171 'a float. Found: %s' % cmd) 172 else: 173 raise ValueError('Pause format "__PAUSE__ <seconds>"; found %s' % cmd) 174 logging.info('Pausing %g seconds', pause_length) 175 time.sleep(pause_length) 176 else: 177 # If it's a normal command we're sending 178 logging.info('Sending serial command "%s"', cmd) 179 self.serial.write(self._encode_str(cmd, unescape=True)) 180 self.serial.flush() 181 182 logging.debug(f'Done sending {cmd}') 183 184 ############################ 185 def read(self): 186 try: 187 # Try again if our read times out, or our serial port returns None 188 while True: 189 # Do we need to send anything prior to reading? 190 if not self.pre_read_cmd: # no pre_read_cmd 191 pass 192 elif isinstance(self.pre_read_cmd, list): # list of commands 193 for cmd in self.pre_read_cmd: 194 self._send_command(cmd) 195 elif isinstance(self.pre_read_cmd, dict): # dict of lists of commands 196 key, commands = next(self.command_cycle) 197 for cmd in commands: 198 self._send_command(cmd) 199 elif self.pre_read_cmd: # simple string command 200 self._send_command(self.pre_read_cmd) 201 202 logging.debug('read() is being called') 203 record = super().read() 204 logging.debug(f'Returned from read() with: {record}') 205 if record is not None: 206 return record 207 logging.debug('Serial read returned None; trying again.') 208 209 except serial.serialutil.SerialException as e: 210 logging.error(str(e)) 211 return None 212 213 ############################ 214 def __del__(self): 215 if self.stop_cmd: 216 try: 217 if isinstance(self.stop_cmd, list): # list of commands 218 for cmd in self.stop_cmd: 219 self._send_command(cmd) 220 else: 221 self._send_command(self.stop_cmd) 222 except serial.serialutil.SerialException as e: 223 logging.error(str(e))
def
is_string_or_list_of_strings(cmd):
def
is_dict_of_lists_of_strings(cmd):
29def is_dict_of_lists_of_strings(cmd): 30 if not isinstance(cmd, dict): 31 return False 32 33 # So we have a dict. Check that all values are either strings 34 # or lists of strings 35 for value in cmd.values(): 36 if isinstance(value, str): 37 continue 38 elif (isinstance(value, list) and 39 all(isinstance(item, str) for item in value)): 40 continue 41 else: 42 return False 43 44 # If got this far, it all checks out 45 return True
class
PolledSerialReader(logger.readers.serial_reader.SerialReader):
49class PolledSerialReader(SerialReader): 50 """ 51 Read text records from a serial port. 52 """ 53 54 def __init__(self, port, baudrate=9600, bytesize=8, parity='N', 55 stopbits=1, timeout=None, xonxoff=False, rtscts=False, 56 write_timeout=None, dsrdtr=False, inter_byte_timeout=None, 57 exclusive=True, max_bytes=None, eol=None, 58 encoding='utf-8', encoding_errors='ignore', 59 start_cmd=None, pre_read_cmd=None, stop_cmd=None, **kwargs): 60 """Extends the standard serial reader by allowing the user to define 61 strings to send to the serial host on startup, before each read and 62 just prior to the reader being destroyed. 63 64 Notable arguments: 65 ``` 66 start_cmd 67 If not None, may be string or list of strings. If a single string, 68 it is sent to the serial port as soon as it is opened. If a list of 69 strings, each string in the list is sent in sequence. 70 71 stop_cmd 72 Much as start_cmd, but is sent when the PolledSerialReader is closed 73 or destroyed. 74 75 pre_read_cmd 76 Much as start_cmd and stop_cmd, except the string or list of strings 77 are sent each time the PolledSerialReader's read() method is called, 78 prior to trying to read from the port. 79 80 In addition to a string or list of strings, pre_read_cmd may be a *dict* 81 of lists of strings: 82 83 pre_read_cmd: 84 key1: ['command 1_1', 'command 1_2] 85 key2: ['command 2_1', 'command 2_2] 86 key3: ... 87 ... 88 The first time read() is called, the strings associated with key1 will be 89 sent. The second time, those associated with key2, and so on. When the end 90 of the dict is reached, it will start again with key1. 91 92 timeout <seconds> 93 If timeout is specified, then the serial read will time out after this many 94 seconds. It will then reissue the pre_read_cmds, if there is one, and try 95 reading again. If there is a dict of pre_read_cmds, it will progress to the 96 next one in the dict. 97 98 exclusive 99 True by default, as for SerialReader - take an exclusive lock on the 100 port so a second OpenRVDAS process opening it fails loudly rather 101 than silently splitting the byte stream. This reader is the case 102 that most wants the lock: it writes commands to the same port it 103 reads from, so another process taking bytes off it would break the 104 command/response pairing rather than merely thinning the data. 105 106 Note that bidirectional use needs no exception here - reads and 107 writes go through the same open port, so there is only one lock 108 holder. Set False only if something outside OpenRVDAS must share 109 the port. 110 ``` 111 For all of these arguments, a special string, ``__PAUSE__``, is recognized. If 112 followed by a number (e.g. ``__PAUSE__ 5``), it will be interpreted as a command 113 to pause for that many seconds prior to sending the next command. If no number 114 is given, it will pause for one second. 115 """ 116 # Can we even run this? 117 if not SERIAL_MODULE_FOUND: 118 raise RuntimeError('Serial port functionality not available. Please ' 119 'install Python module pyserial.') 120 121 # Type check our pre_read commands 122 if start_cmd and not is_string_or_list_of_strings(start_cmd): 123 raise ValueError('PolledSerialReader start_cmd must either be None, ' 124 f'a string, or a list of strings. Found: {start_cmd}') 125 if stop_cmd and not is_string_or_list_of_strings(stop_cmd): 126 raise ValueError('PolledSerialReader stop_cmd must either be None, ' 127 f'a string, or a list of strings. Found: {stop_cmd}') 128 if pre_read_cmd and not (is_string_or_list_of_strings(pre_read_cmd) or 129 is_dict_of_lists_of_strings(pre_read_cmd)): 130 raise ValueError('PolledSerialReader pre_read_cmd must either be None, ' 131 'a string, or a list of strings, or a dict of lists of ' 132 f'strings. Found: {pre_read_cmd}') 133 134 # Okay, let's go and build 135 super().__init__(port=port, baudrate=baudrate, bytesize=bytesize, 136 parity=parity, stopbits=stopbits, timeout=timeout, 137 xonxoff=xonxoff, rtscts=rtscts, write_timeout=write_timeout, 138 dsrdtr=dsrdtr, inter_byte_timeout=inter_byte_timeout, 139 exclusive=exclusive, max_bytes=max_bytes, eol=eol, 140 encoding=encoding, encoding_errors=encoding_errors, **kwargs) 141 142 self.start_cmd = start_cmd 143 self.pre_read_cmd = pre_read_cmd 144 self.stop_cmd = stop_cmd 145 146 if isinstance(pre_read_cmd, dict): 147 self.command_cycle = cycle(pre_read_cmd.items()) 148 149 if self.start_cmd: 150 try: 151 if isinstance(self.start_cmd, list): # list of commands 152 for cmd in self.start_cmd: 153 self._send_command(cmd) 154 else: 155 self._send_command(start_cmd) 156 except serial.serialutil.SerialException as e: 157 logging.error(str(e)) 158 159 ############################ 160 def _send_command(self, cmd): 161 """Check if command is a 'pause'; if so, sleep, otherwise send it to serial port.""" 162 logging.debug(f'Sending {cmd}') 163 if cmd.find('__PAUSE__') == 0: 164 pause_cmd = cmd.split() 165 if len(pause_cmd) == 1: 166 pause_length = 1 167 elif len(pause_cmd) == 2: 168 try: 169 pause_length = float(pause_cmd[1]) 170 except ValueError: 171 raise ValueError('__PAUSE__ interval in PolledSerialReader must be ' 172 'a float. Found: %s' % cmd) 173 else: 174 raise ValueError('Pause format "__PAUSE__ <seconds>"; found %s' % cmd) 175 logging.info('Pausing %g seconds', pause_length) 176 time.sleep(pause_length) 177 else: 178 # If it's a normal command we're sending 179 logging.info('Sending serial command "%s"', cmd) 180 self.serial.write(self._encode_str(cmd, unescape=True)) 181 self.serial.flush() 182 183 logging.debug(f'Done sending {cmd}') 184 185 ############################ 186 def read(self): 187 try: 188 # Try again if our read times out, or our serial port returns None 189 while True: 190 # Do we need to send anything prior to reading? 191 if not self.pre_read_cmd: # no pre_read_cmd 192 pass 193 elif isinstance(self.pre_read_cmd, list): # list of commands 194 for cmd in self.pre_read_cmd: 195 self._send_command(cmd) 196 elif isinstance(self.pre_read_cmd, dict): # dict of lists of commands 197 key, commands = next(self.command_cycle) 198 for cmd in commands: 199 self._send_command(cmd) 200 elif self.pre_read_cmd: # simple string command 201 self._send_command(self.pre_read_cmd) 202 203 logging.debug('read() is being called') 204 record = super().read() 205 logging.debug(f'Returned from read() with: {record}') 206 if record is not None: 207 return record 208 logging.debug('Serial read returned None; trying again.') 209 210 except serial.serialutil.SerialException as e: 211 logging.error(str(e)) 212 return None 213 214 ############################ 215 def __del__(self): 216 if self.stop_cmd: 217 try: 218 if isinstance(self.stop_cmd, list): # list of commands 219 for cmd in self.stop_cmd: 220 self._send_command(cmd) 221 else: 222 self._send_command(self.stop_cmd) 223 except serial.serialutil.SerialException as e: 224 logging.error(str(e))
Read text records from a serial port.
PolledSerialReader( port, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, write_timeout=None, dsrdtr=False, inter_byte_timeout=None, exclusive=True, max_bytes=None, eol=None, encoding='utf-8', encoding_errors='ignore', start_cmd=None, pre_read_cmd=None, stop_cmd=None, **kwargs)
54 def __init__(self, port, baudrate=9600, bytesize=8, parity='N', 55 stopbits=1, timeout=None, xonxoff=False, rtscts=False, 56 write_timeout=None, dsrdtr=False, inter_byte_timeout=None, 57 exclusive=True, max_bytes=None, eol=None, 58 encoding='utf-8', encoding_errors='ignore', 59 start_cmd=None, pre_read_cmd=None, stop_cmd=None, **kwargs): 60 """Extends the standard serial reader by allowing the user to define 61 strings to send to the serial host on startup, before each read and 62 just prior to the reader being destroyed. 63 64 Notable arguments: 65 ``` 66 start_cmd 67 If not None, may be string or list of strings. If a single string, 68 it is sent to the serial port as soon as it is opened. If a list of 69 strings, each string in the list is sent in sequence. 70 71 stop_cmd 72 Much as start_cmd, but is sent when the PolledSerialReader is closed 73 or destroyed. 74 75 pre_read_cmd 76 Much as start_cmd and stop_cmd, except the string or list of strings 77 are sent each time the PolledSerialReader's read() method is called, 78 prior to trying to read from the port. 79 80 In addition to a string or list of strings, pre_read_cmd may be a *dict* 81 of lists of strings: 82 83 pre_read_cmd: 84 key1: ['command 1_1', 'command 1_2] 85 key2: ['command 2_1', 'command 2_2] 86 key3: ... 87 ... 88 The first time read() is called, the strings associated with key1 will be 89 sent. The second time, those associated with key2, and so on. When the end 90 of the dict is reached, it will start again with key1. 91 92 timeout <seconds> 93 If timeout is specified, then the serial read will time out after this many 94 seconds. It will then reissue the pre_read_cmds, if there is one, and try 95 reading again. If there is a dict of pre_read_cmds, it will progress to the 96 next one in the dict. 97 98 exclusive 99 True by default, as for SerialReader - take an exclusive lock on the 100 port so a second OpenRVDAS process opening it fails loudly rather 101 than silently splitting the byte stream. This reader is the case 102 that most wants the lock: it writes commands to the same port it 103 reads from, so another process taking bytes off it would break the 104 command/response pairing rather than merely thinning the data. 105 106 Note that bidirectional use needs no exception here - reads and 107 writes go through the same open port, so there is only one lock 108 holder. Set False only if something outside OpenRVDAS must share 109 the port. 110 ``` 111 For all of these arguments, a special string, ``__PAUSE__``, is recognized. If 112 followed by a number (e.g. ``__PAUSE__ 5``), it will be interpreted as a command 113 to pause for that many seconds prior to sending the next command. If no number 114 is given, it will pause for one second. 115 """ 116 # Can we even run this? 117 if not SERIAL_MODULE_FOUND: 118 raise RuntimeError('Serial port functionality not available. Please ' 119 'install Python module pyserial.') 120 121 # Type check our pre_read commands 122 if start_cmd and not is_string_or_list_of_strings(start_cmd): 123 raise ValueError('PolledSerialReader start_cmd must either be None, ' 124 f'a string, or a list of strings. Found: {start_cmd}') 125 if stop_cmd and not is_string_or_list_of_strings(stop_cmd): 126 raise ValueError('PolledSerialReader stop_cmd must either be None, ' 127 f'a string, or a list of strings. Found: {stop_cmd}') 128 if pre_read_cmd and not (is_string_or_list_of_strings(pre_read_cmd) or 129 is_dict_of_lists_of_strings(pre_read_cmd)): 130 raise ValueError('PolledSerialReader pre_read_cmd must either be None, ' 131 'a string, or a list of strings, or a dict of lists of ' 132 f'strings. Found: {pre_read_cmd}') 133 134 # Okay, let's go and build 135 super().__init__(port=port, baudrate=baudrate, bytesize=bytesize, 136 parity=parity, stopbits=stopbits, timeout=timeout, 137 xonxoff=xonxoff, rtscts=rtscts, write_timeout=write_timeout, 138 dsrdtr=dsrdtr, inter_byte_timeout=inter_byte_timeout, 139 exclusive=exclusive, max_bytes=max_bytes, eol=eol, 140 encoding=encoding, encoding_errors=encoding_errors, **kwargs) 141 142 self.start_cmd = start_cmd 143 self.pre_read_cmd = pre_read_cmd 144 self.stop_cmd = stop_cmd 145 146 if isinstance(pre_read_cmd, dict): 147 self.command_cycle = cycle(pre_read_cmd.items()) 148 149 if self.start_cmd: 150 try: 151 if isinstance(self.start_cmd, list): # list of commands 152 for cmd in self.start_cmd: 153 self._send_command(cmd) 154 else: 155 self._send_command(start_cmd) 156 except serial.serialutil.SerialException as e: 157 logging.error(str(e))
Extends the standard serial reader by allowing the user to define strings to send to the serial host on startup, before each read and just prior to the reader being destroyed.
Notable arguments:
start_cmd
If not None, may be string or list of strings. If a single string,
it is sent to the serial port as soon as it is opened. If a list of
strings, each string in the list is sent in sequence.
stop_cmd
Much as start_cmd, but is sent when the PolledSerialReader is closed
or destroyed.
pre_read_cmd
Much as start_cmd and stop_cmd, except the string or list of strings
are sent each time the PolledSerialReader's read() method is called,
prior to trying to read from the port.
In addition to a string or list of strings, pre_read_cmd may be a *dict*
of lists of strings:
pre_read_cmd:
key1: ['command 1_1', 'command 1_2]
key2: ['command 2_1', 'command 2_2]
key3: ...
...
The first time read() is called, the strings associated with key1 will be
sent. The second time, those associated with key2, and so on. When the end
of the dict is reached, it will start again with key1.
timeout <seconds>
If timeout is specified, then the serial read will time out after this many
seconds. It will then reissue the pre_read_cmds, if there is one, and try
reading again. If there is a dict of pre_read_cmds, it will progress to the
next one in the dict.
exclusive
True by default, as for SerialReader - take an exclusive lock on the
port so a second OpenRVDAS process opening it fails loudly rather
than silently splitting the byte stream. This reader is the case
that most wants the lock: it writes commands to the same port it
reads from, so another process taking bytes off it would break the
command/response pairing rather than merely thinning the data.
Note that bidirectional use needs no exception here - reads and
writes go through the same open port, so there is only one lock
holder. Set False only if something outside OpenRVDAS must share
the port.
For all of these arguments, a special string, __PAUSE__, is recognized. If
followed by a number (e.g. __PAUSE__ 5), it will be interpreted as a command
to pause for that many seconds prior to sending the next command. If no number
is given, it will pause for one second.
def
read(self):
186 def read(self): 187 try: 188 # Try again if our read times out, or our serial port returns None 189 while True: 190 # Do we need to send anything prior to reading? 191 if not self.pre_read_cmd: # no pre_read_cmd 192 pass 193 elif isinstance(self.pre_read_cmd, list): # list of commands 194 for cmd in self.pre_read_cmd: 195 self._send_command(cmd) 196 elif isinstance(self.pre_read_cmd, dict): # dict of lists of commands 197 key, commands = next(self.command_cycle) 198 for cmd in commands: 199 self._send_command(cmd) 200 elif self.pre_read_cmd: # simple string command 201 self._send_command(self.pre_read_cmd) 202 203 logging.debug('read() is being called') 204 record = super().read() 205 logging.debug(f'Returned from read() with: {record}') 206 if record is not None: 207 return record 208 logging.debug('Serial read returned None; trying again.') 209 210 except serial.serialutil.SerialException as e: 211 logging.error(str(e)) 212 return None
read() should return None when there are no more records.