diff --git a/CHANGELOG.md b/CHANGELOG.md index 96e0485c9..c6b445398 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ * OctoPrint now has a [plugin system](http://docs.octoprint.org/en/devel/plugins/index.html) which allows extending its core functionality. * New type of API key: [App Session Keys](http://docs.octoprint.org/en/devel/api/apps.html) for trusted applications +* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A + connection to a printer will always have a printer profile associated. +* OctoPrint now supports `action:...` commands received via debug messages (`// action:...`) from the printer. Currently supported are + - `action:pause`: Pauses the current job in OctoPrint + - `action:resume`: Resumes the current job in OctoPrint + - `action:disconnect`: Disconnects OctoPrint from the printer ### Improvements @@ -33,13 +39,17 @@ ([#532](https://github.com/foosel/OctoPrint/issues/532) and [#590](https://github.com/foosel/OctoPrint/pull/590)) * Slicing has been greatly improved: * It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing - job (defining overrides is not yet part of the UI but it's on the roadmap). + job (defining overrides is not yet part of the UI but it's on the roadmap). + * A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list + as well). This dialog also allows specifying which action to take after slicing has been completed (none, selecting the + sliced GCODE for printing or starting to print it directly) * Slicers themselves are integrated into the system via ``SlicingPlugins``. * The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the [CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See [the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to accommodate the new integration. * The "Slicing done" notification is now colored green ([#558](https://github.com/foosel/OctoPrint/issues/558)). + * The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI). * File management now supports STL files as first class citizens (including UI adjustments to allow management of uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI) * Also interpret lines starting with "!!" as errors @@ -51,8 +61,17 @@ long as they are in use * Settings in UI get refreshed when opening settings dialog * New event "SettingsUpdated" -* Print time estimation is now not displayed until it becomes somewhat stable. Display in web interface now also happens - in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one +* "Print time left" is now not displayed until it becomes somewhat stable. Display in web interface now also happens + in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one. Additionally + OctoPrint will use data from prior prints to enhance the initial print time estimation. +* Added handler for uncaught exceptions to make sure those get logged, should make the logs even more useful for analysing + bug reports +* The server now tracks the modification date of the configuration file and reloads it prior to saving the config if + it has been changed during runtime by external editing, hence no config settings added manually while the server + was running should be overwritten anymore. +* Automatically hard-reload the UI if upon reconnecting to the server a new version is detected. +* Better handling of errors on the websocket - no more logging of the full stack trace to the log, only a warning + message for now. ### Bug Fixes @@ -62,20 +81,44 @@ setups under Smoothieware * [#556](https://github.com/foosel/OctoPrint/issues/556) - Allow login of the same user from multiple browsers without side effects +* [#680](https://github.com/foosel/OctoPrint/issues/680) - Don't accidentally include a newline from the MIME headers + in the parsed multipart data from file uploads * Various fixes of bugs in newly introduced features and improvements: * [#625](https://github.com/foosel/OctoPrint/pull/625) - Newly added GCODE files were not being added to the analysis queue + * [#664](https://github.com/foosel/OctoPrint/issues/664) - Fixed jog controls again + * [#677](https://github.com/foosel/OctoPrint/issues/677) - Fixed extruder offsets not being properly editable in + printer profiles + * [#683](https://github.com/foosel/OctoPrint/issues/683) - Fixed heated bed option not being properly displayed in + printer profiles * Various fixes without tickets: * GCODE viewer now doesn't stumble over completely extrusionless GCODE files * Do not deliver the API key on settings API unless user has admin rights + * Don't hiccup on slic3r filament_diameter comments in GCODE generated for multi extruder setups ## 1.1.2 (Unreleased) +### Improvements + +* Added deletion of `*.pyc` files to `python setup.py clean` command, should help tremendously when switching branches (backported + from [9e014eb](https://github.com/foosel/OctoPrint/commit/9e014eba1feffde11ed0601d9c911b8cac9f3fb0)) + ### Bug Fixes * [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated by versioneer -* [IRC] Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups +* [IRC] - Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups +* [ML] - Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url +* [unreported] & [#698](https://github.com/foosel/OctoPrint/issues/698) - Generated URLs now take X-Forwarded-Host header + sent by proxies into account for included host and port, also fixed [#698](https://github.com/foosel/OctoPrint/issues/698) + introduced by this +* Small fixes for timelapse creation: + - [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there + was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b) + and [bf9d5ef](https://github.com/foosel/OctoPrint/commit/bf9d5efe43a1e57aacd8512125082ddca06b4efc)) + - [#693](https://github.com/foosel/OctoPrint/issues/693) - Try not to capture an image if image counter is still unset + - [unreported] Synchronize image counter decrementing as well as incrementing to prevent rare race conditions when generating the + image file names ## 1.1.1 (2014-10-27) @@ -93,6 +136,8 @@ * [#604](https://github.com/foosel/OctoPrint/issues/604) - Properly initialize settings basedir on server startup * [IRC] Also allow downloading .g files via Tornado +([Commits](https://github.com/foosel/OctoPrint/compare/1.1.0...1.1.1)) + ## 1.1.0 (2014-09-03) ### New Features diff --git a/docs/api/printer.rst b/docs/api/printer.rst index 7c4a1a65f..469af8dde 100644 --- a/docs/api/printer.rst +++ b/docs/api/printer.rst @@ -755,6 +755,61 @@ Retrieve the current SD state :statuscode 200: No error :statuscode 404: If SD support has been disabled in OctoPrint's config. +.. _sec-api-printer-arbcommand: + +Send an arbitrary command to the printer +======================================== + +.. http:post:: /api/printer/command + + Sends any command to the printer via the serial interface. Should be used with some care as some commands can interfere with + or even stop a running print job. + + Expects a :ref:`Arbitrary Command Request ` as the request's body. + + If successful returns a :http:statuscode:`204` and an empty body. + + **Example for sending a single command** + + .. sourcecode:: http + + POST /api/printer/command HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "M106" + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + + **Example for sending multiple commands** + + .. sourcecode:: http + + POST /api/printer/command HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "commands": [ + "M18", + "M106 S0" + ] + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + + :json string command: Single command to send to the printer, mutually exclusive with ``commands``. + :json string commands: List of commands to send to the printer, mutually exclusive with ``command``. + :statuscode 204: No error + .. _sec-api-printer-datamodel: Datamodel @@ -831,3 +886,24 @@ SD State - Boolean - Whether the SD card has been initialized (``true``) or not (``false``). +.. _sec-api-printer-datamodel-arbcommand: + +Arbitrary Command Request +------------------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``command`` + - 0..1 + - String + - Single command to send to the printer, mutually exclusive with ``commands``. + * - ``commands`` + - 0..* + - Array of String + - Multiple commands to send to the printer (in the given order), mutually exclusive with ``command``. diff --git a/docs/events/index.rst b/docs/events/index.rst index a86f83a5e..55200cab0 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -96,6 +96,10 @@ ClientOpened ClientClosed A client has disconnected from the webserver + Payload: + + * ``remoteAddress``: the remote address (IP) of the client that disconnected + Printer communication --------------------- diff --git a/setup.py b/setup.py index 268768838..22db85f6d 100644 --- a/setup.py +++ b/setup.py @@ -96,6 +96,26 @@ class CleanCommand(Command): file_handler=delete_file ) + # pyc files + def delete_folder_if_empty(path, applied_handler): + if not applied_handler: + return + if len(os.listdir(path)) == 0: + shutil.rmtree(path) + print "Deleted %s since it was empty" % path + + def delete_file(path): + os.remove(path) + print "Deleted %s" % path + + import fnmatch + _recursively_handle_files( + os.path.abspath("src"), + lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"), + folder_handler=delete_folder_if_empty, + file_handler=delete_file + ) + class NewTranslation(Command): description = "create a new translation" diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 54d13a434..b2cf61425 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -9,9 +9,12 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging import os import pylru +import tempfile import octoprint.filemanager +from octoprint.util import safeRename + class StorageInterface(object): @@ -867,12 +870,16 @@ class LocalFileStorage(StorageInterface): def _save_metadata(self, path, metadata): metadata_path = os.path.join(path, ".metadata.yaml") + fh, metadata_temporary_path = tempfile.mkstemp() + os.close(fh) + with self._metadata_lock: - with open(metadata_path, "w") as f: - try: + try: + with open(metadata_temporary_path, "w") as f: import yaml yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True) - except: - self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals())) - else: - self._metadata_cache[path] = metadata + safeRename(metadata_temporary_path, metadata_path, throw_error=True) + except: + self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals())) + else: + self._metadata_cache[path] = metadata diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py index 4e9653e3a..da0705066 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -188,7 +188,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, def is_slicer_configured(self): cura_engine = s.get(["cura_engine"]) - return cura_engine is not None and os.path.exists(cura_engine) + if cura_engine is not None and os.path.exists(cura_engine): + return True + else: + self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine) def get_slicer_properties(self): return dict( diff --git a/src/octoprint/printer/__init__.py b/src/octoprint/printer/__init__.py index 8c3403717..929c5dedb 100644 --- a/src/octoprint/printer/__init__.py +++ b/src/octoprint/printer/__init__.py @@ -705,6 +705,9 @@ class Printer(): def mcReceivedRegisteredMessage(self, command, output): self._sendFeedbackCommandOutput(command, output) + def mcForceDisconnect(self): + self.disconnect() + #~~ sd file handling def getSdFiles(self): diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index add8891ca..eaab4b5cc 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -216,6 +216,8 @@ class Server(): from tornado.ioloop import IOLoop from tornado.web import Application + import sys + debug = self._debug # first initialize the settings singleton and make sure it uses given configfile and basedir if available @@ -224,6 +226,9 @@ class Server(): # then initialize logging self._initLogging(self._debug, self._logConf) logger = logging.getLogger(__name__) + def exception_logger(exc_type, exc_value, exc_tb): + logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb)) + sys.excepthook = exception_logger logger.info("Starting OctoPrint %s" % DISPLAY_VERSION) # then initialize the plugin manager @@ -275,8 +280,10 @@ class Server(): app.wsgi_app, settings().get(["server", "reverseProxy", "prefixHeader"]), settings().get(["server", "reverseProxy", "schemeHeader"]), + settings().get(["server", "reverseProxy", "hostHeader"]), settings().get(["server", "reverseProxy", "prefixFallback"]), - settings().get(["server", "reverseProxy", "prefixScheme"]) + settings().get(["server", "reverseProxy", "schemeFallback"]), + settings().get(["server", "reverseProxy", "hostFallback"]) ) secret_key = settings().get(["server", "secretKey"]) diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index 55ae6d3b1..2f5662d51 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -300,7 +300,6 @@ def printerSdState(): @api.route("/printer/command", methods=["POST"]) @restricted_access def printerCommand(): - # TODO: document me if not printer.isOperational(): return make_response("Printer is not operational", 409) @@ -309,15 +308,17 @@ def printerCommand(): data = request.json - parameters = {} - if "parameters" in data.keys(): - parameters = data["parameters"] + parameters = dict() + if "parameters" in data.keys(): parameters = data["parameters"] - commands = [] - if "command" in data.keys(): + if "command" in data and "commands" in data: + return make_response("'command' and 'commands' are mutually exclusive", 400) + elif "command" in data: commands = [data["command"]] - elif "commands" in data.keys(): + elif "commands" in data and isinstance(data["commands"], (list, tuple)): commands = data["commands"] + else: + return make_response("Need either single 'command' or list of 'commands'", 400) commandsToSend = [] for command in commands: diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 83c246cc9..b69022698 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -147,20 +147,25 @@ class ReverseProxied(object): :param app: the WSGI application :param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix :param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme + :param header_host: the HTTP header in the wsgi environment from which to determine the host for which to generate external URLs :param base_url: the prefix to use as fallback if headers are not set + :param scheme: the scheme to use as fallback if headers are not set + :param host: the host to use as fallback if headers are not set """ - def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", base_url="", scheme=""): + def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", header_host="x-forwarded-host", base_url="", scheme="", host=""): self.app = app - # headers for prefix & scheme, converted to conform to WSGI format + # headers for prefix & scheme & host, converted to conform to WSGI format to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_") self._header_prefix = to_wsgi_format(header_prefix) self._header_scheme = to_wsgi_format(header_scheme) + self._header_host = to_wsgi_format(header_host) - # fallback prefix & scheme from config + # fallback prefix & scheme & host from config self._fallback_prefix = base_url self._fallback_scheme = scheme + self._fallback_host = host def __call__(self, environ, start_response): # determine prefix @@ -184,6 +189,15 @@ class ReverseProxied(object): if scheme: environ["wsgi.url_scheme"] = scheme + # determine host + host = environ.get(self._header_host, "") + if not host: + host = self._fallback_host + + # rewrite host header based on host + if host: + environ["HTTP_HOST"] = host + # call wrapped app with rewritten environment return self.app(environ, start_response) diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index bf9ee3cb0..3d321b39d 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -34,6 +34,8 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): self._eventManager = eventManager self._pluginManager = pluginManager + self._remoteAddress = None + def _getRemoteAddress(self, info): forwardedFor = info.headers.get("X-Forwarded-For") if forwardedFor is not None: @@ -41,8 +43,8 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): return info.ip def on_open(self, info): - remoteAddress = self._getRemoteAddress(info) - self._logger.info("New connection from client: %s" % remoteAddress) + self._remoteAddress = self._getRemoteAddress(info) + self._logger.info("New connection from client: %s" % self._remoteAddress) # connected => update the API key, might be necessary if the client was left open while the server restarted self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION}) @@ -52,20 +54,20 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): octoprint.timelapse.registerCallback(self) self._pluginManager.register_client(self) - self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress}) + self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress}) for event in octoprint.events.all_events(): self._eventManager.subscribe(event, self._onEvent) octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current) def on_close(self): - self._logger.info("Client connection closed") + self._logger.info("Client connection closed: %s" % self._remoteAddress) self._printer.unregisterCallback(self) self._fileManager.unregister_slicingprogress_callback(self) octoprint.timelapse.unregisterCallback(self) self._pluginManager.unregister_client(self) - self._eventManager.fire(Events.CLIENT_CLOSED) + self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress}) for event in octoprint.events.all_events(): self._eventManager.unsubscribe(event, self._onEvent) @@ -137,4 +139,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): self.sendEvent(event, payload) def _emit(self, type, payload): - self.send({type: payload}) + try: + self.send({type: payload}) + except Exception as e: + self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, e.message)) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index a07d6c7e1..c9d3ef261 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -69,8 +69,10 @@ default_settings = { "reverseProxy": { "prefixHeader": "X-Script-Name", "schemeHeader": "X-Scheme", + "hostHeader": "X-Forwarded-Host", "prefixFallback": "", - "schemeFallback": "" + "schemeFallback": "", + "hostFallback": "" }, "uploads": { "maxSize": 1 * 1024 * 1024 * 1024, # 1GB diff --git a/src/octoprint/static/js/app/viewmodels/slicing.js b/src/octoprint/static/js/app/viewmodels/slicing.js index 23a189372..7c60c60e9 100644 --- a/src/octoprint/static/js/app/viewmodels/slicing.js +++ b/src/octoprint/static/js/app/viewmodels/slicing.js @@ -28,6 +28,7 @@ function SlicingViewModel(loginStateViewModel, printerProfilesViewModel) { self.afterSlicing = ko.observable("none"); self.show = function(target, file) { + self.requestData(); self.target = target; self.file = file; self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file})); @@ -48,13 +49,18 @@ function SlicingViewModel(loginStateViewModel, printerProfilesViewModel) { && self.profile() != undefined; }); - self.requestData = function() { + self.requestData = function(callback) { $.ajax({ url: API_BASEURL + "slicing", type: "GET", dataType: "json", - success: self.fromResponse - }) + success: function(data) { + self.fromResponse(data); + if (callback !== undefined) { + callback(); + } + } + }); }; self.fromResponse = function(data) { diff --git a/src/octoprint/templates/index.jinja2 b/src/octoprint/templates/index.jinja2 index 955d4ea6b..928112c03 100644 --- a/src/octoprint/templates/index.jinja2 +++ b/src/octoprint/templates/index.jinja2 @@ -59,7 +59,7 @@ var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold }}; var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold }}; - var SOCKJS_URI = window.location.protocol.slice(0, -1) + "://" + (window.document ? window.document.domain : window.location.hostname) + ":" + window.location.port + BASEURL + "sockjs"; + var SOCKJS_URI = "{{ url_for('index') }}" + "sockjs"; var SOCKJS_DEBUG = {% if debug -%} true; {% else %} false; {%- endif %} var UI_API_KEY = "{{ uiApiKey }}"; diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index ba5daf223..24d1dfce4 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -227,8 +227,12 @@ class Timelapse(object): self._logger.warn("Cannot capture image, capture directory is unset") return + if self._imageNumber is None: + self._logger.warn("Cannot capture image, image number is unset") + return + with self._captureMutex: - filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % (self._imageNumber)) + filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber) self._imageNumber += 1 self._logger.debug("Capturing image to %s" % filename) captureThread = threading.Thread(target=self._captureWorker, kwargs={"filename": filename}) @@ -243,8 +247,9 @@ class Timelapse(object): self._logger.debug("Image %s captured from %s" % (filename, self._snapshotUrl)) except: self._logger.exception("Could not capture image %s from %s, decreasing image counter again" % (filename, self._snapshotUrl)) - if self._imageNumber is not None and self._imageNumber > 0: - self._imageNumber -= 1 + with self._captureMutex: + if self._imageNumber is not None and self._imageNumber > 0: + self._imageNumber -= 1 eventManager().fire(Events.CAPTURE_DONE, {"file": filename}) def _createMovie(self, success=True): @@ -299,7 +304,7 @@ class Timelapse(object): # finalize command with output file self._logger.debug("Rendering movie to %s" % output) - command.append(output) + command.append("\"" + output + "\"") eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)}) command_str = " ".join(command) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 59adf6076..3972f5fcd 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -148,7 +148,7 @@ def findCollisionfreeName(input, extension, existingFilenames): raise ValueError("Can't create a collision free filename") -def safeRename(old, new): +def safeRename(old, new, throw_error=False): """ Safely renames a file. @@ -173,12 +173,14 @@ def safeRename(old, new): os.rename(new, backup) os.rename(old, new) os.remove(backup) - except OSError: + except OSError as e: # if anything went wrong, try to rename the backup file to its original name logger.error("Could not perform safe rename, trying to revert") if os.path.exists(backup): - os.remove(new) - os.rename(backup, new) + silentRemove(new) + os.rename(backup, new) + if throw_error: + raise e else: # on anything else than windows it's ooooh so much easier... os.rename(old, new) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 2bbfd2084..bcdcd0172 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -161,6 +161,7 @@ class MachineCom(object): # hooks self._pluginManager = octoprint.plugin.plugin_manager() self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.gcode") + self._printer_action_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.action") # SD status data self._sdAvailable = False @@ -655,6 +656,27 @@ class MachineCom(object): if line.strip() is not "": self._timeout = getNewTimeout("communication") + ##~~ debugging output handling + if line.startswith("//"): + debugging_output = line[2:].strip() + if debugging_output.startswith("action:"): + action_command = debugging_output[len("action:"):].strip() + + if action_command == "pause": + self._log("Pausing on request of the printer...") + self.setPause(True) + elif action_command == "resume": + self._log("Resuming on request of the printer...") + self.setPause(False) + elif action_command == "disconnect": + self._log("Disconnecting on request of the printer...") + self._callback.mcForceDisconnect() + else: + for hook in self._printer_action_hooks: + self._printer_action_hooks[hook](self, line, action_command) + else: + continue + ##~~ Error handling line = self._handleErrors(line) @@ -1296,6 +1318,9 @@ class MachineComPrintCallback(object): def mcReceivedRegisteredMessage(self, command, message): pass + def mcForceDisconnect(self): + pass + ### Printing file information classes ################################################################################## class PrintingFileInformation(object): diff --git a/src/octoprint/util/virtual.py b/src/octoprint/util/virtual.py index 2983d5a78..6c1b6978d 100644 --- a/src/octoprint/util/virtual.py +++ b/src/octoprint/util/virtual.py @@ -227,6 +227,8 @@ class VirtualPrinter(): self._relative = True elif "G92" in data: self._setPosition(data) + elif data.startswith("!!DEBUG:"): + self._debugTrigger(data[len("!!DEBUG:"):].strip()) elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3") \ or data.startswith("G28") or data.startswith("G29") or data.startswith("G30") \ @@ -237,6 +239,14 @@ class VirtualPrinter(): if len(data.strip()) > 0: self._sendOk() + def _debugTrigger(self, data): + if data == "action_pause": + self.outgoing.put("// action:pause") + elif data == "action_resume": + self.outgoing.put("// action:resume") + elif data == "action_disconnect": + self.outgoing.put("// action:disconnect") + def _listSd(self): self.outgoing.put("Begin file list") if settings().getBoolean(["devel", "virtualPrinter", "extendedSdFileList"]):