Extract firmware safety check into bundled plugin

This commit is contained in:
Gina Häußge committed 2018-03-19 13:22:59 +01:00
1 parent 8cdae335a2
commit 8a3a87efac
15 files changed
+275 -81

No files matched your search

+1
View File
@@ -11,4 +11,5 @@ Bundled Plugins
discovery.rst
logging.rst
pluginmanager.rst
printer_safety_check.rst
softwareupdate.rst
@@ -0,0 +1,43 @@
.. _sec-bundledplugins-printer_safety_check:
Printer Safety Check
====================
The Printer Safety Check plugin comes bundled with OctoPrint starting with version 1.3.7.
It tries to identify printers or rather printer firmwares with known safety issues, such as
disabled thermal runaway protection, and displays a warning box to logged in users on
such identification.
.. _fig-bundledplugins-printer_safety_check-example:
.. figure:: ../images/bundledplugins-printer_safety_check-example.png
:align: center
:alt: Printer Safety Check warning example
An example of a warning generated by the Printer Safety Check
Currently the following firmwares produce this warning:
* Anet A8 stock firmware
If you know of further printers/printer firmwares that need to be added here, please
`get in touch on the forum and provide their response to an M115 <https://faq.octoprint.org/warning-firmware-unsafe>`_.
.. seealso::
`Entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
.. note::
Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though
that even if your printer might be running totally fine with a known unsafe configuration, that might change
unexpectedly and with `catastrophic <https://www.thissmarthouse.net/dont-burn-your-house-down-3d-printing-a-cautionary-tale/>`_
`results <https://www.reddit.com/r/3Dprinting/comments/6cekgk/house_fire_thanks_to_cheap_printer_from_china/>`_.
.. _sec-bundledplugins-printer_safety_check-source:
Source Code
-----------
The source of the Printer Safety Check plugin is bundled with OctoPrint and can be
found in its source repository under ``src/octoprint/plugins/printer_safety_check``.
+1
View File
@@ -88,6 +88,7 @@ class Events(object):
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
FIRMWARE_DATA = "FirmwareData"
TOOL_CHANGE = "ToolChange"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
@@ -0,0 +1,110 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__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.events import Events
from octoprint.server import user_permission
import flask
from flask_babel import gettext
import textwrap
TERMINAL_SAFETY_WARNING = """
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
{message}
Learn more at https://faq.octoprint.org/warning-{warning_type}
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
"""
SAFETY_CHECKS = {
"firmware-unsafe": (lambda name, data: name and name.lower().startswith("anet_a8_"),)
}
class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
# noinspection PyMissingConstructor
def __init__(self):
self._warnings = dict()
##~~ TemplatePlugin API
def get_template_configs(self):
return [
dict(type="sidebar",
name=gettext("Printer Safety Warning"),
data_bind="visible: printerState.isOperational() && loginState.isAdmin() && warnings().length > 0",
icon="exclamation-triangle",
styles_wrapper=["display: none"])
]
##~~ AssetPlugin API
def get_assets(self):
return dict(js=("js/printer_safety_check.js",),
css=("css/printer_safety_check.css",),
less=("less/printer_safety_check.less",))
##~~ EventHandlerPlugin API
def on_event(self, event, payload):
if event == Events.FIRMWARE_DATA:
self._analyze_firmware_data(payload.get("name"), payload.get("data"))
elif event == Events.DISCONNECTED:
self._reset_warnings()
##~~ SimpleApiPlugin API
def on_api_get(self, request):
if not user_permission.can():
return flask.make_response("Insufficient rights", 403)
return flask.jsonify(self._warnings)
##~~ Helpers
def _analyze_firmware_data(self, name, data):
changes = False
for warning_type, checks in SAFETY_CHECKS.items():
if any(x(name, data) for x in checks):
message = u"Your printer's firmware is known to lack mandatory safety features (e.g. " \
u"thermal runaway protection). This is a fire risk."
self._log_to_terminal(TERMINAL_SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)),
warning_type=warning_type))
self._warnings[warning_type] = message
changes = True
if changes:
self._ping_clients()
def _reset_warnings(self):
self._warnings.clear()
self._ping_clients()
def _log_to_terminal(self, message):
if self._printer:
lines = message.split("\n")
self._printer.log_lines(*lines)
def _ping_clients(self):
self._plugin_manager.send_plugin_message(self._identifier, dict(type="update"))
__plugin_name__ = "Printer Safety Check"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/printer_safety_check.html"
__plugin_description__ = "Checks for unsafe printers/printer firmwares"
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
"check if the printer it is connected to has a known safety"
"issue and inform you about that fact.")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = PrinterSafetyCheckPlugin()
@@ -0,0 +1 @@
#sidebar_plugin_printer_safety_check_wrapper{border:1px solid #b94a48}#sidebar_plugin_printer_safety_check_wrapper .accordion-heading{background-color:#b94a48;font-weight:700;color:#fff}#sidebar_plugin_printer_safety_check_wrapper .accordion-heading .icon-black,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a:active,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a:hover,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a:visited{color:#fff}
@@ -0,0 +1,78 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintPrinterSafetyCheckClient = function(base) {
this.base = base;
};
OctoPrintPrinterSafetyCheckClient.prototype.get = function(opts) {
return this.base.get(this.base.getSimpleApiUrl("printer_safety_check"), opts);
};
OctoPrintClient.registerPluginComponent("printer_safety_check", OctoPrintPrinterSafetyCheckClient);
return OctoPrintPrinterSafetyCheckClient;
});
$(function() {
function PrinterSafetyCheckViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.printerState = parameters[1];
self.warnings = ko.observableArray([]);
self.requestData = function() {
if (!self.loginState.isUser()) {
self.warnings([]);
return;
}
OctoPrint.plugins.printer_safety_check.get()
.done(self.fromResponse)
.fail(function() {
self.warnings([]);
});
};
self.fromResponse = function(data) {
var warnings = [];
_.each(data, function(message, warning_type) {
warnings.push({type: warning_type, message: message});
});
self.warnings(warnings);
};
self.onStartup = function() {
self.requestData();
};
self.onUserLoggedIn = function() {
self.requestData();
};
self.onUserLoggedOut = function() {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (plugin !== "printer_safety_check") return;
if (!data.hasOwnProperty("type")) return;
if (data.type === "update") {
self.requestData();
}
}
}
OCTOPRINT_VIEWMODELS.push({
construct: PrinterSafetyCheckViewModel,
dependencies: ["loginStateViewModel", "printerStateViewModel"],
elements: ["#sidebar_plugin_printer_safety_check_wrapper"]
});
});
@@ -0,0 +1,15 @@
#sidebar_plugin_printer_safety_check_wrapper {
border: 1px solid #b94a48;
.accordion-heading {
background-color: #b94a48;
font-weight: bold;
color: #fff;
a, a:hover, a:visited, a:active {
color: #fff;
}
.icon-black {
color: #fff;
}
}
}
@@ -0,0 +1,7 @@
<p><strong>{{ _('Warning!') }}</strong></p>
<!-- ko foreach: warnings -->
<p class="printer_safety_warning">
<span data-bind="text: message"></span><br>
<a target="_blank" rel="noreferrer noopener" data-bind="attr: {href: 'https://faq.octoprint.org/warning-' + type}">{{ _('Learn more...') }}</a>
</p>
<!-- /ko -->
+8
View File
@@ -430,6 +430,14 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def log_lines(self, *lines):
"""
Logs the provided lines to the printer log and serial.log
Args:
*lines: the lines to log
"""
pass
def get_state_string(self, *args, **kwargs):
"""
Returns:
+9 -15
View File
@@ -120,8 +120,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
printTimeLeft=None,
printTimeOrigin=None),
current_z=None,
offsets=self._dict(),
warnings=self._dict()
offsets=self._dict()
)
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self._on_event_MetadataAnalysisFinished)
@@ -532,6 +531,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# for further processing
self._comm.cancelPrint(tags=kwargs.get("tags", set()) | {"trigger:printer.cancel_print"})
def log_lines(self, *lines):
serial_logger = logging.getLogger("SERIAL")
self.on_comm_log("\n".join(lines))
for line in lines:
serial_logger.debug(line)
def get_state_string(self, state=None, *args, **kwargs):
if self._comm is None:
return "Offline"
@@ -1067,7 +1072,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._setOffsets(None)
self._stateMonitor.set_warnings(None)
self._addTemperatureData()
self._printerProfileManager.deselect()
eventManager().fire(Events.DISCONNECTED)
@@ -1256,9 +1260,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
except:
self._logger.exception("Error while trying to persist print recovery data")
def on_comm_set_warnings(self, warnings):
self._stateMonitor.set_warnings(self._dict(warnings))
def _payload_for_print_job_event(self, location=None, print_job_file=None, print_job_size=None, position=None):
if print_job_file is None:
with self._selectedFileMutex:
@@ -1315,7 +1316,6 @@ class StateMonitor(object):
self._current_z = None
self._offsets = dict()
self._progress = None
self._warnings = dict()
self._progress_dirty = False
@@ -1333,13 +1333,12 @@ class StateMonitor(object):
return self._on_get_progress()
return self._progress
def reset(self, state=None, job_data=None, progress=None, current_z=None, offsets=None, warnings=None):
def reset(self, state=None, job_data=None, progress=None, current_z=None, offsets=None):
self.set_state(state)
self.set_job_data(job_data)
self.set_progress(progress)
self.set_current_z(current_z)
self.set_temp_offsets(offsets)
self.set_warnings(warnings)
def add_temperature(self, temperature):
self._on_add_temperature(temperature)
@@ -1353,10 +1352,6 @@ class StateMonitor(object):
self._on_add_message(message)
self._change_event.set()
def set_warnings(self, warnings):
self._warnings = warnings
self._change_event.set()
def set_current_z(self, current_z):
self._current_z = current_z
self._change_event.set()
@@ -1414,8 +1409,7 @@ class StateMonitor(object):
"job": self._job_data,
"currentZ": self._current_z,
"progress": self._progress,
"offsets": self._offsets,
"warnings": self._warnings
"offsets": self._offsets
}
+1 -1
View File
@@ -280,7 +280,7 @@ default_settings = {
"components": {
"order": {
"navbar": ["settings", "systemmenu", "plugin_announcements", "login"],
"sidebar": ["connection", "state", "files"],
"sidebar": ["plugin_printer_safety_check", "connection", "state", "files"],
"tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"],
"settings": [
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
@@ -39,8 +39,6 @@ $(function() {
self.sd = ko.observable(undefined);
self.timelapse = ko.observable(undefined);
self.warnings = ko.observableArray([]);
self.busyFiles = ko.observableArray([]);
self.filament = ko.observableArray([]);
@@ -187,7 +185,6 @@ $(function() {
self._processProgressData(data.progress);
self._processZData(data.currentZ);
self._processBusyFiles(data.busyFiles);
self._processWarnings(data.warnings);
};
self._processStateData = function(data) {
@@ -275,14 +272,6 @@ $(function() {
self.busyFiles(busyFiles);
};
self._processWarnings = function(data) {
var warnings = [];
_.each(data, function(message, key) {
warnings.push({type: key, message: message});
});
self.warnings(warnings);
};
self.print = function() {
if (self.isPaused()) {
showConfirmationDialog({
-23
View File
@@ -638,29 +638,6 @@ ul.dropdown-menu li a {
hr {
margin: 5px 0;
}
.alert {
margin-bottom: 5px;
a {
text-decoration: underline;
}
}
.alert a {
color: #c09853;
}
.alert-error a,
.alert-danger a {
color: #b94a48;
}
.alert-success a {
color: #468847;
}
.alert-info a {
color: #3a87ad;
}
}
/** GCODE file manager */
@@ -1,10 +1,3 @@
<div data-bind="visible: warnings().length > 0 && isOperational(), foreach: warnings" style="display: none">
<div class="alert alert-danger">
<strong>{{ _('Warning!') }}</strong>
<span data-bind="text: message"></span><br>
<a target="_blank" rel="noreferrer noopener" data-bind="attr: {href: 'https://faq.octoprint.org/warning-' + type}">{{ _('Learn more...') }}</a>
</div>
</div>
<span title="{{ _('Current printer state') }}">{{ _('State') }}</span>: <strong data-bind="text: stateString"></strong><br>
<hr>
<span title="{{ _('Name of file currently selected for printing') }}">{{ _('File') }}</span>: <strong data-bind="text: filedisplay, attr: {title: filepath}"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
+1 -24
View File
@@ -19,7 +19,6 @@ except ImportError:
from past.builtins import basestring
import logging
import textwrap
import serial
@@ -199,16 +198,6 @@ regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):")
regex_resend_linenumber = re.compile("(N|N:)?(?P<n>%s)" % regex_int_pattern)
"""Regex to use for request line numbers in resend requests"""
SAFETY_WARNING = """
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
{message}
Learn more at https://faq.octoprint.org/warning-{key}
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
"""
def serialList():
baselist=[]
if os.name=="nt":
@@ -444,8 +433,6 @@ class MachineCom(object):
self._toolBeforeHeatup = None
self._knownInvalidTools = set()
self._warnings = dict()
self._long_running_command = False
self._heating = False
self._dwelling_until = False
@@ -1691,14 +1678,7 @@ class MachineCom(object):
if name and "malyan" in name.lower() and ver:
firmware_name = name.strip() + " " + ver.strip()
# special handling for dangerous firmware without obligatory safety features
if firmware_name and firmware_name.lower().startswith("anet_a8"):
key = "firmware-unsafe"
message = "Your printer's firmware is known to lack mandatory safety features (e.g. " \
"thermal runaway protection). This is a fire risk."
self._log(SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)), key=key))
self._warnings[key] = message
self._callback.on_comm_set_warnings(self._warnings)
eventManager().fire(Events.FIRMWARE_DATA, dict(name=firmware_name, data=data))
if not self._firmware_info_received and firmware_name:
firmware_name = firmware_name.strip()
@@ -3392,9 +3372,6 @@ class MachineComPrintCallback(object):
def on_comm_record_fileposition(self, origin, name, pos):
pass
def on_comm_set_warnings(self, warnings):
pass
### Printing file information classes ##################################################################################
class PrintingFileInformation(object):