diff --git a/scripts/octoprint.init b/scripts/octoprint.init index 19b10f7cf..d044a5855 100644 --- a/scripts/octoprint.init +++ b/scripts/octoprint.init @@ -19,6 +19,7 @@ PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin DESC="Octoprint Daemon" NAME="Octoprint" DAEMON=/usr/local/bin/octoprint +NICE=-10 PIDFILE=/var/run/$NAME.pid PKGNAME=octoprint SCRIPTNAME=/etc/init.d/$PKGNAME @@ -72,7 +73,7 @@ do_start() RETVAL="$?" if [ $RETVAL != 0 ]; then - start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile \ + start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile --nicelevel $NICE\ --exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK -- $DAEMON_ARGS RETVAL="$?" fi diff --git a/src/octoprint/comm/protocol/__init__.py b/src/octoprint/comm/protocol/__init__.py index 2a1541082..727ff8e92 100644 --- a/src/octoprint/comm/protocol/__init__.py +++ b/src/octoprint/comm/protocol/__init__.py @@ -61,6 +61,15 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver): self._transport.connect(opt) def disconnect(self, on_error=False): + if self.is_printing(): + payload = None + if self._current_file is not None: + payload = { + "file": self._current_file.getFilename(), + "filename": os.path.basename(self._current_file.getFilename()), + "origin": self._current_file.getFileLocation() + } + eventManager().fire(Events.PRINT_FAILED, payload) self._transport.disconnect(on_error) def send_manually(self, command, high_priority=False): @@ -79,18 +88,33 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver): self._heatup_start_time = None self._heatup_time_lost = 0.0 - self._changeState(State.PRINTING) self._current_file.start() + self._changeState(State.PRINTING) + eventManager().fire(Events.PRINT_STARTED, { + "file": self._current_file.getFilename(), + "filename": os.path.basename(self._current_file.getFilename()), + "origin": self._current_file.getFileLocation() + }) def pause_print(self): + payload = { + "file": self._current_file.getFilename(), + "filename": os.path.basename(self._current_file.getFilename()), + "origin": self._current_file.getFileLocation() + } + if self._state == State.PRINTING: self._changeState(State.PAUSED) + eventManager().fire(Events.PRINT_PAUSED, payload) + elif self._state == State.PAUSED: self._changeState(State.PRINTING) + eventManager().fire(Events.PRINT_RESUMED, payload) def cancel_print(self): eventManager().fire(Events.PRINT_CANCELLED, { "file": self._current_file.getFilename(), + "filename": os.path.basename(self._current_file.getFilename()), "origin": self._current_file.getFileLocation() }) self._changeState(State.OPERATIONAL) diff --git a/src/octoprint/comm/protocol/reprap/__init__.py b/src/octoprint/comm/protocol/reprap/__init__.py index c0e180698..ec24ac62e 100644 --- a/src/octoprint/comm/protocol/reprap/__init__.py +++ b/src/octoprint/comm/protocol/reprap/__init__.py @@ -59,6 +59,7 @@ class RepRapProtocol(Protocol): ## Commands COMMAND_GET_TEMP = staticmethod(lambda: GcodeCommand("M105")) COMMAND_SET_EXTRUDER_TEMP = staticmethod(lambda s, t, w: GcodeCommand("M109", s=s, t=t) if w else GcodeCommand("M104", s=s, t=t)) + COMMAND_SET_LINE = staticmethod(lambda n: GcodeCommand("M110 N%d" % n)) COMMAND_SET_BED_TEMP = staticmethod(lambda s, w: GcodeCommand("M190", s=s) if w else GcodeCommand("M140", s=s)) COMMAND_SET_RELATIVE_POSITIONING = staticmethod(lambda: GcodeCommand("G91")) COMMAND_SET_ABSOLUTE_POSITIONING = staticmethod(lambda: GcodeCommand("G90")) @@ -128,11 +129,23 @@ class RepRapProtocol(Protocol): self._resend_delta = None self._last_resend_request = None + self._force_checksum = False + self._pingpong = False + self._rx_cache_fill = 0 + self._rx_cache_size = 127 + self._nack_lines = deque([]) + self._nack_lock = threading.Lock() + self._send_queue_processing = True self._thread = threading.Thread(target=self._handle_send_queue, name="SendQueueHandler") self._thread.daemon = True self._thread.start() + self._fill_queue_processing = True + self._fill_thread = threading.Thread(target=self._fill_send_queue, name="FillQueueHandler") + self._fill_thread.daemon = True + self._fill_thread.start() + self._current_line = 1 self._currentExtruder = 0 self._state = State.OFFLINE @@ -143,26 +156,43 @@ class RepRapProtocol(Protocol): self._lastTemperatureUpdate = time.time() self._lastSdProgressUpdate = time.time() - self._startSeen = not settings().get(["feature", "waitForStartOnConnect"]) + if settings().get(["feature", "waitForStartOnConnect"]) == True: + self._startSeen = False + self._clear_for_send.clear() + else: + self._startSeen = True + self._clear_for_send.set() + self._receivingSdFileList = False - self._clear_for_send.clear() + # create a new queue to clear the old one + self._send_queue = CommandQueue() self._last_lines.clear() self._resend_delta = None self._last_resend_request = None + self._force_checksum = self._useChecksum() + self._pingpong = self._usePingPong() + self._rx_cache_fill = 0 + self._nack_lines.clear() + self._current_line = 1 self._currentExtruder = 0 def connect(self, opt): self._reset() + # connect + Protocol.connect(self, opt) + # enqueue our first temperature query so it get's sent right on establishment of the connection self._send_temperature_query(withType=True) - # connect - Protocol.connect(self, opt) + def disconnect(self): + self._clear_for_send.clear() + # disconnect + Protocol.disconnect(self) def select_file(self, filename, origin): if origin == FileDestinations.SDCARD: @@ -181,8 +211,6 @@ class RepRapProtocol(Protocol): self._send(RepRapProtocol.COMMAND_SD_SET_POS(0)) self._current_file.setFilepos(0) self._send(RepRapProtocol.COMMAND_SD_START()) - else: - self._send_next() def cancel_print(self): if isinstance(self._current_file, PrintingSdFileInformation): @@ -194,10 +222,14 @@ class RepRapProtocol(Protocol): def init_sd(self): Protocol.init_sd(self) self._send(RepRapProtocol.COMMAND_SD_INIT()) + if settings().getBoolean(["feature", "sdAlwaysAvailable"]) == True: + self._changeSdState(True) def release_sd(self): Protocol.release_sd(self) self._send(RepRapProtocol.COMMAND_SD_RELEASE()) + if settings().getBoolean(["feature", "sdAlwaysAvailable"]) == True: + self._changeSdState(False) def refresh_sd_files(self): if not self._sd_available: @@ -215,12 +247,12 @@ class RepRapProtocol(Protocol): self._current_file = StreamingGcodeFileInformation(path, local, remote) - self._changeState(State.STREAMING) self._current_file.start() eventManager().fire(Events.TRANSFER_STARTED, {"local": local, "remote": remote}) self._startFileTransfer(remote, self._current_file.getFilesize()) + self._changeState(State.STREAMING) def remove_sd_file(self, filename): Protocol.remove_sd_file(self, filename) @@ -286,13 +318,18 @@ class RepRapProtocol(Protocol): return if isinstance(command, (tuple, list)): for c in command: - self._send(c, highPriority=high_priority, withChecksum=self._useChecksum()) + self._send(c, highPriority=high_priority) else: - self._send(command, highPriority=high_priority, withChecksum=self._useChecksum()) + self._send(command, highPriority=high_priority) def _fileTransferFinished(self, current_file): if isinstance(current_file, StreamingGcodeFileInformation): self.send_manually(RepRapProtocol.COMMAND_SD_END_WRITE(current_file.getRemoteFilename())) + eventManager().fire(Events.TRANSFER_DONE, { + "local": local, + "remote": remote, + "time": self.getPrintTime() + }) else: self._logger.warn("Finished file transfer to printer's SD card, but could not determine remote filename, assuming 'unknown.gco' for end-write-command") self.send_manually(RepRapProtocol.COMMAND_SD_END_WRITE("unknown.gco")) @@ -306,6 +343,40 @@ class RepRapProtocol(Protocol): message = self._handle_errors(message.strip()) + # resend == roll back time a bit + if RepRapProtocol.MESSAGE_RESEND(message): + # zero cache fill count + with self._nack_lock: + self._rx_cache_fill = 0 + self._nack_lines.clear() + self._handle_resend_request(message) + return + + if self._resend_delta is None and not self.is_streaming(): + if time.time() > self._lastTemperatureUpdate + 5: + self._send_temperature_query(withType=True) + elif self.is_sd_printing() and time.time() > self._lastSdProgressUpdate + 5: + self._send_sd_progress_query(withType=True) + + # ok == go ahead with sending + if RepRapProtocol.MESSAGE_OK(message): + if self._state == State.CONNECTED and self._startSeen: + # if we are currently connected, have seen start and just gotten an "ok" we are now operational + self._changeState(State.OPERATIONAL) + if self.is_heating_up(): + self._heatupDone() + + # lower cache fill count since the command went through + with self._nack_lock: + if len(self._nack_lines) > 0: + self._rx_cache_fill -= self._nack_lines.popleft() + self._clear_for_send.set() + return + + if RepRapProtocol.MESSAGE_WAIT(message): + with self._nack_lock: + self._clear_for_send.set() + # SD file list if self._receivingSdFileList and not RepRapProtocol.MESSAGE_SD_END_FILE_LIST(message): fileinfo = message.strip().split(None, 2) @@ -378,42 +449,23 @@ class RepRapProtocol(Protocol): return # initial handshake with the firmware - if not self._startSeen and RepRapProtocol.MESSAGE_START(message): - # if we did not see "start" from the firmware yet and we just did we are cleared for sending + if RepRapProtocol.MESSAGE_START(message): + if self._state != State.CONNECTED: + # we received a "start" while running, this means the printer has unexpectedly reset + self._reset() + self._changeState(State.CONNECTED) + # otherwise we did not see "start" from the firmware yet and we just did; we are cleared for sending self._startSeen = True self._clear_for_send.set() - if self._state == State.CONNECTED and self._startSeen and RepRapProtocol.MESSAGE_OK(message): - # if we are currently connected, have seen start and just gotten an "ok" we are now operational - self._changeState(State.OPERATIONAL) - - # resend == roll back time a bit - if RepRapProtocol.MESSAGE_RESEND(message): - self._handle_resend_request(message) - - # ok == go ahead with sending - if RepRapProtocol.MESSAGE_OK(message): - if self.is_heating_up(): - self._heatupDone() - - if self.is_printing() or self.is_streaming(): - if not self.is_sd_printing() and not self._state == State.PAUSED: - self._send_next() - if self._resend_delta is None and not self.is_streaming(): - if time.time() > self._lastTemperatureUpdate + 5: - self._send_temperature_query(withType=True) - elif self.is_sd_printing() and time.time() > self._lastSdProgressUpdate + 5: - self._send_sd_progress_query(withType=True) - self._clear_for_send.set() - def onTimeoutReceived(self, source): if self._transport != source: return - - if self._state == State.CONNECTED: - # it might be that the printer controller did not reset on connect and therefore we won't ever see a start => try clearing for send + self._logger.warn("Communication timeout") + # allow sending to restart communcation + if self._state != State.OFFLINE: self._clear_for_send.set() - self._send_temperature_query(withType=True) + ##~~ private @@ -422,17 +474,25 @@ class RepRapProtocol(Protocol): def _send(self, command, highPriority=False, commandType=None, withChecksum=None, withLinenumber=None): if withChecksum is None: - withChecksum = self._useChecksum() - commandTuple = (command, withChecksum, withLinenumber) + withChecksum = self._force_checksum priority = 100 if highPriority: priority = 1 - if commandType is not None: - self._send_queue.put((priority, commandTuple, commandType)) - else: - self._send_queue.put((priority, commandTuple)) + if not isinstance(command, GcodeCommand): + command = GcodeCommand.from_line(command) + preprocessed = self._preprocess_command(command, with_checksum=withChecksum, with_line_number=withLinenumber) + + if withChecksum == False: + command = None + + if commandType is not None: + self._send_queue.put((priority, command, preprocessed, commandType)) + else: + self._send_queue.put((priority, command, preprocessed)) + + # Called only from worker thread, not thread safe def _send_next(self): if self._resend_delta is not None: command = self._last_lines[-self._resend_delta] @@ -568,8 +628,17 @@ class RepRapProtocol(Protocol): # reset resend delta, we can't do anything about it self._resend_delta = None + # reset line number local and remote + self._current_line = 1 + self._last_lines.clear() + self._resend_delta = None + self._send(RepRapProtocol.COMMAND_SET_LINE(0)) + def _useChecksum(self): - return settings().getBoolean(["feature", "alwaysSendChecksum"]) or (not self._transport_properties[TransportProperties.FLOWCONTROL] and self.is_busy()) + return settings().getBoolean(["feature", "alwaysSendChecksum"]) + + def _usePingPong(self): + return settings().getBoolean(["feature", "pingPong"]) ##~~ specific command actions @@ -635,31 +704,60 @@ class RepRapProtocol(Protocol): self.cancel_print() return command, with_checksum, with_line_number + + ##~~ handle queue filling in this thread when printing or streaming + + def _fill_send_queue(self): + while self._fill_queue_processing: + # queue is full, wait a bit before checking again + if self._send_queue.qsize() > 20: + time.sleep(0.05) + # -send_next only if printing (not SD) or streaming + elif ((self._state == State.PRINTING and not isinstance(self._current_file, PrintingSdFileInformation)) + or self._state == State.STREAMING): + self._send_next() + # not printing or streaming + else: + time.sleep(0.1) + + ##~~ the actual send queue handling starts here def _handle_send_queue(self): while self._send_queue_processing: - self._clear_for_send.wait() - self._clear_for_send.clear() - entry = self._send_queue.get() - if len(entry) == 3: - priority, command_tuple, command_type = entry + if self._send_queue.qsize() == 0: + # queue is empty, wait a bit before checking again + time.sleep(0.1) + continue + entry = self._send_queue.peek() + if len(entry) == 4: + priority, command, preprocessed, command_type = entry else: - priority, command_tuple = entry + priority, command, preprocessed = entry - command, with_checksum, with_line_number = command_tuple - if not isinstance(command, GcodeCommand): - command = GcodeCommand.from_line(command) - preprocessed_command = self._preprocess_command(command, with_checksum=with_checksum, with_line_number=with_line_number) + size = len(preprocessed) + 1 + # deassert _clear_for_send to wait for an "ok" if cache full + self._nack_lock.acquire() + if self._rx_cache_fill + size > self._rx_cache_size: + self._nack_lock.release() + self._clear_for_send.clear() + self._clear_for_send.wait() + continue + # put tx size into the list so we can pop it later when we get "ok" + self._nack_lines.append(size) + self._rx_cache_fill += size + self._nack_lock.release() + # send the command + self._transport.send(preprocessed) + # remove from queue + self._send_queue.get() - if preprocessed_command is not None: - self._transport.send(preprocessed_command) + if command is not None: + self._last_lines.append(command) + if self._pingpong == True: + self._clear_for_send.clear() + self._clear_for_send.wait() - if with_checksum: - self._last_lines.append(command) - else: - # reset clear for send flag, since we didn't send a command just now - self._clear_for_send.set() def _preprocess_command(self, command, with_checksum=False, with_line_number=None): if command is None: diff --git a/src/octoprint/comm/protocol/reprap/util.py b/src/octoprint/comm/protocol/reprap/util.py index a999988f8..e148d4b1f 100644 --- a/src/octoprint/comm/protocol/reprap/util.py +++ b/src/octoprint/comm/protocol/reprap/util.py @@ -121,10 +121,10 @@ class CommandQueue(Queue.Queue): return len(self.queue) def _put(self, item, heappush=heapq.heappush): - if len(item) == 3: - priority, command, commandType = item + if len(item) == 4: + priority, command, preprocessed, commandType = item else: - priority, command = item + priority, command, preprocessed = item commandType = None if commandType is not None: @@ -133,14 +133,17 @@ class CommandQueue(Queue.Queue): else: return - heappush(self.queue, (priority, next(self.counter), command, commandType)) + heappush(self.queue, (priority, next(self.counter), command, preprocessed, commandType)) def _get(self, heappop=heapq.heappop): - priority, count, command, commandType = heappop(self.queue) + priority, count, command, preprocessed, commandType = heappop(self.queue) if commandType in self.lookup: del self.lookup[commandType] - return priority, command, commandType + return priority, command, preprocessed, commandType + def peek(self): + priority, count, command, preprocessed, commandType = self.queue[0] + return priority, command, preprocessed, commandType class PrintingGcodeFileInformation(PrintingFileInformation): """ @@ -156,6 +159,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation): self._offsetCallback = offsetCallback + self._fileHandle = None if not os.path.exists(self._filename) or not os.path.isfile(self._filename): raise IOError("File %s does not exist" % self._filename) self._filesize = os.stat(self._filename).st_size diff --git a/src/octoprint/comm/transport/__init__.py b/src/octoprint/comm/transport/__init__.py index a6fec3a28..ae63c6181 100644 --- a/src/octoprint/comm/transport/__init__.py +++ b/src/octoprint/comm/transport/__init__.py @@ -5,6 +5,7 @@ __copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the import logging +from octoprint.events import eventManager, Events class Transport(object): @@ -35,7 +36,7 @@ class Transport(object): self.changeState(State.DISCONNECTED_WITH_ERROR) else: self.changeState(State.DISCONNECTED) - + eventManager().fire(Events.DISCONNECTED) def send(self, command): pass diff --git a/src/octoprint/comm/transport/serialTransport.py b/src/octoprint/comm/transport/serialTransport.py index 014cbccc1..0f464ed1f 100644 --- a/src/octoprint/comm/transport/serialTransport.py +++ b/src/octoprint/comm/transport/serialTransport.py @@ -17,7 +17,7 @@ from . import Transport, TransportProperties, State from octoprint.util import getExceptionString from octoprint.util.virtual import VirtualPrinter from octoprint.settings import settings - +from octoprint.events import eventManager, Events class SerialTransport(Transport): @@ -126,17 +126,17 @@ class SerialTransport(Transport): self._serial = VirtualPrinter(timeout=self._communicationTimeout, writeTimeout=self._writeTimeout) self.changeState(State.CONNECTED) self._transport_logger.debug("Connected to VIRTUAL printer") - return True else: try: self._serial = serial.Serial(self._port, self._baudrate, timeout=self._communicationTimeout, writeTimeout=self._writeTimeout) self.changeState(State.CONNECTED) self._transport_logger.debug("Connected to %s" % self._serial) - return True except: self.logError("Unexpected error while connecting to serial port: %s %s" % (self._port, getExceptionString())) self.onError("Failed to open serial port, permissions correct?") return False + eventManager().fire(Events.CONNECTED, {"port": self._port, "baudrate": self._baudrate}) + return True def _readline(self): if self._serial is None: diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 701505ad9..85ab5cda7 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -303,7 +303,7 @@ class CommandTrigger(GenericEventListener): def _executeGcodeCommand(self, command): commands = [command] if isinstance(command, (list, tuple, set)): - self.logger.debug("Executing GCode commands: %r" % command) + self._logger.debug("Executing GCode commands: %r" % command) commands = list(command) else: self._logger.debug("Executing GCode command: %s" % command) diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 63ed8eb08..5ace60e41 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -66,6 +66,7 @@ def getSettings(): "temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]), "waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]), "alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]), + "pingPong": s.getBoolean(["feature", "pingPong"]), "sdSupport": s.getBoolean(["feature", "sdSupport"]), "sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]), "swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]), @@ -163,6 +164,7 @@ def setSettings(): if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"]) if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"]) if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"]) + if "pingPong" in data["feature"].keys(): s.setBoolean(["feature", "pingPong"], data["feature"]["pingPong"]) if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"]) if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"]) if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"]) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index d157bf661..cc91c1128 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -100,6 +100,7 @@ default_settings = { "temperatureGraph": True, "waitForStartOnConnect": False, "alwaysSendChecksum": False, + "pingPong": False, "sdSupport": True, "sdAlwaysAvailable": False, "swallowOkAfterResend": True, diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 909be6196..7bbf3b697 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -134,6 +134,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.feature_temperatureGraph = ko.observable(undefined); self.feature_waitForStart = ko.observable(undefined); self.feature_alwaysSendChecksum = ko.observable(undefined); + self.feature_pingPong = ko.observable(undefined); self.feature_sdSupport = ko.observable(undefined); self.feature_sdAlwaysAvailable = ko.observable(undefined); self.feature_swallowOkAfterResend = ko.observable(undefined); @@ -258,6 +259,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.feature_temperatureGraph(response.feature.temperatureGraph); self.feature_waitForStart(response.feature.waitForStart); self.feature_alwaysSendChecksum(response.feature.alwaysSendChecksum); + self.feature_pingPong(response.feature.pingPong); self.feature_sdSupport(response.feature.sdSupport); self.feature_sdAlwaysAvailable(response.feature.sdAlwaysAvailable); self.feature_swallowOkAfterResend(response.feature.swallowOkAfterResend); @@ -330,6 +332,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { "temperatureGraph": self.feature_temperatureGraph(), "waitForStart": self.feature_waitForStart(), "alwaysSendChecksum": self.feature_alwaysSendChecksum(), + "pingPong": self.feature_pingPong(), "sdSupport": self.feature_sdSupport(), "sdAlwaysAvailable": self.feature_sdAlwaysAvailable(), "swallowOkAfterResend": self.feature_swallowOkAfterResend(), diff --git a/src/octoprint/templates/settings.jinja2 b/src/octoprint/templates/settings.jinja2 index 7ce9fd072..43d782bdc 100644 --- a/src/octoprint/templates/settings.jinja2 +++ b/src/octoprint/templates/settings.jinja2 @@ -293,7 +293,14 @@