♻ Refactor buffered readline & add null byte logging

As suggested in #2454
This commit is contained in:
Gina Häußge committed 2020-06-17 17:01:54 +02:00
1 parent 0aed3c05cb
commit 7290a6d350
1 file changed
+18 -25
+18 -25
View File
@@ -691,9 +691,9 @@ class MachineCom(object):
self._logger.info(text)
self._callback.on_comm_state_change(newState)
def _dual_log(self, message, level=logging.ERROR):
def _dual_log(self, message, level=logging.ERROR, prefix=""):
self._logger.log(level, message)
self._log(message)
self._log(prefix + message)
def _log(self, message):
message = to_unicode(message)
@@ -2895,6 +2895,8 @@ class MachineCom(object):
self.close(is_error=True)
return None
null_pos = ret.find(b'\x00')
try:
ret = ret.decode('utf-8')
except UnicodeDecodeError:
@@ -2907,6 +2909,14 @@ class MachineCom(object):
self._log("WARN: While reading last line: {}".format(e))
self._log("Recv: {!r}".format(ret))
if null_pos >= 0:
self._logger.warning("Received line:")
self._logger.warning("| {}".format(ret.replace('\0', '\\x00').rstrip()))
self._dual_log("The received line contains at least one null byte character at position {}, "
"this hints at some data corruption going on".format(null_pos),
level=logging.WARNING,
prefix="WARN")
for name, hook in self._received_message_hooks.items():
try:
ret = hook(self, ret)
@@ -5009,36 +5019,19 @@ class BufferedReadlineWrapper(wrapt.ObjectProxy):
def readline(self, terminator=serial.LF):
termlen = len(terminator)
data = self._buffered
timeout = serial.Timeout(self._timeout)
while True:
# make sure we always read everything that is waiting
data += bytearray(self.read(self.in_waiting))
while not timeout.expired():
self._buffered += self.read(self.in_waiting)
# check for terminator, if it's there we have found our line
termpos = data.find(terminator)
termpos = self._buffered.find(terminator)
if termpos >= 0:
# line: everything up to and incl. the terminator
line = data[:termpos + termlen]
# buffered: everything after the terminator
self._buffered = data[termpos + termlen:]
# line: everything up to and incl. the terminator, buffered: rest
line = self._buffered[:termpos + termlen]
del self._buffered[:termpos + termlen]
return bytes(line)
# check if timeout expired
if timeout.expired():
break
# if we arrive here we so far couldn't read a full line, wait for more data
c = self.read(1)
if not c:
# EOF
break
# add to data and loop
data += bytearray(c)
self._buffered = data
return b""