comm: custom readline implementation w/ buffer
We always read everything from the serial that is currently available in our rx buffer but only return the first line in that. While that increases our memory consumption slightly, it should hopefully not cause issues and should greatly reduce the risk of buffer overflows making us lose or receive corrupt data. Possible solution for #2370 and #2454
This commit is contained in:
1 parent
10af43285b
commit
c6dfdf8d4b
1 file changed
+42
-1
@@ -20,6 +20,7 @@ from past.builtins import basestring
|
||||
|
||||
import logging
|
||||
import serial
|
||||
import wrapt
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
@@ -2240,7 +2241,7 @@ class MachineCom(object):
|
||||
serial_obj.parity = serial.PARITY_NONE
|
||||
serial_obj.open()
|
||||
|
||||
return serial_obj
|
||||
return BufferedReadlineWrapper(serial_obj)
|
||||
|
||||
serial_factories = self._serial_factory_hooks.items() + [("default", default)]
|
||||
for name, factory in serial_factories:
|
||||
@@ -4174,6 +4175,46 @@ class SendQueueMarker(QueueMarker):
|
||||
pass
|
||||
|
||||
|
||||
class BufferedReadlineWrapper(wrapt.ObjectProxy):
|
||||
def __init__(self, obj):
|
||||
wrapt.ObjectProxy.__init__(self, obj)
|
||||
self._buffered = bytearray()
|
||||
|
||||
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))
|
||||
|
||||
# check for terminator, if it's there we have found our line
|
||||
termpos = data.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:]
|
||||
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 += c
|
||||
|
||||
self._buffered = data
|
||||
return bytes("")
|
||||
|
||||
|
||||
# --- Test code for speed testing the comm layer via command line follows
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user