From 7e2382fed4199ee50db14e40cc8b03c694894a04 Mon Sep 17 00:00:00 2001 From: Dattas Moonchaser Date: Thu, 20 Oct 2016 19:06:26 -0600 Subject: [PATCH 01/72] Add option to repeat last captured frame instead of capturing new frames for the end of a timelapse. Defaults to current behavior (capturing new frames for the time after). Implements foosel/OctoPrint#1422 --- src/octoprint/server/api/timelapse.py | 14 ++++++- src/octoprint/settings.py | 3 +- .../static/js/app/viewmodels/timelapse.js | 12 ++++++ src/octoprint/templates/tabs/timelapse.jinja2 | 6 +++ src/octoprint/timelapse.py | 41 +++++++++++++++---- 5 files changed, 67 insertions(+), 9 deletions(-) diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 33b3bddd6..872b204fa 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -66,7 +66,8 @@ def getTimelapseData(): config = dict(type="timed", postRoll=timelapse.post_roll, fps=timelapse.fps, - interval=timelapse.interval) + interval=timelapse.interval, + capturePostRoll=timelapse.capture_post_roll) else: config = dict(type="off") @@ -204,6 +205,16 @@ def setTimelapseConfig(): else: return make_response("Invalid value for interval: %d" % interval) + if "capturePostRoll" in data: + config["options"]["capturePostRoll"] = True + try: + capturePostRoll = bool(data["capturePostRoll"]) + except ValueError: + return make_response("Invalid value for capturePostRoll: %r" % data["capturePostRoll"]) + else: + config["options"]["capturePostRoll"] = capturePostRoll + + if "retractionZHop" in request.values: config["options"] = { "retractionZHop": 0 @@ -219,6 +230,7 @@ def setTimelapseConfig(): else: return make_response("Invalid value for retraction Z-Hop: %d" % retractionZHop) + if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues: octoprint.timelapse.configure_timelapse(config, True) else: diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index bf0ac1194..ddf5aabd3 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -166,7 +166,8 @@ default_settings = { "type": "off", "options": {}, "postRoll": 0, - "fps": 25 + "fps": 25, + "capturePostRoll": True }, "cleanTmpAfterDays": 7 }, diff --git a/src/octoprint/static/js/app/viewmodels/timelapse.js b/src/octoprint/static/js/app/viewmodels/timelapse.js index a7230d897..f50b6da1c 100644 --- a/src/octoprint/static/js/app/viewmodels/timelapse.js +++ b/src/octoprint/static/js/app/viewmodels/timelapse.js @@ -10,12 +10,14 @@ $(function() { self.defaultPostRoll = 0; self.defaultInterval = 10; self.defaultRetractionZHop = 0; + self.defaultCapturePostroll = true; self.timelapseType = ko.observable(undefined); self.timelapseTimedInterval = ko.observable(self.defaultInterval); self.timelapsePostRoll = ko.observable(self.defaultPostRoll); self.timelapseFps = ko.observable(self.defaultFps); self.timelapseRetractionZHop = ko.observable(self.defaultRetractionZHop); + self.timelapseCapturePostRoll = ko.observable(self.defaultCapturePostRoll); self.persist = ko.observable(false); self.isDirty = ko.observable(false); @@ -61,6 +63,9 @@ $(function() { self.timelapseRetractionZHop.subscribe(function(newValue) { self.isDirty(true); }); + self.timelapseCapturePostRoll.subscribe(function() { + self.isDirty(true); + }); // initialize list helper self.listHelper = new ItemListHelper( @@ -167,6 +172,12 @@ $(function() { self.timelapseFps(self.defaultFps); } + if (config.capturePostRoll != undefined){ + self.timelapseCapturePostRoll(config.capturePostRoll); + } else { + self.timelapseCapturePostRoll(self.defaultCapturePostRoll); + } + self.persist(false); self.isDirty(false); }; @@ -214,6 +225,7 @@ $(function() { if (self.timelapseType() == "timed") { payload["interval"] = self.timelapseTimedInterval(); + payload["capturePostRoll"] = self.timelapseCapturePostRoll(); } if (self.timelapseType() == "zchange") { diff --git a/src/octoprint/templates/tabs/timelapse.jinja2 b/src/octoprint/templates/tabs/timelapse.jinja2 index 041c3bc34..e01f4ebe8 100644 --- a/src/octoprint/templates/tabs/timelapse.jinja2 +++ b/src/octoprint/templates/tabs/timelapse.jinja2 @@ -24,6 +24,12 @@ {{ _('sec') }} +
+ +
+
diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index 214428436..899e4e59f 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -303,7 +303,10 @@ def configure_timelapse(config=None, persist=False): interval = 10 if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0: interval = config["options"]["interval"] - current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps) + capture_post_roll = True + if "options" in config and "capturePostRoll" in config["options"] and isinstance(config["options"]["capturePostRoll"], bool): + capture_post_roll = config["options"]["capturePostRoll"] + current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps, capture_post_roll=capture_post_roll) notify_callbacks(current) @@ -628,11 +631,12 @@ class ZTimelapse(Timelapse): class TimedTimelapse(Timelapse): - def __init__(self, post_roll=0, interval=1, fps=25): + def __init__(self, post_roll=0, interval=1, fps=25, capture_post_roll=True): Timelapse.__init__(self, post_roll=post_roll, fps=fps) self._interval = interval if self._interval < 1: self._interval = 1 # force minimum interval of 1s + self._capture_post_roll = capture_post_roll self._postroll_captures = 0 self._timer = None self._logger.debug("TimedTimelapse initialized") @@ -641,11 +645,16 @@ class TimedTimelapse(Timelapse): def interval(self): return self._interval + @property + def capture_post_roll(self): + return self._capture_post_roll + def config_data(self): return { "type": "timed", "options": { - "interval": self._interval + "interval": self._interval, + "capture_post_roll": self._capture_post_roll } } @@ -662,14 +671,31 @@ class TimedTimelapse(Timelapse): self._timer.start() def on_print_done(self, event, payload): - self._postroll_captures = self._post_roll * self._fps + if self._capture_post_roll: + self._postroll_captures = self._post_roll * self._fps Timelapse.on_print_done(self, event, payload) def calculate_post_roll(self): - return self._post_roll * self._fps * self._interval + if self._capture_post_roll: + return self._post_roll * self._fps * self._interval + else: + return Timelapse.calculate_post_roll(self) def process_post_roll(self): - pass + if self._capture_post_roll: + return + + with self._capture_mutex: + filename = os.path.join(self._capture_dir, _capture_format.format(prefix=self._file_prefix) % self._image_number) + self._image_number += 1 + + if self._perform_capture(filename): + for _ in range(self._post_roll * self._fps): + newFile = os.path.join(self._capture_dir, _capture_format.format(prefix=self._file_prefix) % self._image_number) + self._image_number += 1 + shutil.copyfile(filename, newFile) + + self.post_roll_finished() def post_roll_finished(self): Timelapse.post_roll_finished(self) @@ -684,7 +710,8 @@ class TimedTimelapse(Timelapse): self._postroll_captures -= 1 def _on_timer_finished(self): - self.post_roll_finished() + if self._capture_post_roll: + self.post_roll_finished() class TimelapseRenderJob(object): From 5446dc645c170821e6b3325e6167839af8ab98a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 11 Nov 2016 11:45:17 +0100 Subject: [PATCH 02/72] Use default settings preprocessors if none are provided Re-enables feedback controls. Closes #1588 --- src/octoprint/settings.py | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index bf0ac1194..9746eecbe 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -1105,12 +1105,14 @@ class Settings(object): else: chain = self._map + if preprocessors is None: + preprocessors = self._get_preprocessors + preprocessor = None - if preprocessors is not None: - try: - preprocessor = self._get_by_path(path, preprocessors) - except NoSuchSettingsPath: - pass + try: + preprocessor = self._get_by_path(path, preprocessors) + except NoSuchSettingsPath: + pass parent_path = path[:-1] last = path[-1] @@ -1310,15 +1312,17 @@ class Settings(object): else: chain = self._map - preprocessor = None - if preprocessors is not None: - try: - preprocessor = self._get_by_path(path, preprocessors) - except NoSuchSettingsPath: - pass + if preprocessors is None: + preprocessors = self._set_preprocessors - if callable(preprocessor): - value = preprocessor(value) + preprocessor = None + try: + preprocessor = self._get_by_path(path, preprocessors) + except NoSuchSettingsPath: + pass + + if callable(preprocessor): + value = preprocessor(value) try: current = chain.get_by_path(path) From c8273785cd73f3f11652f17899c25e3e8f005c15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 11 Nov 2016 11:52:33 +0100 Subject: [PATCH 03/72] Fix position tracking of virtual printer Wasn't taking relative moves into account for coordinate persistence. --- .../plugins/virtual_printer/virtual.py | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 2ae3ba86c..f4b6c4b77 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -705,7 +705,11 @@ class VirtualPrinter(object): duration = max(duration, x * self._unitModifier / float(self.speeds["x"]) * 60.0) else: duration = max(duration, (x - self._lastX) * self._unitModifier / float(self.speeds["x"]) * 60.0) - self._lastX = x + + if self._relative and self._lastX is not None: + self._lastX += x + else: + self._lastX = x except: pass if matchY is not None: @@ -715,7 +719,11 @@ class VirtualPrinter(object): duration = max(duration, y * self._unitModifier / float(self.speeds["y"]) * 60.0) else: duration = max(duration, (y - self._lastY) * self._unitModifier / float(self.speeds["y"]) * 60.0) - self._lastY = y + + if self._relative and self._lastY is not None: + self._lastY += y + else: + self._lastY = y except: pass if matchZ is not None: @@ -725,7 +733,11 @@ class VirtualPrinter(object): duration = max(duration, z * self._unitModifier / float(self.speeds["z"]) * 60.0) else: duration = max(duration, (z - self._lastZ) * self._unitModifier / float(self.speeds["z"]) * 60.0) - self._lastZ = z + + if self._relative and self._lastZ is not None: + self._lastZ += z + else: + self._lastZ = z except: pass if matchE is not None: @@ -735,7 +747,11 @@ class VirtualPrinter(object): duration = max(duration, e * self._unitModifier / float(self.speeds["e"]) * 60.0) else: duration = max(duration, (e - self._lastE) * self._unitModifier / float(self.speeds["e"]) * 60.0) - self._lastE = e + + if self._relative and self._lastE is not None: + self._lastE += e + else: + self._lastE = e except: pass From b4215c885c5ae967cf50df8161b3571c35a2334d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 11 Nov 2016 13:24:00 +0100 Subject: [PATCH 04/72] Support M114 responses without whitespace between coordinates Because apparently there exist some firmware variants/forks which don't have spaces between the coordinate entries. Who needs standards :) --- src/octoprint/util/comm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 1648ae85f..9ea226cf8 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -113,7 +113,7 @@ Groups will be as follows: * ``target``: new target temperature (float) """ -regex_position = re.compile("X:(?P{float})\s+Y:(?P{float})\s+Z:(?P{float})\s+E:(?P{float})".format(float=regex_float_pattern)) +regex_position = re.compile("X:(?P{float})\s*Y:(?P{float})\s*Z:(?P{float})\s*E:(?P{float})".format(float=regex_float_pattern)) """Regex for matching position reporting. Groups will be as follows: From 2c6fb68544239afcdd63e629aab8ae57f4b05e18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 11 Nov 2016 15:20:19 +0100 Subject: [PATCH 05/72] SWU: Fix issue with log output containing non ASCII characters See #1586 --- .../softwareupdate/scripts/update-octoprint.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py index fdb065e60..9c6a600f3 100644 --- a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py +++ b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py @@ -27,7 +27,9 @@ def _log(lines, prefix=None, stream=None): output_stream = sys.stderr for line in lines: - print(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")), file=output_stream) + to_print = _to_str(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")), + errors="replace") + print(to_print, file=output_stream) def _to_unicode(s_or_u, encoding="utf-8", errors="strict"): @@ -38,6 +40,14 @@ def _to_unicode(s_or_u, encoding="utf-8", errors="strict"): return s_or_u +def _to_str(s_or_u, encoding="utf-8", errors="strict"): + """Make sure ``s_or_u`` is a str.""" + if isinstance(s_or_u, unicode): + return s_or_u.encode(encoding, errors=errors) + else: + return s_or_u + + def _execute(command, **kwargs): import sarge From 0a9475661fd4b68b9a0ff0ad06acf993fa833e0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 11 Nov 2016 15:26:36 +0100 Subject: [PATCH 06/72] SWU: more verbose output on restart fail --- src/octoprint/plugins/softwareupdate/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 7a3ac351d..e2b84192e 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -794,9 +794,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, try: util.execute(restart_command) except exceptions.ScriptError as e: - self._logger.exception("Error while restarting") - self._logger.warn("Restart stdout:\n%s" % e.stdout) - self._logger.warn("Restart stderr:\n%s" % e.stderr) + self._logger.exception("Error while restarting via command {}".format(restart_command)) + self._logger.warn("Restart stdout:\n{}".format(e.stdout)) + self._logger.warn("Restart stderr:\n{}".format(e.stderr)) raise exceptions.RestartFailed() def _populated_check(self, target, check): From 4a67762ead7237616d2eb1f031e3d5bf6914ff5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 14 Nov 2016 13:24:56 +0100 Subject: [PATCH 07/72] virtual printer: Track F and flow/feedrate factors --- .../plugins/virtual_printer/virtual.py | 36 ++++++++++++++----- src/octoprint/settings.py | 6 ---- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index f4b6c4b77..b75cedf31 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -59,15 +59,17 @@ class VirtualPrinter(object): self.lastTempAt = time.time() self.bedTemp = 1.0 self.bedTargetTemp = 1.0 - self.speeds = settings().get(["devel", "virtualPrinter", "movementSpeed"]) self._relative = True self._lastX = 0.0 self._lastY = 0.0 self._lastZ = 0.0 self._lastE = 0.0 + self._lastF = 200 self._unitModifier = 1 + self._feedrate_multiplier = 100 + self._flowrate_multiplier = 100 self._virtualSd = settings().getBaseFolder("virtualSd") self._sdCardReady = True @@ -383,6 +385,12 @@ class VirtualPrinter(object): if self._echoOnM117: self._send("echo:%s" % re.search("M117\s+(.*)", data).group(1)) + def _gcode_M220(self, data): + self._feedrate_multiplier = float(re.search('S([0-9]+)', data).group(1)) + + def _gcode_M221(self, data): + self._flowrate_multiplier = float(re.search('S([0-9]+)', data).group(1)) + def _gcode_M400(self, data): self.buffered.join() @@ -696,15 +704,25 @@ class VirtualPrinter(object): matchY = re.search("Y([0-9.]+)", line) matchZ = re.search("Z([0-9.]+)", line) matchE = re.search("E([0-9.]+)", line) + matchF = re.search("F([0-9.]+)", line) duration = 0 + if matchF is not None: + try: + self._lastF = float(matchF.group(1)) + except: + pass + + speedXYZ = self._lastF * (self._feedrate_multiplier / 100.0) + speedE = self._lastF * (self._flowrate_multiplier / 100.0) + if matchX is not None: try: x = float(matchX.group(1)) if self._relative or self._lastX is None: - duration = max(duration, x * self._unitModifier / float(self.speeds["x"]) * 60.0) + duration = max(duration, x * self._unitModifier / speedXYZ * 60.0) else: - duration = max(duration, (x - self._lastX) * self._unitModifier / float(self.speeds["x"]) * 60.0) + duration = max(duration, (x - self._lastX) * self._unitModifier / speedXYZ * 60.0) if self._relative and self._lastX is not None: self._lastX += x @@ -716,9 +734,9 @@ class VirtualPrinter(object): try: y = float(matchY.group(1)) if self._relative or self._lastY is None: - duration = max(duration, y * self._unitModifier / float(self.speeds["y"]) * 60.0) + duration = max(duration, y * self._unitModifier / speedXYZ * 60.0) else: - duration = max(duration, (y - self._lastY) * self._unitModifier / float(self.speeds["y"]) * 60.0) + duration = max(duration, (y - self._lastY) * self._unitModifier / speedXYZ * 60.0) if self._relative and self._lastY is not None: self._lastY += y @@ -730,9 +748,9 @@ class VirtualPrinter(object): try: z = float(matchZ.group(1)) if self._relative or self._lastZ is None: - duration = max(duration, z * self._unitModifier / float(self.speeds["z"]) * 60.0) + duration = max(duration, z * self._unitModifier / speedXYZ * 60.0) else: - duration = max(duration, (z - self._lastZ) * self._unitModifier / float(self.speeds["z"]) * 60.0) + duration = max(duration, (z - self._lastZ) * self._unitModifier / speedXYZ * 60.0) if self._relative and self._lastZ is not None: self._lastZ += z @@ -744,9 +762,9 @@ class VirtualPrinter(object): try: e = float(matchE.group(1)) if self._relative or self._lastE is None: - duration = max(duration, e * self._unitModifier / float(self.speeds["e"]) * 60.0) + duration = max(duration, e * self._unitModifier / speedE * 60.0) else: - duration = max(duration, (e - self._lastE) * self._unitModifier / float(self.speeds["e"]) * 60.0) + duration = max(duration, (e - self._lastE) * self._unitModifier / speedE * 60.0) if self._relative and self._lastE is not None: self._lastE += e diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 9746eecbe..23f030668 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -332,12 +332,6 @@ default_settings = { "numExtruders": 1, "includeCurrentToolInTemps": True, "includeFilenameInOpened": True, - "movementSpeed": { - "x": 6000, - "y": 6000, - "z": 200, - "e": 300 - }, "hasBed": True, "repetierStyleTargetTemperature": False, "repetierStyleResends": False, From c6b8b1725a714c14bb2f69ce685cc7042ab74bf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 14 Nov 2016 13:26:05 +0100 Subject: [PATCH 08/72] Fixed duplicated M140 line (merge error) --- src/octoprint/plugins/virtual_printer/virtual.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index b75cedf31..52c4c7e74 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -319,7 +319,7 @@ class VirtualPrinter(object): def _gcode_M140(self, data): self._parseBedCommand(data) - def _gcode_M140(self, data): + def _gcode_M190(self, data): self._parseBedCommand(data, wait=True, support_r=True) def _gcode_M105(self, data): From 2429ebc1a2a4aa5779b50704cbb10ffde9525bc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 14 Nov 2016 13:45:22 +0100 Subject: [PATCH 09/72] Virtual Printer: Simplified temperature output --- src/octoprint/plugins/virtual_printer/virtual.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 52c4c7e74..17517455b 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -643,12 +643,14 @@ class VirtualPrinter(object): else: output = "T:%.2f %s @:64\n" % (self.temp[self.currentExtruder], allTempsString) else: - output = "%s @:64\n" % allTempsString + output = allTempsString else: if includeTarget: - output = "T:%.2f /%.2f B:%.2f /%.2f @:64\n" % (self.temp[0], self.targetTemp[0], self.bedTemp, self.bedTargetTemp) + output = "T:%.2f /%.2f B:%.2f /%.2f" % (self.temp[0], self.targetTemp[0], self.bedTemp, self.bedTargetTemp) else: - output = "T:%.2f B:%.2f @:64\n" % (self.temp[0], self.bedTemp) + output = "T:%.2f B:%.2f" % (self.temp[0], self.bedTemp) + + output += " @:64\n" if includeOk: output = "ok " + output From 06f7abdb2d35699c55ac2aef30d4290b6dacd3dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 15 Nov 2016 10:25:40 +0100 Subject: [PATCH 10/72] Manually track position in file self._handle.tell lies because of line based reading and buffering --- src/octoprint/util/comm.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 9ea226cf8..aab9a1119 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -2515,8 +2515,16 @@ class PrintingGcodeFileInformation(PrintingFileInformation): Opens the file for reading and determines the file size. """ PrintingFileInformation.start(self) - self._read_lines = 0 self._handle = bom_aware_open(self._filename, encoding="utf-8", errors="replace") + self._pos = self._handle.tell() + if self._handle.encoding.endswith("-sig"): + # Apparently we found an utf-8 bom in the file. + # We need to add its length to our pos because it will + # be stripped transparently and we'll have no chance + # catching that. + import codecs + self._pos += len(codecs.BOM_UTF8) + self._read_lines = 0 def close(self): """ @@ -2548,11 +2556,17 @@ class PrintingGcodeFileInformation(PrintingFileInformation): self._pos = self._size self._report_stats() return None - line = to_unicode(self._handle.readline()) + + # we need to manually keep track of our pos here since + # codecs' readline will make our handle's tell not + # return the actual number of bytes read, but also the + # already buffered bytes (for detecting the newlines) + line = self._handle.readline() + self._pos += len(line.encode("utf-8")) + if not line: self.close() processed = self._process(line, offsets, current_tool) - self._pos = self._handle.tell() self._read_lines += 1 return processed except Exception as e: From e04bdb357156452a52ad91041e06efc74d08f65a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 15 Nov 2016 10:28:14 +0100 Subject: [PATCH 11/72] Allow access to the current printed file position --- src/octoprint/printer/standard.py | 9 +++++++++ src/octoprint/util/comm.py | 14 +++++++++++--- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 5a9719bc1..ac5b5be99 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -405,6 +405,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._setProgressData(completion=0) self._setCurrentZ(None) + def get_file_position(self): + if self._comm is None: + return None + + if self._selectedFile is None: + return None + + return self._comm.getFilePosition() + def start_print(self, pos=None): """ Starts the currently loaded print job. diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index aab9a1119..d3c81d430 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -939,15 +939,23 @@ class MachineCom(object): ##~~ record aborted file positions - def _recordFilePosition(self): + def getFilePosition(self): if self._currentFile is None: - return + return None origin = self._currentFile.getFileLocation() filename = self._currentFile.getFilename() pos = self._currentFile.getFilepos() - self._callback.on_comm_record_fileposition(origin, filename, pos) + return dict(origin=origin, + filename=filename, + pos=pos) + + def _recordFilePosition(self): + if self._currentFile is None: + return + data = self.getFilePosition() + self._callback.on_comm_record_fileposition(data["origin"], data["filename"], data["pos"]) ##~~ communication monitoring and handling From 58835cfd8e32b3513baaf3790b848d810a88e41b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 15 Nov 2016 11:54:35 +0100 Subject: [PATCH 12/72] Add tracking of cancel position & make public --- .../actual/data/actualResumeFilePrefix.gcode | 31 +++++++++++ src/octoprint/printer/standard.py | 6 ++- src/octoprint/util/comm.py | 51 +++++++++++++------ 3 files changed, 71 insertions(+), 17 deletions(-) create mode 100644 src/octoprint/plugins/actual/data/actualResumeFilePrefix.gcode diff --git a/src/octoprint/plugins/actual/data/actualResumeFilePrefix.gcode b/src/octoprint/plugins/actual/data/actualResumeFilePrefix.gcode new file mode 100644 index 000000000..b2139fc72 --- /dev/null +++ b/src/octoprint/plugins/actual/data/actualResumeFilePrefix.gcode @@ -0,0 +1,31 @@ +; resume file for {{ file }} +; generated on {{ timestamp }} +; reason: {{ reason }} + +; home print head in X and Y +G28 X0 Y0 F1200 + +; set all temperatures back to original targets +{% for temp in temperatures %} +M104 T{{ temp.t }} S{{ temp.target }} +{% endfor %} +M116 ; wait for all temperatures to reach target + +; reposition nozzle X, Y, Z, E and feedrate +G1 X{{ position.x }} Y{{ position.y }} Z{{ position.z }} F4500 +G92 E{{ position.e }} +G1 F{{ movement.f }} + +; feed- and flowrate modifiers +M220 {{ movement.fm }} +M221 {{ movement.em }} + +; fan speeds +{% for fan in fans %} +M106 P{{ fan.p }} S{{ fan.speed }} +{% endfor %} + +; --- +; {{ file }}, starting at byte {{ pos }} +; --- + diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index ac5b5be99..76eba3367 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -965,8 +965,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def on_comm_temperature_update(self, temp, bedTemp): self._addTemperatureData(copy.deepcopy(temp), copy.deepcopy(bedTemp)) - def on_comm_position_update(self, position): - eventManager().fire(Events.POSITION_UPDATE, position) + def on_comm_position_update(self, position, reason=None): + payload = dict(reason=reason) + payload.update(position) + eventManager().fire(Events.POSITION_UPDATE, payload) def on_comm_state_change(self, state): """ diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index d3c81d430..4b18d68db 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -370,9 +370,11 @@ class MachineCom(object): self._ignore_select = False self._manualStreaming = False - self._last_position = PositionRecord() - self._pause_position = PositionRecord() + self.last_position = PositionRecord() + self.pause_position = PositionRecord() self._record_pause_position = False + self.cancel_position = PositionRecord() + self._record_cancel_position = False # print job self._currentFile = None @@ -669,8 +671,8 @@ class MachineCom(object): context.update(replacements) context.update(dict( printer_profile=self._printerProfileManager.get_current_or_default(), - last_position=self._last_position, - pause_position=self._pause_position + last_position=self.last_position, + pause_position=self.pause_position )) template = settings().loadScript("gcode", scriptName, context=context) @@ -806,6 +808,10 @@ class MachineCom(object): self._currentFile = None self._callback.on_comm_file_selected(None, None, False) + def _cancel_preparation_done(self): + self._recordFilePosition() + self._callback.on_comm_print_job_cancelled() + def cancelPrint(self, firmware_error=None): if not self.isOperational() or self.isStreaming(): return @@ -825,8 +831,14 @@ class MachineCom(object): except: pass - self._recordFilePosition() - self._callback.on_comm_print_job_cancelled() + def _on_M400_sent(): + # we don't call on_print_job_cancelled on our callback here + # because we do this only after our M114 has been answered + # by the firmware + self._record_cancel_position = True + self.sendCommand("M114") + + self.sendCommand("M400", on_sent=_on_M400_sent) def _pause_preparation_done(self): self._callback.on_comm_print_job_paused() @@ -1134,19 +1146,28 @@ class MachineCom(object): # there's no way to query it from the firmware and # no way to track it ourselves when not streaming # the file - this all sucks sooo much - self._last_position.x = float(match.group("x")) - self._last_position.y = float(match.group("y")) - self._last_position.z = float(match.group("z")) - self._last_position.e = float(match.group("e")) - self._last_position.t = self._currentTool if not self.isSdFileSelected() else None - self._last_position.f = self._currentF if not self.isSdFileSelected() else None + self.last_position.x = float(match.group("x")) + self.last_position.y = float(match.group("y")) + self.last_position.z = float(match.group("z")) + self.last_position.e = float(match.group("e")) + self.last_position.t = self._currentTool if not self.isSdFileSelected() else None + self.last_position.f = self._currentF if not self.isSdFileSelected() else None + + reason = None if self._record_pause_position: + reason = "pause" self._record_pause_position = False - self._pause_position.copy_from(self._last_position) + self.pause_position.copy_from(self.last_position) self._pause_preparation_done() - self._callback.on_comm_position_update(self._last_position.as_dict()) + if self._record_cancel_position: + reason = "cancel" + self._record_cancel_position = False + self.cancel_position.copy_from(self.last_position) + self._cancel_preparation_done() + + self._callback.on_comm_position_update(self.last_position.as_dict(), reason=reason) # temperature processing elif ' T:' in line or line.startswith('T:') or ' T0:' in line or line.startswith('T0:') or ((' B:' in line or line.startswith('B:')) and not 'A:' in line): @@ -2359,7 +2380,7 @@ class MachineComPrintCallback(object): def on_comm_temperature_update(self, temp, bedTemp): pass - def on_comm_position_update(self, position): + def on_comm_position_update(self, position, reason=None): pass def on_comm_state_change(self, state): From e6c4e0a808e3ff25852787e4b2bc54cde3ee0e4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 15 Nov 2016 11:55:09 +0100 Subject: [PATCH 13/72] Query byte position on cancel of SD print --- src/octoprint/util/comm.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 4b18d68db..de7c8036a 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -824,6 +824,7 @@ class MachineCom(object): if self.isSdFileSelected(): self.sendCommand("M25") # pause print + self.sendCommand("M27") # get current byte position in file self.sendCommand("M26 S0") # reset position in file to byte 0 if self._sd_status_timer is not None: try: From a8ff23abe4e360fbcd17951d7276eb53f49b0b23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 15 Nov 2016 11:55:34 +0100 Subject: [PATCH 14/72] Also track F parameters in G28 commands --- src/octoprint/util/comm.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index de7c8036a..d4e43ee64 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -2218,6 +2218,16 @@ class MachineCom(object): pass _gcode_G1_sent = _gcode_G0_sent + def _gcode_G28_sent(self, cmd, cmd_type=None): + if "F" in cmd: + match = regexes_parameters["floatF"].search(cmd) + if match: + try: + f = float(match.group("value")) + self._currentF = f + except ValueError: + pass + def _gcode_M0_queuing(self, cmd, cmd_type=None): self.setPause(True) return None, # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause. From cc5f119f1b7db764a85912bf6f05d60c2f79356d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 15 Nov 2016 11:56:30 +0100 Subject: [PATCH 15/72] Include position in PrintPaused and PrintCancelled events If available. Updated docs accordingly. --- docs/events/index.rst | 22 ++++++++++++++++++++++ src/octoprint/printer/standard.py | 23 ++++++++++++++--------- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/docs/events/index.rst b/docs/events/index.rst index 0b0139c90..506aadddf 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -308,6 +308,17 @@ PrintCancelled * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``position``: the print head position at the time of cancelling, if available + * ``position.x``: x coordinate, as reported back from the firmware through `M114` + * ``position.y``: y coordinate, as reported back from the firmware through `M114` + * ``position.z``: z coordinate, as reported back from the firmware through `M114` + * ``position.e``: e coordinate (of currently selected extruder), as reported back from the firmware through `M114` + * ``position.t``: last tool selected *through OctoPrint* (note that if you did change the printer's selected + tool outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will NOT + be accurate) + * ``position.f``: last feedrate for move commands **sent through OctoPrint** (note that if you modified the + feedrate outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will + NOT be accurate) .. deprecated:: 1.3.0 @@ -324,6 +335,17 @@ PrintPaused * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``position``: the print head position at the time of pausing, if available + * ``position.x``: x coordinate, as reported back from the firmware through `M114` + * ``position.y``: y coordinate, as reported back from the firmware through `M114` + * ``position.z``: z coordinate, as reported back from the firmware through `M114` + * ``position.e``: e coordinate (of currently selected extruder), as reported back from the firmware through `M114` + * ``position.t``: last tool selected *through OctoPrint* (note that if you did change the printer's selected + tool outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will NOT + be accurate) + * ``position.f``: last feedrate for move commands **sent through OctoPrint** (note that if you modified the + feedrate outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will + NOT be accurate) .. deprecated:: 1.3.0 diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 76eba3367..fe7ed97a2 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -1077,7 +1077,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): eventManager().fire(Events.PRINT_FAILED, payload) def on_comm_print_job_cancelled(self): - payload = self._payload_for_print_job_event() + payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None) if payload: eventManager().fire(Events.PRINT_CANCELLED, payload) self.script("afterPrintCancelled", @@ -1085,7 +1085,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): must_be_set=False) def on_comm_print_job_paused(self): - payload = self._payload_for_print_job_event() + payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None) if payload: eventManager().fire(Events.PRINT_PAUSED, payload) self.script("afterPrintPaused", @@ -1131,7 +1131,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): except: self._logger.exception("Error while trying to persist print recovery data") - def _payload_for_print_job_event(self, location=None, print_job_file=None): + def _payload_for_print_job_event(self, location=None, print_job_file=None, position=None): if print_job_file is None: selected_file = self._selectedFile if not selected_file: @@ -1156,13 +1156,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): _, name = self._fileManager.split_path(FileDestinations.LOCAL, path) origin = FileDestinations.LOCAL - return dict(name=name, - path=path, - origin=origin, + result= dict(name=name, + path=path, + origin=origin, - # TODO deprecated, remove in 1.4.0 - file=full_path, - filename=name) + # TODO deprecated, remove in 1.4.0 + file=full_path, + filename=name) + + if position is not None: + result["position"] = position + + return result class StateMonitor(object): From d52462b9f5af2177141f643705c1211ad22ae27d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 15 Nov 2016 11:57:09 +0100 Subject: [PATCH 16/72] Docs: Fixed GCODE event docs --- docs/events/index.rst | 40 ++++++++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/docs/events/index.rst b/docs/events/index.rst index 506aadddf..802ed3856 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -374,37 +374,53 @@ GCODE processing ---------------- PowerOn - The GCode has turned on the printer power via M80 + An ``M80`` was sent to the printer through OctoPrint (not triggered when printing from SD!) PowerOff - The GCODE has turned on the printer power via M81 + An ``M81`` was sent to the printer through OctoPrint (not triggered when printing from SD!) Home - The head has gone home via G28 + A ``G28`` was sent to the printer through OctoPrint (not triggered when printing from SD!) ZChange - The printer's Z-Height has changed (new layer) + The printer's Z-Height has changed (new layer) through a ``G0`` or ``G1`` that was sent to the printer through OctoPrint + (not triggered when printing from SD!) -Paused - The print has been paused +Dwell + A ``G4`` was sent to the printer through OctoPrint (not triggered when printing from SD!) Waiting - The print is paused due to a gcode wait command + One of the following commands was sent to the printer through OctoPrint (not triggered when printing from SD!): + ``M0``, ``M1``, ``M226`` Cooling - The GCODE has enabled the platform cooler via M245 + An ``M245`` was sent to the printer through OctoPrint (not triggered when printing from SD!) Alert - The GCODE has issued a user alert (beep) via M300 + An ``M300`` was sent to the printer through OctoPrint (not triggered when printing from SD!) Conveyor - The GCODE has enabled the conveyor belt via M240 + An ``M240`` was sent to the printer through OctoPrint (not triggered when printing from SD!) Eject - The GCODE has enabled the part ejector via M40 + An ``M40`` was sent to the printer through OctoPrint (not triggered when printing from SD!) EStop - The GCODE has issued a panic stop via M112 + An ``M112`` was sent to the printer through OctoPrint (not triggered when printing from SD!) + +PositionUpdate + The response to an ``M114`` was received by OctoPrint. The payload contains the current position information + parsed from the response and (in the case of the selected tool ``t`` and the current feedrate ``f``) tracked + by OctoPrint. + + Payload: + + * ``x``: x coordinate, parsed from response + * ``y``: y coordinate, parsed from response + * ``z``: z coordinate, parsed from response + * ``e``: e coordinate, parsed from response + * ``t``: last tool selected *through OctoPrint* + * ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint* Timelapses ---------- From f9253adf72a523b4956adca4d7addf60f580c512 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 15 Nov 2016 13:03:18 +0100 Subject: [PATCH 17/72] Remove accidentally commited plugin file --- .../actual/data/actualResumeFilePrefix.gcode | 31 ------------------- 1 file changed, 31 deletions(-) delete mode 100644 src/octoprint/plugins/actual/data/actualResumeFilePrefix.gcode diff --git a/src/octoprint/plugins/actual/data/actualResumeFilePrefix.gcode b/src/octoprint/plugins/actual/data/actualResumeFilePrefix.gcode deleted file mode 100644 index b2139fc72..000000000 --- a/src/octoprint/plugins/actual/data/actualResumeFilePrefix.gcode +++ /dev/null @@ -1,31 +0,0 @@ -; resume file for {{ file }} -; generated on {{ timestamp }} -; reason: {{ reason }} - -; home print head in X and Y -G28 X0 Y0 F1200 - -; set all temperatures back to original targets -{% for temp in temperatures %} -M104 T{{ temp.t }} S{{ temp.target }} -{% endfor %} -M116 ; wait for all temperatures to reach target - -; reposition nozzle X, Y, Z, E and feedrate -G1 X{{ position.x }} Y{{ position.y }} Z{{ position.z }} F4500 -G92 E{{ position.e }} -G1 F{{ movement.f }} - -; feed- and flowrate modifiers -M220 {{ movement.fm }} -M221 {{ movement.em }} - -; fan speeds -{% for fan in fans %} -M106 P{{ fan.p }} S{{ fan.speed }} -{% endfor %} - -; --- -; {{ file }}, starting at byte {{ pos }} -; --- - From 7ae6240de2824f962e34fda3cd4c88cdb413c071 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 15 Nov 2016 17:26:11 +0100 Subject: [PATCH 18/72] Make CommandLineCaller use unicode instead of bytes p.(stdout|stderr).text is unicode. p.(stdout|stderr).readline isn't, so decode manually. Should hopefully solve #1586 for good now... --- src/octoprint/util/commandline.py | 43 ++++++++++++++----------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/src/octoprint/util/commandline.py b/src/octoprint/util/commandline.py index 41e6abf72..47b8f424a 100644 --- a/src/octoprint/util/commandline.py +++ b/src/octoprint/util/commandline.py @@ -10,6 +10,8 @@ import sarge import logging import re +from . import to_unicode + # These regexes are based on the colorama package # Author: Jonathan Hartley @@ -82,36 +84,31 @@ class CommandlineCaller(object): all_stdout = [] all_stderr = [] + + def process_lines(lines, logger): + if not lines: + return [] + l = self._preprocess_lines(*map(lambda x: to_unicode(x, errors="replace"), lines)) + logger(*l) + return list(l) + + def process_stdout(lines): + return process_lines(lines, self._log_stdout) + + def process_stderr(lines): + return process_lines(lines, self._log_stderr) + try: while p.returncode is None: - lines = p.stderr.readlines(timeout=0.5) - if lines: - lines = self._preprocess_lines(*lines) - self._log_stderr(*lines) - all_stderr += list(lines) - - lines = p.stdout.readlines(timeout=0.5) - if lines: - lines = self._preprocess_lines(*lines) - self._log_stdout(*lines) - all_stdout += list(lines) - + all_stderr += process_stderr(p.stderr.readlines(timeout=0.5)) + all_stdout += process_stdout(p.stdout.readlines(timeout=0.5)) p.commands[0].poll() finally: p.close() - lines = p.stderr.readlines() - if lines: - lines = self._preprocess_lines(*lines) - self._log_stderr(*lines) - all_stderr += lines - - lines = p.stdout.readlines() - if lines: - lines = self._preprocess_lines(*lines) - self._log_stdout(*lines) - all_stdout += lines + all_stderr += process_stderr(p.stderr.readlines()) + all_stdout += process_stdout(p.stdout.readlines()) return p.returncode, all_stdout, all_stderr From 174ffdf06f012b6fb59b8decebc91d5fea7debf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 15 Nov 2016 17:26:41 +0100 Subject: [PATCH 19/72] Simplified a line --- src/octoprint/plugins/softwareupdate/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index e2b84192e..4098366ae 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -882,7 +882,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._send_client_message("loglines", data=dict(loglines=[dict(line=line, stream=stream) for line in lines])) for line in lines: - self._console_logger.debug(u"{prefix} {line}".format(**locals())) + self._console_logger.debug(u"{} {}".format(prefix, line)) def _send_client_message(self, message_type, data=None): self._plugin_manager.send_plugin_message(self._identifier, dict(type=message_type, data=data)) From c194cabdcf504a190dd2c9c345da67aeef35d1f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 16 Nov 2016 14:12:00 +0100 Subject: [PATCH 20/72] Fix for select&print not working for SD files anymore Timing issue, "OctoPrint.job.start()" would be called at a time when the file had not yet been selected on the server. Hence a different approach, calculating printerAfterLoading parameter based on existing information at the time of clicking the load button and using the print parameter on the select file API again, as previously. --- src/octoprint/static/js/app/viewmodels/files.js | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index b00d75f9c..03ec14734 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -402,13 +402,10 @@ $(function() { if (!file) { return; } - OctoPrint.files.select(file.origin, file.path) - .done(function() { - var withinPrintDimensions = self.evaluatePrintDimensions(file, true); - if (withinPrintDimensions && printAfterLoad) { - OctoPrint.job.start(); - } - }); + var withinPrintDimensions = self.evaluatePrintDimensions(file, true); + var print = printAfterLoad && withinPrintDimensions; + + OctoPrint.files.select(file.origin, file.path, print); }; self.removeFile = function(file, event) { From 83a08cd927ec85fef8db145a70e0495f5ae52693 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 16 Nov 2016 14:12:37 +0100 Subject: [PATCH 21/72] Fix a small issue with estimator output when no file is selected --- src/octoprint/printer/standard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index fe7ed97a2..c693b0cde 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -763,7 +763,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): """ if progress is None or printTime is None or cleanedPrintTime is None: - return None + return None, None dumbTotalPrintTime = printTime / progress estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime) From a58b167bed63501d32b22db5ab1c0563aa462287 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 16 Nov 2016 15:37:49 +0100 Subject: [PATCH 22/72] Utilize settings chain maps for plugin default settings too --- src/octoprint/plugin/__init__.py | 22 +++++++++++----------- src/octoprint/server/__init__.py | 12 ++++++++++-- src/octoprint/settings.py | 8 ++++++-- 3 files changed, 27 insertions(+), 15 deletions(-) diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index a8736c4c8..bab1350a0 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -145,7 +145,7 @@ def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_prepr Arguments: plugin_key (string): The plugin identifier for which to create the settings instance. - defaults (dict): The default settings for the plugin. + defaults (dict): The default settings for the plugin, if different from get_settings_defaults. get_preprocessors (dict): The getter preprocessors for the plugin. set_preprocessors (dict): The setter preprocessors for the plugin. settings (octoprint.settings.Settings): The settings instance to use. @@ -180,13 +180,12 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): return None try: - defaults = instance.get_settings_defaults() get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() except: - logging.getLogger(__name__).exception("Error while retrieving defaults or preprocessors for plugin {}".format(plugin_key)) + logging.getLogger(__name__).exception("Error while retrieving preprocessors for plugin {}".format(plugin_key)) return None - return plugin_settings(plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings) + return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings) def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None): @@ -315,11 +314,12 @@ class PluginSettings(object): self.settings = settings self.plugin_key = plugin_key - if defaults is None: - defaults = dict() - self.defaults = dict(plugins=dict()) - self.defaults["plugins"][plugin_key] = defaults - self.defaults["plugins"][plugin_key]["_config_version"] = None + if defaults is not None: + self.defaults = dict(plugins=dict()) + self.defaults["plugins"][plugin_key] = defaults + self.defaults["plugins"][plugin_key]["_config_version"] = None + else: + self.defaults = None if get_preprocessors is None: get_preprocessors = dict() @@ -345,14 +345,14 @@ class PluginSettings(object): return result def add_getter_kwargs(kwargs): - if not "defaults" in kwargs: + if not "defaults" in kwargs and self.defaults is not None: kwargs.update(defaults=self.defaults) if not "preprocessors" in kwargs: kwargs.update(preprocessors=self.get_preprocessors) return kwargs def add_setter_kwargs(kwargs): - if not "defaults" in kwargs: + if not "defaults" in kwargs and self.defaults is not None: kwargs.update(defaults=self.defaults) if not "preprocessors" in kwargs: kwargs.update(preprocessors=self.set_preprocessors) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index b90ab21eb..140099658 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -245,7 +245,14 @@ class Server(object): return props def settings_plugin_inject_factory(name, implementation): - """Factory for additional injections depending on plugin type""" + """Factory for additional injections/initializations depending on plugin type""" + if not isinstance(implementation, octoprint.plugin.SettingsPlugin): + return + + default_settings_overlay = dict(plugins=dict()) + default_settings_overlay["plugins"][name] = implementation.get_settings_defaults() + self._settings.add_overlay(default_settings_overlay, at_end=True) + plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin(name, implementation) if plugin_settings is None: return @@ -272,7 +279,8 @@ class Server(object): implementation.on_settings_initialized() - pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory, settings_plugin_inject_factory] + pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory, + settings_plugin_inject_factory] pluginManager.initialize_implementations() settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 23f030668..d5f8dd2e9 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -829,8 +829,12 @@ class Settings(object): self._migrate_config(config) return config - def add_overlay(self, overlay): - self._map.maps.insert(1, overlay) + def add_overlay(self, overlay, at_end=False): + if at_end: + pos = len(self._map.maps) - 1 + self._map.maps.insert(pos, overlay) + else: + self._map.maps.insert(1, overlay) def _migrate_config(self, config=None): if config is None: From f688786fd55eb2897b333510e32caaab4cd9d0e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 16 Nov 2016 15:38:13 +0100 Subject: [PATCH 23/72] Make cache validation for settings API depend on effective config --- src/octoprint/server/api/settings.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index b4d862aeb..8ccc0e127 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -40,6 +40,7 @@ def _etag(lm=None): import hashlib hash = hashlib.sha1() hash.update(str(lm)) + hash.update(repr(settings().effective)) hash.update(repr(connection_options)) hash.update(repr(plugins)) hash.update(repr(roles)) From 1a5f4e0b9fb89bc4ad60531ffc744cd726608eb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 16 Nov 2016 16:04:43 +0100 Subject: [PATCH 24/72] Stop focusing files in list after deleted file Looks weird, especially with the new yellow highlight. --- .../static/js/app/viewmodels/files.js | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 03ec14734..24695b2dd 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -441,20 +441,6 @@ $(function() { }; self._removeEntry = function(entry, event) { - var index = self.listHelper.paginatedItems().indexOf(entry) + 1; - if (index >= self.listHelper.paginatedItems().length) { - index = index - 2; - } - if (index < 0) { - index = 0; - } - - var focus = undefined; - var fileToFocus = self.listHelper.paginatedItems()[index]; - if (fileToFocus) { - focus = {location: fileToFocus.origin, path: fileToFocus.path}; - } - self.activeRemovals.push(entry.origin + ":" + entry.path); var finishActiveRemoval = function() { self.activeRemovals(_.filter(self.activeRemovals(), function(e) { @@ -485,10 +471,7 @@ $(function() { var deferred = $.Deferred(); OctoPrint.files.delete(entry.origin, entry.path) .done(function() { - self.requestData({ - focus: focus, - switchToPath: (entry.parent ? entry.parent.path : "") - }) + self.requestData() .done(function() { deferred.resolve(); }) From 0ad057cdbbe7c93f0980378ee3d02823f2c27aba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 16 Nov 2016 16:09:42 +0100 Subject: [PATCH 25/72] Fix PrintFailed event Was missing the new fields in the payload --- src/octoprint/printer/standard.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index c693b0cde..684969307 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -487,12 +487,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): # mark print as failure if self._selectedFile is not None: self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"]) - payload = { - "file": self._selectedFile["filename"], - "origin": FileDestinations.LOCAL - } - if self._selectedFile["sd"]: - payload["origin"] = FileDestinations.SDCARD + payload = self._payload_for_print_job_event() eventManager().fire(Events.PRINT_FAILED, payload) def get_state_string(self, state=None): From b87348be3b799f2fdbb873cb84278a4ec0d30f49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2016 12:13:52 +0100 Subject: [PATCH 26/72] Add support for M115 to virtual printer --- src/octoprint/plugins/virtual_printer/virtual.py | 6 ++++++ src/octoprint/settings.py | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 17517455b..3eb02e0d2 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -94,6 +94,8 @@ class VirtualPrinter(object): self._brokenM29 = settings().getBoolean(["devel", "virtualPrinter", "brokenM29"]) + self._firmwareName = settings().get(["devel", "virtualPrinter", "firmwareName"]) + self.currentLine = 0 self.lastN = 0 @@ -380,6 +382,10 @@ class VirtualPrinter(object): self._send(output) return True + def _gcode_M115(self, data): + output = "FIRMWARE_NAME:{} PROTOCOL_VERSION:1.0".format(self._firmwareName) + self._send(output) + def _gcode_M117(self, data): # we'll just use this to echo a message, to allow playing around with pause triggers if self._echoOnM117: diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index d5f8dd2e9..20cb42b39 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -348,7 +348,8 @@ default_settings = { "supportM112": True, "echoOnM117": True, "brokenM29": True, - "supportF": False + "supportF": False, + "firmwareName": "Virtual Marlin 1.0" } } } From d5a73b8b4f8fba47ea8ab9f79c725231d1cc6f22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2016 12:14:10 +0100 Subject: [PATCH 27/72] Add chunks util function --- src/octoprint/util/__init__.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 3252b25ba..a736e35e6 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -442,6 +442,16 @@ def to_unicode(s_or_u, encoding="utf-8", errors="strict"): return s_or_u +def chunks(l, n): + """ + Yield successive n-sized chunks from l. + + Taken from http://stackoverflow.com/a/312464/2028598 + """ + for i in range(0, len(l), n): + yield l[i:i+n] + + def is_running_from_source(): root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../..")) return os.path.isdir(os.path.join(root, "src")) and os.path.isfile(os.path.join(root, "setup.py")) From ec12e52865298a4be9400e4a485cc0ed84ca698d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2016 14:46:56 +0100 Subject: [PATCH 28/72] virtual printer: small fix of temperature responses --- src/octoprint/plugins/virtual_printer/virtual.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 3eb02e0d2..afd4179ab 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -645,9 +645,9 @@ class VirtualPrinter(object): if settings().getBoolean(["devel", "virtualPrinter", "includeCurrentToolInTemps"]): if includeTarget: - output = "T:%.2f /%.2f %s @:64\n" % (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder] + 1, allTempsString) + output = "T:%.2f /%.2f %s" % (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder] + 1, allTempsString) else: - output = "T:%.2f %s @:64\n" % (self.temp[self.currentExtruder], allTempsString) + output = "T:%.2f %s" % (self.temp[self.currentExtruder], allTempsString) else: output = allTempsString else: From 07382d39182ae7f1b9c27695bb4d0ed5f65d1e6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2016 17:13:36 +0100 Subject: [PATCH 29/72] Add (optional) firmware auto detection If enabled (which it is by default), OctoPrint will now send an M115 to the printer on initial connection in order to try to figure out what kind of firmware it is. For FIRMWARE_NAME values containing "repetier" (case insensitive), all Repetier- specific flags will be set on the comm layer. For FIRMWARE_NAME values containing "reprapfirmware", all RepRapFirmware- specific flags will be set on the comm layer. For now no other handling will be performed. --- src/octoprint/printer/standard.py | 2 +- src/octoprint/server/api/settings.py | 4 +- src/octoprint/settings.py | 3 +- .../static/js/app/viewmodels/settings.js | 1 + .../dialogs/settings/features.jinja2 | 88 +++++++++++-------- src/octoprint/util/comm.py | 70 ++++++++++++++- 6 files changed, 124 insertions(+), 44 deletions(-) diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 684969307..1d8ebd1fd 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -393,7 +393,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._printAfterSelect = printAfterSelect self._posAfterSelect = pos - self._comm.selectFile("/" + path if sd and not settings().getBoolean(["feature", "sdRelativePath"]) else path, sd) + self._comm.selectFile("/" + path if sd else path, sd) self._setProgressData(completion=0) self._setCurrentZ(None) diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 8ccc0e127..339a77a2c 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -104,7 +104,8 @@ def getSettings(): "keyboardControl": s.getBoolean(["feature", "keyboardControl"]), "pollWatched": s.getBoolean(["feature", "pollWatched"]), "ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"]), - "modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]) + "modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]), + "firmwareDetection": s.getBoolean(["feature", "firmwareDetection"]) }, "serial": { "port": connectionOptions["portPreference"], @@ -274,6 +275,7 @@ def _saveSettings(data): if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"]) if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"]) if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"]) + if "firmwareDetection" in data["feature"]: s.setBoolean(["feature", "firmwareDetection"], data["feature"]["firmwareDetection"]) if "serial" in data.keys(): if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"]) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 20cb42b39..fdface850 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -197,7 +197,8 @@ default_settings = { "ignoreIdenticalResends": False, "identicalResendsCountdown": 7, "supportFAsCommand": False, - "modelSizeDetection": True + "modelSizeDetection": True, + "firmwareDetection": True }, "folder": { "uploads": None, diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 96381f309..12e4703ca 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -133,6 +133,7 @@ $(function() { self.feature_pollWatched = ko.observable(undefined); self.feature_ignoreIdenticalResends = ko.observable(undefined); self.feature_modelSizeDetection = ko.observable(undefined); + self.feature_firmwareDetection = ko.observable(undefined); self.serial_port = ko.observable(); self.serial_baudrate = ko.observable(); diff --git a/src/octoprint/templates/dialogs/settings/features.jinja2 b/src/octoprint/templates/dialogs/settings/features.jinja2 index ab7a88430..3d146167b 100644 --- a/src/octoprint/templates/dialogs/settings/features.jinja2 +++ b/src/octoprint/templates/dialogs/settings/features.jinja2 @@ -34,53 +34,67 @@
+
-
-
- +
+
+
+ +
-
-
-
- +
+
+ +
-
-
-
- +
+
+ +
-
-
-
- +
+
+ +
-
-
- -
- - - +
+
+ +
+
+
+ +
+ + + +
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index d4e43ee64..5d111e744 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -28,7 +28,7 @@ from octoprint.events import eventManager, Events from octoprint.filemanager import valid_file_type from octoprint.filemanager.destinations import FileDestinations from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \ - to_unicode, bom_aware_open, TypedQueue, TypeAlreadyInQueue + to_unicode, bom_aware_open, TypedQueue, TypeAlreadyInQueue, chunks try: import _winreg @@ -124,6 +124,9 @@ Groups will be as follows: * ``e``: E coordinate """ +regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):") +"""Regex to use for splitting M115 responses.""" + def serialList(): baselist=[] if os.name=="nt": @@ -310,6 +313,8 @@ class MachineCom(object): self._neverSendChecksum = settings().getBoolean(["feature", "neverSendChecksum"]) self._sendChecksumWithUnknownCommands = settings().getBoolean(["feature", "sendChecksumWithUnknownCommands"]) self._unknownCommandsNeedAck = settings().getBoolean(["feature", "unknownCommandsNeedAck"]) + self._sdAlwaysAvailable = settings().getBoolean(["feature", "sdAlwaysAvailable"]) + self._sdRelativePath = settings().getBoolean(["feature", "sdRelativePath"]) self._currentLine = 1 self._line_mutex = threading.RLock() self._resendDelta = None @@ -319,7 +324,9 @@ class MachineCom(object): self._currentResendCount = 0 self._resendSwallowRepetitions = settings().getBoolean(["feature", "ignoreIdenticalResends"]) self._resendSwallowRepetitionsCounter = 0 - self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"]) + + self._firmwareDetection = settings().getBoolean(["feature", "firmwareDetection"]) + self._firmwareInfoReceived = not self._firmwareDetection self._supportResendsWithoutOk = settings().getBoolean(["serial", "supportResendsWithoutOk"]) @@ -795,6 +802,10 @@ class MachineCom(object): if not self.isOperational(): # printer is not connected, can't use SD return + + if filename.startswith("/") and self._sdRelativePath: + filename = filename[1:] + self._sdFileToSelect = filename self.sendCommand("M23 %s" % filename) else: @@ -920,7 +931,7 @@ class MachineCom(object): return self.sendCommand("M21") - if settings().getBoolean(["feature", "sdAlwaysAvailable"]): + if self._sdAlwaysAvailable: self._sdAvailable = True self.refreshSdFiles() self._callback.on_comm_sd_state_change(self._sdAvailable) @@ -1207,6 +1218,33 @@ class MachineCom(object): except ValueError: pass + ##~~ firmware name & version + elif "FIRMWARE_NAME:" in line: + # looks like a response to M115 + data = parse_firmware_line(line) + firmware_name = data.get("FIRMWARE_NAME") + self._logger.info("Printer reports firmware name \"{}\"".format(firmware_name)) + + if not self._firmwareInfoReceived and firmware_name: + if "repetier" in firmware_name.lower(): + self._logger.info("Detected Repetier firmware, enabling relevant features for issue free communication") + + self._alwaysSendChecksum = True + self._resendSwallowRepetitions = True + supportRepetierTargetTemp = True + disable_external_heatup_detection = True + + sd_always_available = self._sdAlwaysAvailable + self._sdAlwaysAvailable = True + if not sd_always_available and not self._sdAvailable: + self.initSdCard() + + elif "reprapfirmware" in firmware_name.lower(): + self._logger.info("Detected RepRapFirmware, enabling relevant features for issue free communication") + self._sdRelativePath = True + + self._firmwareInfoReceived = True + ##~~ SD Card handling elif 'SD init fail' in line or 'volume.init failed' in line or 'openRoot failed' in line: self._sdAvailable = False @@ -1528,6 +1566,8 @@ class MachineCom(object): self._changeState(self.STATE_OPERATIONAL) self.resetLineNumbers() + if self._firmwareDetection: + self.sendCommand("M115") if self._sdAvailable: self.refreshSdFiles() @@ -2012,7 +2052,9 @@ class MachineCom(object): # now comes the part where we increase line numbers and send stuff - no turning back now command_requiring_checksum = gcode is not None and gcode in self._checksum_requiring_commands command_allowing_checksum = gcode is not None or self._sendChecksumWithUnknownCommands - checksum_enabled = self.isPrinting() or self._alwaysSendChecksum + checksum_enabled = not self._neverSendChecksum and (self.isPrinting() or + self._alwaysSendChecksum or + not self._firmwareInfoReceived) command_to_send = command.encode("ascii", errors="replace") if command_requiring_checksum or (command_allowing_checksum and checksum_enabled): @@ -2916,6 +2958,26 @@ def parse_temperature_line(line, current): return max(maxToolNum, current), canonicalize_temperatures(result, current) +def parse_firmware_line(line): + """ + Parses the provided firmware info line. + + The result will be a dictionary mapping from the contained keys to the contained + values. + + Arguments: + line (str): the line to parse + + Returns: + dict: a dictionary with the parsed data + """ + + result = dict() + split_line = regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string + for key, value in chunks(split_line, 2): + result[key] = value + return result + def gcode_command_for_cmd(cmd): """ Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0"). From f1a1b851ee55ef50e7d5ed2bc86c37f151984131 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2016 17:15:28 +0100 Subject: [PATCH 30/72] Better resilience against exceptions in view models in callViewModels --- src/octoprint/static/js/app/helpers.js | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index dae6d8fd1..81c3b9c94 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -832,17 +832,21 @@ function callViewModelsIf(allViewModels, method, condition, callback) { _.each(allViewModels, function(viewModel) { if (viewModel.hasOwnProperty(method) && condition(viewModel, method)) { - if (callback == undefined) { - if (parameters != undefined) { - // call the method with the provided parameters - viewModel[method].apply(viewModel, parameters); + try { + if (callback == undefined) { + if (parameters != undefined) { + // call the method with the provided parameters + viewModel[method].apply(viewModel, parameters); + } else { + // call the method without parameters + viewModel[method](); + } } else { - // call the method without parameters - viewModel[method](); + // provide the method to the callback + callback(viewModel[method], viewModel); } - } else { - // provide the method to the callback - callback(viewModel[method], viewModel); + } catch (exc) { + log.error("Error calling", method, "on view model", viewModel.constructor.name, ":", (exc.stack || exc)); } } }); From d1cb8ca98ad56109b6086090d48f03db7f8be0bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2016 17:30:10 +0100 Subject: [PATCH 31/72] Fix premature parse stop on M114 and M115 response with ok-prefix --- src/octoprint/util/comm.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 5d111e744..b4cc9c0f4 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -1133,7 +1133,9 @@ class MachineCom(object): # ok only considered handled if it's alone on the line, might be # a response to an M105 or an M114 self._handle_ok() - handled = (line == "wait" or line == "ok" or not ("T:" in line or "T0:" in line or "B:" in line or "C:" in line)) + needs_further_handling = "T:" in line or "T0:" in line or "B:" in line or "C:" in line or \ + "X:" in line or "FIRMWARE_NAME:" in line + handled = (line == "wait" or line == "ok" or not needs_further_handling) # process resends elif lower_line.startswith("resend") or lower_line.startswith("rs"): From 1a75dcd5ee52f381fae43e7e9d1446df688aa6ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 18 Nov 2016 07:50:53 +0100 Subject: [PATCH 32/72] Allow locale definition via request header Important for session less API calls that might return localized content (e.g. the system commands). See #1593 --- src/octoprint/cli/config.py | 0 src/octoprint/server/__init__.py | 3 +++ 2 files changed, 3 insertions(+) create mode 100644 src/octoprint/cli/config.py diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py new file mode 100644 index 000000000..e69de29bb diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 140099658..f7b63ec6a 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -575,6 +575,9 @@ class Server(object): if "l10n" in request.values: return Locale.negotiate([request.values["l10n"]], LANGUAGES) + if "X-Locale" in request.headers: + return Locale.negotiate([request.headers["X-Locale"]], LANGUAGES) + if hasattr(g, "identity") and g.identity and userManager.enabled: userid = g.identity.id try: From 0d13c3b439b9ae9fa8b3226d302871681c4a1541 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 18 Nov 2016 07:54:17 +0100 Subject: [PATCH 33/72] Add OctoPrint.options.locale and if set send X-Locale header on requests See #1593 --- docs/jsclientlib/base.rst | 4 ++++ src/octoprint/static/js/app/client/base.js | 7 ++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/jsclientlib/base.rst b/docs/jsclientlib/base.rst index e59cca695..65a56340c 100644 --- a/docs/jsclientlib/base.rst +++ b/docs/jsclientlib/base.rst @@ -14,6 +14,10 @@ ``OctoPrint.options.baseurl`` The base URL of the OctoPrint API + ``OctoPrint.options.locale`` + The locale to set in ``X-Locale`` headers on API requests. Useful for API + endpoints that might return localized content. + .. js:data:: OctoPrint.plugins Registration of client library components provided by plugins. diff --git a/src/octoprint/static/js/app/client/base.js b/src/octoprint/static/js/app/client/base.js index eb159d0a4..c0ea5292a 100644 --- a/src/octoprint/static/js/app/client/base.js +++ b/src/octoprint/static/js/app/client/base.js @@ -46,7 +46,8 @@ OctoPrint.options = { "baseurl": undefined, - "apikey": undefined + "apikey": undefined, + "locale": undefined }; OctoPrint.plugins = {}; @@ -65,6 +66,10 @@ var headers = $.extend({}, additional); headers["X-Api-Key"] = OctoPrint.options.apikey; + if (OctoPrint.options.locale !== undefined) { + headers["X-Locale"] = OctoPrint.options.locale; + } + return headers; }; From b68ee4df98c41c358c0a15050219f2af7840cfa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 18 Nov 2016 07:55:16 +0100 Subject: [PATCH 34/72] If l10n is set on page load, set OctoPrint.options.locale to its value That way API requests will be made with the locale the page was requested in. See #1593 --- src/octoprint/static/js/app/helpers.js | 13 +++++++++++++ src/octoprint/static/js/app/main.js | 5 +++++ 2 files changed, 18 insertions(+) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 81c3b9c94..ef4a4d6ff 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -865,3 +865,16 @@ var sizeObservable = function(observable) { } }) }; + +var getQueryParameterByName = function(name, url) { + // from http://stackoverflow.com/a/901144/2028598 + if (!url) { + url = window.location.href; + } + name = name.replace(/[\[\]]/g, "\\$&"); + var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), + results = regex.exec(url); + if (!results) return null; + if (!results[2]) return ''; + return decodeURIComponent(results[2].replace(/\+/g, " ")); +}; diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index a870ecc75..127643b54 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -13,6 +13,11 @@ $(function() { OctoPrint.options.baseurl = BASEURL; OctoPrint.options.apikey = UI_API_KEY; + var l10n = getQueryParameterByName("l10n"); + if (l10n) { + OctoPrint.options.locale = l10n; + } + OctoPrint.socket.onMessage("connected", function(data) { var payload = data.data; OctoPrint.options.apikey = payload.apikey; From e4d34f4130c5e604f31706be3f18adfe76eb9012 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 18 Nov 2016 10:25:24 +0100 Subject: [PATCH 35/72] Fix logging during settings initialization We record the messages logged during that time to a recording log handler, then playback anything we caught after startup. --- src/octoprint/__init__.py | 59 +++++++++++++++++++++++++++---- src/octoprint/cli/server.py | 15 ++++++-- src/octoprint/logging/handlers.py | 53 +++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 8 deletions(-) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 389fd2245..b27e14b26 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -18,10 +18,6 @@ __revision__ = versions.get('full-revisionid', versions.get('full', None)) del versions del get_versions -#~~ sane logging defaults - -log.basicConfig() - #~~ try to ensure a sound SSL environment urllib3_ssl = True @@ -61,7 +57,13 @@ class FatalStartupError(BaseException): def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, logging_config=None, debug=False, verbosity=0, uncaught_logger=None, - uncaught_handler=None, after_settings=None, after_logging=None): + uncaught_handler=None, after_preinit_logging=None, + after_settings=None, after_logging=None): + logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler) + + if callable(after_preinit_logging): + after_preinit_logging(logger, recorder) + settings = init_settings(basedir, configfile) if callable(after_settings): after_settings(settings) @@ -74,8 +76,9 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, verbosity=verbosity, uncaught_logger=uncaught_logger, uncaught_handler=uncaught_handler) + if callable(after_logging): - after_logging(logger) + after_logging(logger, recorder) plugin_manager = init_pluginsystem(settings) return settings, logger, plugin_manager @@ -94,6 +97,45 @@ def init_settings(basedir, configfile): raise FatalStartupError(message) +def preinit_logging(debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None): + config = { + "version": 1, + "formatters": { + "simple": { + "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + } + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "level": "DEBUG", + "formatter": "simple", + "stream": "ext://sys.stdout" + } + }, + "loggers": { + "octoprint": { + "level": "DEBUG" if debug else "INFO" + }, + "octoprint.util": { + "level": "INFO" + } + }, + "root": { + "level": "WARN", + "handlers": ["console"] + } + } + + logger = set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler) + + from octoprint.logging.handlers import RecordingLogHandler + recorder = RecordingLogHandler(level=log.DEBUG) + log.getLogger().addHandler(recorder) + + return logger, recorder + + def init_logging(settings, use_logging_file=True, logging_file=None, default_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None): """Sets up logging.""" @@ -182,6 +224,11 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con else: config = default_config + # configure logging globally + return set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler) + + +def set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler): # configure logging globally import logging.config as logconfig logconfig.dictConfig(config) diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 3fb45f2c9..0b187bd68 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -16,8 +16,19 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi from octoprint import init_platform, __display_version__, FatalStartupError - def log_startup(_): - logging.getLogger("octoprint.server").info("Starting OctoPrint {}".format(__display_version__)) + def log_startup(_, recorder): + logger = logging.getLogger("octoprint.server") + logger.info("Starting OctoPrint {}".format(__display_version__)) + + if recorder and len(recorder): + logger.info("--- Logged during platform initialization: ---") + + from octoprint.logging.handlers import CombinedLogHandler + handler = CombinedLogHandler(*logging.getLogger().handlers) + recorder.setTarget(handler) + recorder.flush() + + logger.info("----------------------------------------------") from octoprint import urllib3_ssl if not urllib3_ssl: diff --git a/src/octoprint/logging/handlers.py b/src/octoprint/logging/handlers.py index fb6134293..fc2d5e430 100644 --- a/src/octoprint/logging/handlers.py +++ b/src/octoprint/logging/handlers.py @@ -81,3 +81,56 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler): self.cleanupFiles() if not self.delay: self.stream = self._open() + +class RecordingLogHandler(logging.Handler): + def __init__(self, target=None, level=logging.NOTSET): + logging.Handler.__init__(self, level=level) + self._buffer = [] + self._target = target + + def emit(self, record): + self._buffer.append(record) + + def setTarget(self, target): + self._target = target + + def flush(self): + if not self._target: + return + + self.acquire() + try: + for record in self._buffer: + self._target.handle(record) + self._buffer = [] + finally: + self.release() + + def close(self): + self.flush() + self.acquire() + try: + self._buffer = [] + finally: + self.release() + + def __len__(self): + return len(self._buffer) + + +class CombinedLogHandler(logging.Handler): + def __init__(self, *handlers): + logging.Handler.__init__(self) + self._handlers = handlers + + def setHandlers(self, *handlers): + self._handlers = handlers + + def handle(self, record): + self.acquire() + try: + if self._handlers: + for handler in self._handlers: + handler.handle(record) + finally: + self.release() From 97bf33130789bc443f91579b6f2dcdf8d91f0fb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 18 Nov 2016 13:01:14 +0100 Subject: [PATCH 36/72] Add safe mode that disables all third party plugins Can be enabled either through new --safe command line parameter or through server.startOnceInSafeMode in config.yaml When running in safe mode the plugin manager will only allow to disable or uninstall third party plugins. Enabling third party plugins or installing new plugins is disabled. That will hopefully allow for more straightforward recovery in case of a misbehaving plugin. --- src/octoprint/__init__.py | 59 +++++++++++++++---- src/octoprint/cli/__init__.py | 5 +- src/octoprint/cli/plugins.py | 2 +- src/octoprint/cli/server.py | 36 ++++++----- src/octoprint/plugin/__init__.py | 32 ++++------ src/octoprint/plugin/core.py | 19 +++++- .../plugins/pluginmanager/__init__.py | 23 +++++--- .../pluginmanager/static/js/pluginmanager.js | 28 +++++++-- .../templates/pluginmanager_settings.jinja2 | 11 +++- src/octoprint/server/__init__.py | 11 +++- src/octoprint/server/util/sockjs.py | 4 +- src/octoprint/settings.py | 1 + src/octoprint/static/js/app/dataupdater.js | 15 +++++ 13 files changed, 179 insertions(+), 67 deletions(-) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index b27e14b26..ebf1ffbd8 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -57,16 +57,21 @@ class FatalStartupError(BaseException): def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, logging_config=None, debug=False, verbosity=0, uncaught_logger=None, - uncaught_handler=None, after_preinit_logging=None, - after_settings=None, after_logging=None): + uncaught_handler=None, safe_mode=False, after_preinit_logging=None, + after_settings=None, after_logging=None, after_safe_mode=None): + kwargs = dict() + logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler) + kwargs["logger"] = logger + kwargs["recorder"] = recorder if callable(after_preinit_logging): - after_preinit_logging(logger, recorder) + after_preinit_logging(**kwargs) settings = init_settings(basedir, configfile) + kwargs["settings"] = settings if callable(after_settings): - after_settings(settings) + after_settings(**kwargs) logger = init_logging(settings, use_logging_file=use_logging_file, @@ -76,12 +81,20 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, verbosity=verbosity, uncaught_logger=uncaught_logger, uncaught_handler=uncaught_handler) + kwargs["logger"] = logger if callable(after_logging): - after_logging(logger, recorder) + after_logging(**kwargs) - plugin_manager = init_pluginsystem(settings) - return settings, logger, plugin_manager + settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"]) + safe_mode = safe_mode or settings_safe_mode + kwargs["safe_mode"] = safe_mode + + if callable(after_safe_mode): + after_safe_mode(**kwargs) + + plugin_manager = init_pluginsystem(settings, safe_mode=safe_mode) + return settings, logger, safe_mode, plugin_manager def init_settings(basedir, configfile): @@ -254,19 +267,45 @@ def set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handl if uncaught_handler is None: def exception_logger(exc_type, exc_value, exc_tb): logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb)) + uncaught_handler = exception_logger sys.excepthook = uncaught_handler return logger -def init_pluginsystem(settings): +def init_pluginsystem(settings, safe_mode=False): """Initializes the plugin manager based on the settings.""" - from octoprint.plugin import plugin_manager - pm = plugin_manager(init=True, settings=settings) + import os logger = log.getLogger(__name__) + + plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True), + settings.getBaseFolder("plugins")] + plugin_entry_points = ["octoprint.plugin"] + plugin_disabled_list = settings.get(["plugins", "_disabled"]) + + plugin_validators = [] + if safe_mode: + def validator(phase, plugin_info): + if phase == "after_load": + setattr(plugin_info, "safe_mode_victim", not plugin_info.bundled) + setattr(plugin_info, "safe_mode_enabled", False) + elif phase == "before_enable": + if not plugin_info.bundled: + setattr(plugin_info, "safe_mode_enabled", True) + return False + return True + plugin_validators.append(validator) + + from octoprint.plugin import plugin_manager + pm = plugin_manager(init=True, + plugin_folders=plugin_folders, + plugin_entry_points=plugin_entry_points, + plugin_disabled_list=plugin_disabled_list, + plugin_validators=plugin_validators) + settings_overlays = dict() disabled_from_overlays = dict() diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 43923eff9..635ffc792 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -13,10 +13,11 @@ import octoprint class OctoPrintContext(object): """Custom context wrapping the standard options.""" - def __init__(self, configfile=None, basedir=None, verbosity=0): + def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False): self.configfile = configfile self.basedir = basedir self.verbosity = verbosity + self.safe_mode = safe_mode pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True) """Decorator to pass in the :class:`OctoPrintContext` instance.""" @@ -95,6 +96,8 @@ def standard_options(hidden=False): help="Specify the config file to use."), factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, help="Increase logging verbosity"), + factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, + help="Enable safe mode; disables all third party plugins") ] return bulk_options(options) diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index e28c3ee65..44d60952b 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -51,7 +51,7 @@ class OctoPrintPluginCommands(click.MultiCommand): from octoprint import init_settings, init_pluginsystem, FatalStartupError try: self.settings = init_settings(ctx.obj.basedir, ctx.obj.configfile) - self.plugin_manager = init_pluginsystem(self.settings) + self.plugin_manager = init_pluginsystem(self.settings, safe_mode=ctx.obj.safe_mode) except FatalStartupError as e: click.echo(e.message, err=True) click.echo("There was a fatal error initializing the settings or the plugin system.", err=True) diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 0b187bd68..2ea6fc4b0 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -11,14 +11,16 @@ import sys from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options -def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, octoprint_daemon = None): +def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode, octoprint_daemon=None): """Initializes the environment and starts up the server.""" from octoprint import init_platform, __display_version__, FatalStartupError - def log_startup(_, recorder): + def log_startup(recorder=None, safe_mode=None, **kwargs): logger = logging.getLogger("octoprint.server") logger.info("Starting OctoPrint {}".format(__display_version__)) + if safe_mode: + logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") if recorder and len(recorder): logger.info("--- Logged during platform initialization: ---") @@ -41,13 +43,14 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi "https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl") try: - settings, _, plugin_manager = init_platform(basedir, - configfile, - logging_file=logging_config, - debug=debug, - verbosity=verbosity, - uncaught_logger=__name__, - after_logging=log_startup) + settings, _, safe_mode, plugin_manager = init_platform(basedir, + configfile, + logging_file=logging_config, + debug=debug, + verbosity=verbosity, + uncaught_logger=__name__, + safe_mode=safe_mode, + after_safe_mode=log_startup) except FatalStartupError as e: click.echo(e.message, err=True) click.echo("There was a fatal error starting up OctoPrint.", err=True) @@ -58,6 +61,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi host=host, port=port, debug=debug, + safe_mode=safe_mode, allow_root=allow_root, octoprint_daemon=octoprint_daemon) octoprint_server.run() @@ -73,7 +77,7 @@ server_options = bulk_options([ help="Specify the config file to use for configuring logging."), click.option("--iknowwhatimdoing", "allow_root", is_flag=True, help="Allow OctoPrint to run as user root."), - click.option("--debug", is_flag=True, help="Enable debug mode"), + click.option("--debug", is_flag=True, help="Enable debug mode.") ]) """Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``--logging``, ``--iknowwhatimdoing`` and ``--debug``.""" @@ -93,7 +97,7 @@ def server_commands(obj): def serve_command(obj, host, port, logging, allow_root, debug): """Starts the OctoPrint server.""" run_server(obj.basedir, obj.configfile, host, port, debug, - allow_root, logging, obj.verbosity) + allow_root, logging, obj.verbosity, obj.safe_mode) @server_commands.command(name="daemon") @@ -122,7 +126,7 @@ def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, c from octoprint.daemon import Daemon class OctoPrintDaemon(Daemon): - def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity): + def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode): Daemon.__init__(self, pidfile) self._basedir = basedir @@ -133,12 +137,16 @@ def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, c self._allow_root = allow_root self._logging_config = logging_config self._verbosity = verbosity + self._safe_mode = safe_mode def run(self): - run_server(self._basedir, self._configfile, self._host, self._port, self._debug, self._allow_root, self._logging_config, self._verbosity, self) + run_server(self._basedir, self._configfile, self._host, self._port, self._debug, + self._allow_root, self._logging_config, self._verbosity, self._safe_mode, + octoprint_daemon=self) octoprint_daemon = OctoPrintDaemon(pid, octoprint_ctx.basedir, octoprint_ctx.configfile, - host, port, debug, allow_root, logging, octoprint_ctx.verbosity) + host, port, debug, allow_root, logging, octoprint_ctx.verbosity, + octoprint_ctx.safe_mode) if command == "start": octoprint_daemon.start() diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index bab1350a0..31367e542 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -42,9 +42,10 @@ def _validate_plugin(phase, plugin_info): if not "octoprint.accesscontrol.appkey" in hooks: hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks) + return True def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None, - plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None, settings=None): + plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` singleton. @@ -87,14 +88,6 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en else: if init: - if settings is None: - settings = s() - - if plugin_folders is None: - plugin_folders = ( - settings.getBaseFolder("plugins"), - (os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")), True) - ) if plugin_types is None: plugin_types = [StartupPlugin, ShutdownPlugin, @@ -109,22 +102,17 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en ProgressPlugin, WizardPlugin, UiPlugin] - if plugin_entry_points is None: - plugin_entry_points = "octoprint.plugin" - if plugin_disabled_list is None: - plugin_disabled_list = settings.get(["plugins", "_disabled"]) + if plugin_restart_needing_hooks is None: - plugin_restart_needing_hooks = [ - "octoprint.server.http" - ] + plugin_restart_needing_hooks = ["octoprint.server.http"] + if plugin_obsolete_hooks is None: - plugin_obsolete_hooks = [ - "octoprint.comm.protocol.gcode" - ] + plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] + if plugin_validators is None: - plugin_validators = [ - _validate_plugin - ] + plugin_validators = [_validate_plugin] + else: + plugin_validators.append(_validate_plugin) _instance = PluginManager(plugin_folders, plugin_types, diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index c95f13266..61ba0ff7a 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -149,6 +149,8 @@ class PluginInfo(object): self._license = license def validate(self, phase, additional_validators=None): + result = True + if phase == "before_load": # if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__ if hasattr(self.instance, self.__class__.attr_init): @@ -183,7 +185,9 @@ class PluginInfo(object): if additional_validators is not None: for validator in additional_validators: - validator(phase, self) + result = result and validator(phase, self) + + return result def __str__(self): if self.version: @@ -448,6 +452,12 @@ class PluginManager(object): if logging_prefix is None: logging_prefix = "" + if plugin_folders is None: + plugin_folders = [] + if plugin_types is None: + plugin_types = [] + if plugin_entry_points is None: + plugin_entry_points = [] if plugin_disabled_list is None: plugin_disabled_list = [] @@ -740,7 +750,9 @@ class PluginManager(object): plugin = self.plugins[name] try: - plugin.validate("before_load", additional_validators=self.plugin_validators) + if not plugin.validate("before_load", additional_validators=self.plugin_validators): + return + plugin.load() plugin.validate("after_load", additional_validators=self.plugin_validators) self.on_plugin_loaded(name, plugin) @@ -802,6 +814,9 @@ class PluginManager(object): raise PluginCantEnable(name, "Dependency on obsolete hooks detected, full functionality cannot be guaranteed") try: + if not plugin.validate("before_enable", additional_validators=self.plugin_validators): + return False + plugin.enable() self._activate_plugin(name, plugin) except PluginLifecycleException as e: diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index e1f36c992..97dfc4560 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -180,6 +180,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if not admin_permission.can(): return make_response("Insufficient rights", 403) + from octoprint.server import safe_mode + refresh_repository = request.values.get("refresh_repository", "false") in valid_boolean_trues if refresh_repository: self._repository_available = self._refresh_repository() @@ -200,7 +202,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, virtual_env=self._pip_caller.virtual_env, additional_args=self._settings.get(["pip_args"]), python=sys.executable - )) + ), + safe_mode=safe_mode) def etag(): import hashlib @@ -208,6 +211,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, hash.update(repr(self._get_plugins())) hash.update(str(self._repository_available)) hash.update(repr(self._repository_plugins)) + hash.update(repr(safe_mode)) return hash.hexdigest() def condition(): @@ -450,7 +454,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable)) - needs_restart_api = needs_restart and not pending + safe_mode_victim = getattr(plugin, "safe_mode_victim", False) + needs_restart_api = (needs_restart or safe_mode_victim) and not pending needs_refresh_api = needs_refresh and not pending try: @@ -514,12 +519,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._settings.global_set(["plugins", "_disabled"], disabled_list) self._settings.save(force=True) - if not needs_restart: + if not needs_restart and not getattr(plugin, "safe_mode_victim", False): self._plugin_manager.enable_plugin(plugin.key) else: if plugin.key in self._pending_disable: self._pending_disable.remove(plugin.key) - elif not plugin.enabled and plugin.key not in self._pending_enable: + elif (not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_enable: self._pending_enable.add(plugin.key) def _mark_plugin_disabled(self, plugin, needs_restart=False): @@ -529,12 +534,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._settings.global_set(["plugins", "_disabled"], disabled_list) self._settings.save(force=True) - if not needs_restart: + if not needs_restart and not getattr(plugin, "safe_mode_victim", False): self._plugin_manager.disable_plugin(plugin.key) else: if plugin.key in self._pending_enable: self._pending_enable.remove(plugin.key) - elif plugin.enabled and plugin.key not in self._pending_disable: + elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable: self._pending_disable.add(plugin.key) def _fetch_repository_from_disk(self): @@ -688,8 +693,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, bundled=plugin.bundled, managable=plugin.managable, enabled=plugin.enabled, - pending_enable=(not plugin.enabled and plugin.key in self._pending_enable), - pending_disable=(plugin.enabled and plugin.key in self._pending_disable), + safe_mode_victim=getattr(plugin, "safe_mode_victim", False), + safe_mode_enabled=getattr(plugin, "safe_mode_enabled", False), + pending_enable=(not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False) and plugin.key in self._pending_enable), + pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key in self._pending_disable), pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")), pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")), origin=plugin.origin.type diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 7b6ac5202..c634dfe36 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -155,6 +155,8 @@ $(function() { self.pipAdditionalArgs = ko.observable(); self.pipPython = ko.observable(); + self.safeMode = ko.observable(); + self.pipUseUserString = ko.pureComputed(function() { return self.pipUseUser() ? "yes" : "no"; }); @@ -186,7 +188,8 @@ $(function() { }); self.enableToggle = function(data) { - return self.enableManagement() && data.key != 'pluginmanager'; + var command = self._getToggleCommand(data); + return self.enableManagement() && (command == "disable" || !data.safe_mode_victim || data.safe_mode_enabled) && data.key != 'pluginmanager'; }; self.enableUninstall = function(data) { @@ -199,7 +202,7 @@ $(function() { }; self.enableRepoInstall = function(data) { - return self.enableManagement() && self.pipAvailable() && self.isCompatible(data); + return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data); }; self.invalidUrl = ko.pureComputed(function() { @@ -209,7 +212,7 @@ $(function() { self.enableUrlInstall = ko.pureComputed(function() { var url = self.installUrl(); - return self.enableManagement() && self.pipAvailable() && url !== undefined && url.trim() != "" && !self.invalidUrl(); + return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl(); }); self.invalidArchive = ko.pureComputed(function() { @@ -219,7 +222,7 @@ $(function() { self.enableArchiveInstall = ko.pureComputed(function() { var name = self.uploadFilename(); - return self.enableManagement() && self.pipAvailable() && name !== undefined && name.trim() != "" && !self.invalidArchive(); + return self.enableManagement() && self.pipAvailable() && !self.safeMode() && name !== undefined && name.trim() != "" && !self.invalidArchive(); }); self.uploadElement.fileupload({ @@ -278,6 +281,8 @@ $(function() { self._fromPluginsResponse(data.plugins); self._fromRepositoryResponse(data.repository); self._fromPipResponse(data.pip); + + self.safeMode(data.safe_mode || false); }; self._fromPluginsResponse = function(data) { @@ -347,6 +352,7 @@ $(function() { }; if (self._getToggleCommand(data) == "enable") { + if (data.safe_mode_victim && !data.safe_mode_enabled) return; OctoPrint.plugins.pluginmanager.enable(data.key) .done(onSuccess) .fail(onError); @@ -655,7 +661,8 @@ $(function() { }; self._getToggleCommand = function(data) { - return ((!data.enabled || data.pending_disable) && !data.pending_enable) ? "enable" : "disable"; + var disable = (data.enabled || data.pending_enable || (data.safe_mode_victim && data.safe_mode_enabled)) && !data.pending_disable; + return disable ? "disable" : "enable"; }; self.toggleButtonCss = function(data) { @@ -666,7 +673,16 @@ $(function() { }; self.toggleButtonTitle = function(data) { - return self._getToggleCommand(data) == "enable" ? gettext("Enable Plugin") : gettext("Disable Plugin"); + var command = self._getToggleCommand(data); + if (command == "enable") { + if (data.safe_mode_victim && !data.safe_mode_enabled) { + return gettext("Disabled due to active safe mode"); + } else { + return gettext("Enable Plugin"); + } + } else { + return gettext("Disable Plugin"); + } }; self.onBeforeBinding = function() { diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 0c9c721df..bd717be5a 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -13,8 +13,16 @@ {% endtrans %}
{% endmacro %} +{% macro pluginmanager_safemode() %} +
{% trans %} + Safe mode is currently active. All third party plugins are disabled and cannot be + enabled. Installation of plugin packages is disabled. +{% endtrans %}
+{% endmacro %} + {{ pluginmanager_printing() }} {{ pluginmanager_nopip() }} +{{ pluginmanager_safemode() }}
@@ -32,7 +40,7 @@ -
()
+
()
 
{{ _('Homepage') }} @@ -99,6 +107,7 @@ @@ -18,7 +18,7 @@ yet. You should do this now.{% endtrans %}

- {% include "_snippets/settings/cura/profiles.jinja2" %} + {% include "snippets/settings/cura/profiles.jinja2" %}
diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/engineLog.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 similarity index 100% rename from src/octoprint/plugins/cura/templates/_snippets/settings/cura/engineLog.jinja2 rename to src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/enginePath.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 similarity index 100% rename from src/octoprint/plugins/cura/templates/_snippets/settings/cura/enginePath.jinja2 rename to src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 similarity index 100% rename from src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2 rename to src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profiles.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 similarity index 100% rename from src/octoprint/plugins/cura/templates/_snippets/settings/cura/profiles.jinja2 rename to src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 diff --git a/src/octoprint/plugins/softwareupdate/templates/_snippets/plugins/softwareupdate/checkoutFolder.jinja2 b/src/octoprint/plugins/softwareupdate/templates/snippets/plugins/softwareupdate/checkoutFolder.jinja2 similarity index 100% rename from src/octoprint/plugins/softwareupdate/templates/_snippets/plugins/softwareupdate/checkoutFolder.jinja2 rename to src/octoprint/plugins/softwareupdate/templates/snippets/plugins/softwareupdate/checkoutFolder.jinja2 diff --git a/src/octoprint/plugins/softwareupdate/templates/_snippets/plugins/softwareupdate/releaseChannel.jinja2 b/src/octoprint/plugins/softwareupdate/templates/snippets/plugins/softwareupdate/releaseChannel.jinja2 similarity index 100% rename from src/octoprint/plugins/softwareupdate/templates/_snippets/plugins/softwareupdate/releaseChannel.jinja2 rename to src/octoprint/plugins/softwareupdate/templates/snippets/plugins/softwareupdate/releaseChannel.jinja2 diff --git a/src/octoprint/plugins/softwareupdate/templates/_snippets/plugins/softwareupdate/versionTracking.jinja2 b/src/octoprint/plugins/softwareupdate/templates/snippets/plugins/softwareupdate/versionTracking.jinja2 similarity index 100% rename from src/octoprint/plugins/softwareupdate/templates/_snippets/plugins/softwareupdate/versionTracking.jinja2 rename to src/octoprint/plugins/softwareupdate/templates/snippets/plugins/softwareupdate/versionTracking.jinja2 diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 index 31f8b94ab..656f23165 100644 --- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 +++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 @@ -74,9 +74,9 @@