diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 229524196..dccd65189 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -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