From 45b59494ca0d8eb338a0ed3e24c7c2396b9e3675 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 15 Jan 2019 16:30:22 +0100 Subject: [PATCH] Add new hook too allow plugins to register custom events Implements #2965 --- docs/bundledplugins/pluginmanager.rst | 39 +++++++++++++++++++ docs/bundledplugins/printer_safety_check.rst | 14 +++++++ docs/bundledplugins/softwareupdate.rst | 23 +++++++++++ docs/events/index.rst | 13 ++----- docs/plugins/hooks.rst | 28 +++++++++++++ src/octoprint/events.py | 20 +++++++++- src/octoprint/plugins/pi_support/__init__.py | 14 ++++++- .../plugins/pluginmanager/__init__.py | 34 ++++++++++------ .../plugins/printer_safety_check/__init__.py | 17 ++++++-- .../plugins/softwareupdate/__init__.py | 17 ++++++-- src/octoprint/plugins/tracking/__init__.py | 39 ++++++++++++------- src/octoprint/server/__init__.py | 11 ++++++ 12 files changed, 225 insertions(+), 44 deletions(-) diff --git a/docs/bundledplugins/pluginmanager.rst b/docs/bundledplugins/pluginmanager.rst index dacb3f8ca..2ec1babbb 100644 --- a/docs/bundledplugins/pluginmanager.rst +++ b/docs/bundledplugins/pluginmanager.rst @@ -82,6 +82,45 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``: - hidden - plugins +.. _sec-bundledplugins-pluginmanager-events: + +Events +------ + +plugin_pluginmanager_install_plugin + A plugin was installed. + + Payload: + + * ``id``: the identifier of the installed plugin + * ``version``: the version of the installed plugin + * ``source``: source from which the plugin was installed, can be an URL or a path in the local file system + * ``source_type``: type of source from which the plugin was installed, can be ``url`` or ``path`` + +plugin_pluginmanager_uninstall_plugin + A plugin was uninstalled. + + Payload: + + * ``id``: the identifier of the uninstalled plugin + * ``version``: the version of the uninstalled plugin + +plugin_pluginmanager_enable_plugin + A plugin was enabled. + + Payload: + + * ``id``: the identifier of the enabled plugin + * ``version``: the version of the enabled plugin + +plugin_pluginmanager_disabled_plugin + A plugin was disabled. + + Payload: + + * ``id``: the identifier of the disabled plugin + * ``version``: the version of the disabled plugin + .. _sec-bundledplugins-pluginmanager-hooks: Hooks diff --git a/docs/bundledplugins/printer_safety_check.rst b/docs/bundledplugins/printer_safety_check.rst index 6770056cb..320de9053 100644 --- a/docs/bundledplugins/printer_safety_check.rst +++ b/docs/bundledplugins/printer_safety_check.rst @@ -29,6 +29,20 @@ If you know of further printers/printer firmwares that need to be added here, pl unexpectedly and with `catastrophic `_ `results `_. +.. _sec-bundledplugins-printer_safety_check-events: + +Events +------ + +warning + A printer safety warning was triggered. + + Payload: + + * ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``) + * ``check_name``: name of check that was triggered (e.g. ``aneta8``) + * ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``) + .. _sec-bundledplugins-printer_safety_check-source: Source Code diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index de4896b6d..1fd5d3a80 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -325,6 +325,29 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing branch: devel pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip' +.. _sec-bundledplugins-softwareupdate-events: + +Events +------ + +plugin_softwareupdate_update_succeeded + An update succeeded. + + Payload: + + * ``target``: update target + * ``from_version``: version from which was updated + * ``to_version``: version to which was updated + +plugin_softwareupdate_update_failed + An update failed. + + Payload: + + * ``target``: update target + * ``from_version``: version from which was updated + * ``to_version``: version to which was updated + .. _sec-bundledplugins-softwareupdate-hooks: Hooks diff --git a/docs/events/index.rst b/docs/events/index.rst index 288f8d82f..c84e420f7 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -6,15 +6,6 @@ Events .. contents:: - -.. note:: - - With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events. - Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to - accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer - separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed - to indicate what to do with the command contained. - .. _sec-events-configuration: Configuration @@ -85,6 +76,10 @@ and its origin via the placeholder ``{origin}``. Available Events ================ +.. note:: + + Plugins may add additional events via the :ref:`octoprint.events.register_custom_events hook `. + Server ------ diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 77a3fbaec..2dc08b3c2 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -903,6 +903,34 @@ octoprint.comm.transport.serial.factory :rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and optionally ``baudrate`` and ``timeout`` attributes as described above. +.. _sec-plugins-hook-events-register_custom_events: + +octoprint.events.register_custom_events +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: register_custom_events_hook(*args, **kwargs) + + Return a list of custom :ref:`events ` to register in the system for your plugin. + + Should return a list of strings which represent the custom events. Their name on the `octoprint.events.Events` object + will be the returned value transformed into upper case ``CAMEL_CASE`` and prefixed with ``PLUGIN_``. Their + value will be prefixed with ``plugin__``. + + Example: + + Consider the following hook part of a plugin with the identifier ``myplugin``. It will register two custom events + in the system, ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_CUSTOM_EVENT`` with value ``plugin_myplugin_my_custom_event`` + and ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_OTHER_CUSTOM_EVENT`` with value ``plugin_myplugin_my_other_custom_event``. + + .. code-block:: python + :linenos: + + def register_custom_events(*args, **kwargs): + return ["my_custom_event", "my_other_custom_event"] + + :return: A list of custom events to register + :rtype: list + .. _sec-plugins-hook-filemanager-analysis-factory: octoprint.filemanager.analysis.factory diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 4b2e2a12b..9bb3b167e 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -14,6 +14,7 @@ except ImportError: import Queue as queue import threading import collections +import re from octoprint.settings import settings import octoprint.plugin @@ -23,7 +24,7 @@ _instance = None def all_events(): - return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")] + return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)] class Events(object): @@ -119,6 +120,23 @@ class Events(object): # Settings SETTINGS_UPDATED = "SettingsUpdated" + @classmethod + def register_event(cls, event, prefix=None): + name = cls._to_identifier(event) + if prefix: + event = prefix + event + name = cls._to_identifier(prefix) + name + setattr(cls, name, event) + return name, event + + # based on https://stackoverflow.com/a/1176023 + _first_cap_re = re.compile('(.)([A-Z][a-z]+)') + _all_cap_re = re.compile('([a-z0-9])([A-Z])') + + @classmethod + def _to_identifier(cls, name): + s1 = cls._first_cap_re.sub(r'\1_\2', name) + return cls._all_cap_re.sub(r'\1_\2', s1).upper() def eventManager(): global _instance diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py index 8ea0af7be..4c79b6151 100644 --- a/src/octoprint/plugins/pi_support/__init__.py +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -12,6 +12,7 @@ from flask_babel import gettext from octoprint.util import RepeatedTimer import octoprint.plugin +import octoprint.events _PROC_DT_MODEL_PATH = "/proc/device-tree/model" _OCTOPI_VERSION_PATH = "/etc/octopi_version" @@ -290,7 +291,13 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state", state=self._throttle_state.as_dict())) - self._event_bus.fire("plugin_pi_support_throttle_state", self._throttle_state.as_dict()) + + # noinspection PyUnresolvedReferences + self._event_bus.fire(octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, self._throttle_state.as_dict()) + + +def register_custom_events(*args, **kwargs): + return ["throttle_state",] __plugin_name__ = "Pi Support Plugin" @@ -316,5 +323,10 @@ def __plugin_load__(): global __plugin_implementation__ __plugin_implementation__ = plugin + global __plugin_hooks__ + __plugin_hooks__ = { + "octoprint.events.register_custom_events": register_custom_events + } + global __plugin_helpers__ __plugin_helpers__ = dict(get_throttled=plugin.get_throttle_state) diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index f6c492fdf..b602e4d95 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -16,6 +16,7 @@ from octoprint.server import admin_permission from octoprint.util.pip import LocalPipCaller from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible from octoprint.util.platform import get_os, is_os_compatible +from octoprint.events import Events from flask import jsonify, make_response from flask_babel import gettext @@ -485,10 +486,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.log_all_plugins() self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version)) - self._event_bus.fire("plugin_pluginmanager_installplugin", dict(id=new_plugin.key, - version=new_plugin.version, - source=source, - source_type=source_type)) + + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, dict(id=new_plugin.key, + version=new_plugin.version, + source=source, + source_type=source_type)) result = dict(result=True, source=source, @@ -580,8 +583,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.reload_plugins() - self._event_bus.fire("plugin_pluginmanager_uninstallplugin", dict(id=plugin.key, - version=plugin.version)) + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, dict(id=plugin.key, + version=plugin.version)) result = dict(result=True, needs_restart=needs_restart, @@ -723,8 +727,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif not plugin.enabled and plugin.key not in self._pending_enable: self._pending_enable.add(plugin.key) - self._event_bus.fire("plugin_pluginmanager_enableplugin", dict(id=plugin.key, - version=plugin.version)) + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, dict(id=plugin.key, + version=plugin.version)) def _mark_plugin_disabled(self, plugin, needs_restart=False): disabled_list = list(self._settings.global_get(["plugins", "_disabled"], @@ -743,8 +748,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable: self._pending_disable.add(plugin.key) - self._event_bus.fire("plugin_pluginmanager_disableplugin", dict(id=plugin.key, - version=plugin.version)) + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, dict(id=plugin.key, + version=plugin.version)) def _fetch_all_data(self, do_async=False): def run(): @@ -961,6 +967,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, versions=notification.get("versions", []), important=notification.get("important", False)) + +def _register_custom_events(*args, **kwargs): + return ["install_plugin", "uninstall_plugin", "enable_plugin", "disable_plugin"] + + __plugin_name__ = "Plugin Manager" __plugin_author__ = "Gina Häußge" __plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html" @@ -974,5 +985,6 @@ def __plugin_load__(): global __plugin_hooks__ __plugin_hooks__ = { "octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize, - "octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types + "octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types, + "octoprint.events.register_custom_events": _register_custom_events } diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 01b118ced..5728440c9 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -150,9 +150,12 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, for check_name, check in checks: if check(*args, **kwargs): self._register_warning(warning_type, message) - self._event_bus.fire("plugin_printer_safety_check_warning", dict(check_type=check_type, - check_name=check_name, - warning_type=warning_type)) + + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING, dict(check_type=check_type, + check_name=check_name, + warning_type=warning_type)) + changes = True break @@ -176,6 +179,11 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, def _ping_clients(self): self._plugin_manager.send_plugin_message(self._identifier, dict(type="update")) + +def register_custom_events(*args, **kwargs): + return ["warning",] + + __plugin_name__ = "Printer Safety Check" __plugin_author__ = "Gina Häußge" __plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/printer_safety_check.html" @@ -188,6 +196,7 @@ __plugin_implementation__ = PrinterSafetyCheckPlugin() __plugin_hooks__ = { "octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received, "octoprint.comm.protocol.firmware.info": __plugin_implementation__.on_firmware_info_received, - "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received + "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received, + "octoprint.events.register_custom_events": register_custom_events } diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 863c67b0b..4b962979c 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -944,17 +944,21 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, target_result = None def trigger_event(success, **additional_payload): + from octoprint.events import Events + if success: - event = "update_succeeded" + # noinspection PyUnresolvedReferences + event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED else: - event = "update_failed" + # noinspection PyUnresolvedReferences + event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED payload = copy.copy(additional_payload) payload.update(dict(target=target, from_version=information["local"]["value"], to_version=target_version)) - self._event_bus.fire("plugin_softwareupdate_{}".format(event), payload=payload) + self._event_bus.fire(event, payload=payload) ### The actual update procedure starts here... @@ -1198,6 +1202,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, return None +def _register_custom_events(*args, **kwargs): + return ["update_succeeded", "update_failed"] + + __plugin_name__ = "Software Update" __plugin_author__ = "Gina Häußge" __plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html" @@ -1220,7 +1228,8 @@ def __plugin_load__(): global __plugin_hooks__ __plugin_hooks__ = { - "octoprint.cli.commands": cli.commands + "octoprint.cli.commands": cli.commands, + "octoprint.events.register_custom_events": _register_custom_events } diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index cf1b79ab5..6d3c7d392 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -111,28 +111,39 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, ##~~ EventHandlerPlugin + # noinspection PyUnresolvedReferences def on_event(self, event, payload): - if event.startswith("plugin_pluginmanager_"): - self._track_plugin_event(event, payload) - elif event.startswith("plugin_softwareupdate_"): - self._track_update_event(event, payload) - elif event in ("plugin_pi_support_throttle_state",): - self._throttle_state = payload - self._track_throttle_event(event, payload) - elif event in ("plugin_printer_safety_check_warning",): - self._track_printer_safety_event(event, payload) - elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED): + if event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED): self._track_printjob_event(event, payload) + elif event in (Events.ERROR,): self._track_commerror_event(event, payload) + elif event in (Events.CONNECTED,): self._printer_connection_parameters = dict(port=payload["port"], baudrate=payload["baudrate"]) self._record_next_firmware_info = True + elif event in (Events.FIRMWARE_DATA,) and self._record_next_firmware_info: self._record_next_firmware_info = False self._track_printer_event(event, payload) + elif hasattr(Events, "PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN") and \ + event in (Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, + Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN): + self._track_plugin_event(event, payload) + + elif hasattr(Events, "PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED") and \ + event in (Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED, Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED): + self._track_update_event(event, payload) + + elif hasattr(Events, "PLUGIN_PI_SUPPORT_THROTTLE_STATE") and event in (Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE,): + self._throttle_state = payload + self._track_throttle_event(event, payload) + + elif hasattr(Events, "PLUGIN_PRINTER_SAFETY_CHECK_WARNING") and event in (Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING,): + self._track_printer_safety_event(event, payload) + ##~~ TemplatePlugin def get_template_configs(self): @@ -211,13 +222,13 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, if not self._settings.get_boolean(["events", "plugin"]): return - if event.endswith("_installplugin"): + if event.endswith("_install_plugin"): self._track("install_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) - elif event.endswith("_uninstallplugin"): + elif event.endswith("_uninstall_plugin"): self._track("uninstall_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) - elif event.endswith("_enableplugin"): + elif event.endswith("_enable_plugin"): self._track("enable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) - elif event.endswith("_disableplugin"): + elif event.endswith("_disable_plugin"): self._track("disable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) def _track_update_event(self, event, payload): diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index f385b9ac1..9a173c76d 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -446,6 +446,17 @@ class Server(object): implementation.on_settings_initialized() + custom_events_hooks = pluginManager.get_hooks("octoprint.events.register_custom_events") + for name, hook in custom_events_hooks.items(): + try: + result = hook() + if isinstance(result, (list, tuple)): + for event in result: + constant, value = octoprint.events.Events.register_event(event, prefix="plugin_{}_".format(name)) + self._logger.debug("Registered event {} of plugin {} as Events.{} = \"{}\"".format(event, name, constant, value)) + except: + self._logger.exception("Error while retrieving custom event list from plugin {}".format(name)) + pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory, settings_plugin_inject_factory] pluginManager.initialize_implementations()