From 38b7640769c311e4f2b57f9d78858736a2af81b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 May 2018 18:16:06 +0200 Subject: [PATCH] Add support for prompt_* action commands --- docs/bundledplugins/action_command_prompt.rst | 110 ++++++++++++ docs/bundledplugins/index.rst | 1 + docs/features/action_commands.rst | 3 + .../plugins/action_command_prompt/__init__.py | 166 ++++++++++++++++++ .../static/js/action_command_prompt.js | 104 +++++++++++ .../action_command_prompt_settings.jinja2 | 11 ++ src/octoprint/static/js/app/helpers.js | 110 +++++++++++- 7 files changed, 504 insertions(+), 1 deletion(-) create mode 100644 docs/bundledplugins/action_command_prompt.rst create mode 100644 src/octoprint/plugins/action_command_prompt/__init__.py create mode 100644 src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js create mode 100644 src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 diff --git a/docs/bundledplugins/action_command_prompt.rst b/docs/bundledplugins/action_command_prompt.rst new file mode 100644 index 000000000..2d972cac4 --- /dev/null +++ b/docs/bundledplugins/action_command_prompt.rst @@ -0,0 +1,110 @@ +.. _sec-bundledplugins-action_command_prompt: + +Action Command Prompt support +============================= + +The OctoPrint Action Command Prompt Support Plugin comes bundled with OctoPrint (starting with 1.3.9). + +It allows firmware to trigger dialog prompts for logged in users using :ref:`action commands `, e.g. to wait +for user acknowledgement or allow the user to choose between options, and also to close the dialog again +in case its no longer needed, e.g. due to the user proceeding on the printer's own controller. + +The choice of the user can be communicated back to the firmware via a configurable GCODE command with a +placeholder for the selected option's index. + +.. _fig-bundledplugins-action_command_prompt-example: +.. figure:: ../images/bundledplugins-action_command_prompt-example.png + :align: center + :alt: Simple prompt example + + A simple dialog example triggered by the firmware + +.. _sec-bundledplugins-action_command_prompt-firststeps: + +First Steps +----------- + +In order for this plugin to work, you'll need to configure it with the command your firmware uses to accept +dialog selections. You can do that in the settings dialog. + +Currently there is no agreed upon command for this since no firmware has yet made use of this feature, so OctoPrint +ships with an empty value here. + +.. _sec-bundledplugins-action_command_prompt-configuration: + +Configuring the plugin +---------------------- + +The plugin supports the following configuration keys: + + * ``selection_command``: The command to send to the firmware on choice, including the ``{choice}`` placeholder, e.g. ``M876 S{choice}``. + +You can modify them either through the plugin's configuration dialog under Settings, or by directly editing ``config.yaml``. + +.. _sec-bundledplugins-action_command_prompt-action_commands: + +Supported action commands +------------------------- + +prompt_begin + Starts the definition of a prompt dialog. ```` is the message to display to the user. Will be ignored + if a dialog is already defined. + +prompt_choice + Defines a choice with the associated ````. Will be ignored if no dialog has been defined yet. + +prompt_button + Same as ``prompt_choice``. + +prompt_show + Tells OctoPrint that the dialog is now fully defined and to prompt the user. Will be ignored if no dialog is + defined yet. + +prompt_end + Tells OctoPrint that the dialog should now be closed (e.g. the user made the choice on the printer directly instead + of through OctoPrint). Will be ignored if no dialog is defined yet. + +.. _sec-bundledplugins-action_command_prompt-example: + +Example communication with the firmware +--------------------------------------- + +.. _sec-bundledplugins-action_command_prompt-sourcecode: + +To display the :ref:`above dialog ` the firmware sent these action commands: + +.. code-block:: none + + //action:prompt_begin Filament unloaded, swap then proceed + //action:prompt_choice Filament swapped + //action:prompt_show + +If the user clicks the button, assuming a ``selection_command`` of ``M876 S{choice}`` is configured, OctoPrint +will send back ``M876 S0`` (0-based index). + +A more complicated example with three options would be the following: + +.. code-block:: none + + //action:prompt_begin Filament runout detected. Please choose how to proceed: + //action:prompt_choice Swap filament + //action:prompt_choice Home X/Y and pause print + //action:prompt_choice Abort print + //action:prompt_show + +This would produce the following output: + +.. _fig-bundledplugins-action_command_prompt-example2: +.. figure:: ../images/bundledplugins-action_command_prompt-example2.png + :align: center + :alt: Another prompt example + + Another dialog example triggered by the firmware + +If the user selects "Abort print", OctoPrint will send ``2`` as selected choice. + +Source code +----------- + +The source of the Action Command Prompt Support plugin is bundled with OctoPrint and can be found in +its source repository under ``src/octoprint/plugins/action_command_prompt``. diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst index bd862b005..26a520699 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -7,6 +7,7 @@ Bundled Plugins .. toctree:: :maxdepth: 2 + action_command_prompt.rst cura.rst discovery.rst logging.rst diff --git a/docs/features/action_commands.rst b/docs/features/action_commands.rst index 2439b667f..7fcf6063e 100644 --- a/docs/features/action_commands.rst +++ b/docs/features/action_commands.rst @@ -48,5 +48,8 @@ resumed disconnect When this command is received from the printer, OctoPrint will immediately disconnect from it. +If the bundled :ref:`Action Command Prompt Support Plugin ` is enabled (which +should be the case by default), OctoPrint will also interactive dialog creation through its :ref:`supported commands `. + Support for additional commands may be added by plugins by implementing a handler for the :ref:`octoprint.comm.protocol.action ` hook. diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py new file mode 100644 index 000000000..0dd9a4be2 --- /dev/null +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -0,0 +1,166 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin + +from octoprint.server import user_permission + +import flask +from flask_babel import gettext + +class Prompt(object): + + def __init__(self, text): + self.text = text + self.choices = [] + + self._active = False + + @property + def active(self): + return self._active + + def add_choice(self, text): + self.choices.append(text) + + def activate(self): + self._active = True + + def validate_choice(self, choice): + return 0 <= choice < len(self.choices) + + +class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin): + + # noinspection PyMissingConstructor + def __init__(self): + self._prompt = None + self._selection_command = None + + def initialize(self): + self._selection_command = self._settings.get([b"selection_command"]) + + #~ AssetPlugin + + def get_assets(self): + return dict(js=["js/action_command_prompt.js"]) + + #~ SettingsPlugin + + def get_settings_defaults(self): + return dict(selection_command=None) + + def on_settings_save(self, data): + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + self._selection_command = self._settings.get([b"selection_command"]) + + #~ SimpleApiPlugin + + def get_api_commands(self): + return dict(select=["choice"]) + + def on_api_command(self, command, data): + if command == "select": + if not user_permission.can(): + return flask.abort(403, "Insufficient permissions") + + if self._prompt is None: + return flask.abort(409, "No active prompt") + + choice = data["choice"] + if not isinstance(choice, int) or not self._prompt.validate_choice(choice): + return flask.abort(400, "{!r} is not a valid value for choice".format(choice)) + + self._answer_prompt(choice) + + def on_api_get(self, request): + if not user_permission.can(): + return flask.abort(403, "Insufficient permissions") + if self._prompt is None: + return flask.jsonify() + else: + return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices) + + #~ TemplatePlugin + + def get_template_configs(self): + return [dict(type="settings", name=gettext("Action Command Prompt"), custom_bindings=False)] + + #~ action command handler + + def action_command_handler(self, comm, line, action, *args, **kwargs): + if not action.startswith(b"prompt_"): + return + + if self._selection_command is None: + self._logger.info("Got a prompt command from the printer but no selection command is defined") + return + + parts = action.split(None, 1) + if len(parts) == 1: + action = parts[0] + parameter = b"" + else: + action, parameter = parts + + if action == b"prompt_begin": + if self._prompt is not None and self._prompt.active: + self._logger.warn("Prompt is already defined") + return + self._prompt = Prompt(parameter.strip()) + + elif action == b"prompt_choice" or action == b"prompt_button": + if self._prompt is None: + return + if self._prompt.active: + self._logger.warn("Prompt is already active") + return + self._prompt.add_choice(parameter.strip()) + + elif action == b"prompt_show": + if self._prompt is None: + return + if self._prompt.active: + self._logger.warn("Prompt is already active") + return + self._show_prompt() + + elif action == b"prompt_end": + if self._prompt is None: + return + self._close_prompt() + self._prompt = None + + #~ prompt handling + + def _show_prompt(self): + self._prompt.activate() + self._plugin_manager.send_plugin_message(self._identifier, dict(action="show", + text=self._prompt.text, + choices=self._prompt.choices)) + + def _close_prompt(self): + self._prompt = None + self._plugin_manager.send_plugin_message(self._identifier, dict(action="close")) + + def _answer_prompt(self, choice): + self._close_prompt() + self._printer.commands([self._selection_command.format(choice=choice)]) + + +__plugin_name__ = "Action Command Prompt Support" +__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection" +__plugin_author__ = "Gina Häußge" +__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger" + "confirmation or selection prompts in OctoPrint") +__plugin_license__ = "AGPLv3" +__plugin_implementation__ = ActionCommandPromptPlugin() +__plugin_hooks__ = { + b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler +} diff --git a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js new file mode 100644 index 000000000..6298a5338 --- /dev/null +++ b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js @@ -0,0 +1,104 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintActionCommandPromptClient = function(base) { + this.base = base; + }; + + OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) { + return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts); + }; + + OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) { + var data = { + choice: choice + }; + return this.base.simpleApiCommand("action_command_prompt", "select", data, opts); + }; + + OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient); + return OctoPrintActionCommandPromptClient; +}); + +$(function() { + function ActionCommandPromptViewModel(parameters) { + var self = this; + + self.loginState = parameters[0]; + + self._modal = undefined; + + self.requestData = function() { + if (!self.loginState.isUser()) return; + + OctoPrint.plugins.action_command_prompt.get() + .done(self.fromResponse); + }; + + self.fromResponse = function(data) { + if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) { + self._showPrompt(data.text, data.choices); + } + }; + + self._showPrompt = function(text, buttons) { + var opts = { + title: gettext("Message from your printer"), + message: text, + selections: buttons, + onselect: function(index) { + if (index > -1) { + self._select(index); + } + }, + onclose: function() { + self._modal = undefined; + } + }; + + self._modal = showSelectionDialog(opts) + }; + + self._select = function(index) { + OctoPrint.plugins.action_command_prompt.select(index); + }; + + self._closePrompt = function() { + if (self._modal) { + self._modal.modal("hide"); + } + }; + + self.onStartupComplete = function() { + self.requestData(); + }; + + self.onDataUpdaterPluginMessage = function(plugin, data) { + if (!self.loginState.isUser()) return; + if (plugin !== "action_command_prompt") { + return; + } + + switch (data.action) { + case "show": { + self._showPrompt(data.text, data.choices); + break; + } + case "close": { + self._closePrompt(); + break; + } + } + } + + } + + OCTOPRINT_VIEWMODELS.push({ + construct: ActionCommandPromptViewModel, + dependencies: ["loginStateViewModel"] + }); +}); diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 new file mode 100644 index 000000000..a30e7f9b8 --- /dev/null +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 @@ -0,0 +1,11 @@ +

{{ _('Action Command Prompt Settings') }}

+ +
+
+ +
+ +
{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace {choice} with the index of the selected choice. E.g. M876 S{choice} will become M123 S1') }}
+
+
+
diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 8f4fa92db..49af106bc 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -650,6 +650,7 @@ function showMessageDialog(msg, options) { var onclose = options.onclose || undefined; var onshow = options.onshow || undefined; var onshown = options.onshown || undefined; + var nofade = options.nofade || false; if (_.isString(message)) { message = $("

" + message + "

"); @@ -660,7 +661,11 @@ function showMessageDialog(msg, options) { var modalFooter = $(''); var modal = $('
') - .addClass('modal hide fade') + .addClass("modal hide"); + if (!nofade) { + modal.addClass("fade"); + } + modal .append($('
').addClass('modal-header').append(modalHeader)) .append($('
').addClass('modal-body').append(modalBody)) .append($('
').addClass('modal-footer').append(modalFooter)); @@ -669,6 +674,7 @@ function showMessageDialog(msg, options) { if (onclose && _.isFunction(onclose)) { onclose(); } + modal.remove(); }); if (onshow) { @@ -743,6 +749,108 @@ function showConfirmationDialog(msg, onacknowledge, options) { onproceed(e); } modal.modal("hide"); + modal.remove(); + }); + + return modal; +} + +function showSelectionDialog(options) { + var title = options.title; + var message = options.message || undefined; + var selections = options.selections || []; + + var maycancel = options.maycancel || false; + var cancel = options.cancel || undefined; + var onselect = options.onselect || undefined; + var onclose = options.onclose || undefined; + var dialogClass = options.dialogClass || ""; + var nofade = options.nofade || false; + + // header + var modalHeader; + if (maycancel) { + modalHeader = $('

' + title + '

'); + } else { + modalHeader = $('

' + title + '

'); + } + + // body + var buttons = []; + var selectionBody = $("
"); + var container; + var additionalClass; + + if (selections.length === 1) { + container = selectionBody; + additionalClass = "btn-block"; + } else if (selections.length === 2) { + container = $("
"); + selectionBody.append(container); + additionalClass = "span6" + } else { + container = $("
"); + selectionBody.append(container); + additionalClass = "span6 offset3"; + } + + _.each(selections, function(s, i) { + var button = $(''); + if (additionalClass) { + button.addClass(additionalClass); + } + container.append(button); + buttons.push(button); + + if (selections.length > 2 && i < selections.length - 1) { + container = $("
"); + selectionBody.append(container); + } + }); + + // divs + var headerDiv = $('
').addClass('modal-header').append(modalHeader); + + var bodyDiv = $('
').addClass('modal-body'); + if (message) { + bodyDiv.append($('

' + message + '

')); + } + bodyDiv.append(selectionBody); + + // create modal and do final wiring up + var modal = $('
') + .addClass('modal hide'); + if (!nofade) { + modal.addClass('fade'); + } + if (!cancel) { + modal.data("backdrop", "static").data("keyboard", "false"); + } + + modal.addClass(dialogClass) + .append(headerDiv) + .append(bodyDiv); + modal.on('hidden', function(event) { + if (onclose && _.isFunction(onclose)) { + onclose(event); + } + modal.remove(); + }); + modal.modal("show"); + + _.each(buttons, function(button) { + button.click(function(e) { + e.preventDefault(); + var index = button.data("index"); + if (index < 0) { + return; + } + + if (onselect && _.isFunction(onselect)) { + onselect(index, e); + } + modal.modal("hide"); + }) }); return modal;