Merge branch 'maintenance' into devel

This commit is contained in:
GitHub Nightly Merge Action committed 2023-12-12 00:12:41 +00:00
commit 80e637de8c
13 files changed
+335 -64

No files matched your search

+98
View File
@@ -1054,6 +1054,65 @@ Retrieve the current SD state
:statuscode 200: No error
:statuscode 404: If SD support has been disabled in OctoPrint's config.
.. _sec-api-printer-error:
Retrieve information about the last error
=========================================
.. http:get:: /api/printer/error
Retrieves information about the last error that occurred on the printer.
Returns a :http:statuscode:`200` with an :ref:`Error Information <sec-api-printer-datamodel-errorinfo>` in the body
upon success.
Requires the ``STATUS`` permission and ``MONITOR_TERMINAL`` to also get access to the last terminal lines associated with the error.
**Example**
Read the last error that occurred on the printer.
.. sourcecode:: http
GET /api/printer/error HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"consequence": "emergency",
"error": "MINTEMP triggered, OMG, kill() called - Not SD printing",
"faq": "firmware-mintemp",
"logs": [
"Send: N2685 G1 X147.748 Y108.411 E627.83763*85",
"Recv: ok",
"Send: N2686 G1 X148.522 Y108.286 E627.8963*98",
"Recv: ok",
"Send: N2687 G1 X148.866 Y108.174 E627.92338*87",
"Recv: ok",
"Send: N2688 G1 X149.494 Y107.868 E627.97566*91",
"Recv: ok",
"Send: N2689 G1 X149.731 Y107.779 E627.9946*96",
"Recv: ok",
"Send: N2690 G1 X149.69 Y108.032 E628.01378*101",
"Recv: ok",
"Send: N2691 G1 X147.252 Y112.252 E628.3785*107",
"Recv: ok",
"Send: N2692 G1 X145.082 Y112.253 E628.54089*93",
"Recv: ok",
"Recv: Error: MINTEMP triggered, kill() called",
"Recv: Not SD printing",
"Changing monitoring state from \"Printing\" to \"Error\""
],
"reason": "firmware"
}
:statuscode 200: No error
.. _sec-api-printer-arbcommand:
Send an arbitrary command to the printer
@@ -1259,3 +1318,42 @@ Custom Controls Response
- 0..n
- List of :ref:`custom controls <sec-features-custom_controls>`
- A list of custom control definitions as defined in ``config.yaml``.
.. _sec-api-printer-datamodel-errorinfo:
Error Information
-----------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``error``
- 1
- String
- The error message, will be empty if no error information is currently present.
* - ``reason``
- 1
- String
- The reason for the error, e.g. ``firmware`` in case of errors triggered by the firmware. Will be empty if no
error information is currently present.
* - ``consequence``
- 0..1
- String
- The consequence of the error, e.g. ``emergency`` if an emergency stop and disconnect was triggered, ``disconnect``
if just a disconnect was triggered, ``cancel`` if the ongoing print job was cancelled. Will be unset if
no consequence was triggered or no error information is currently present.
* - ``faq``
- 0..1
- String
- An FAQ id for the error, to be added to ``https://faq.octoprint.org/`` for a link to the FAQ entry. Will be unset
if no FAQ entry is available for the error or no error information is currently present.
* - ``logs``
- 0..*
- List of String
- A list of log lines that might be relevant for the error. Will be unset if no error information is currently
present or if the requesting user lacks the ``MONITOR_TERMINAL`` permission.
+21 -1
View File
@@ -61,7 +61,7 @@ used for the ``serial.log`` and the ``console`` handler used for the output to s
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
formatter: colored
stream: ext://sys.stdout
# octoprint.log
@@ -81,6 +81,12 @@ used for the ``serial.log`` and the ``console`` handler used for the output to s
maxBytes: 2097152 # 2 * 1024 * 1024 = 2 MB in bytes
filename: /path/to/octoprints/logs/serial.log
.. note::
If OctoPrint is instructed to not color its logging output (e.g. via the ``--no-color`` command
line option or the ``NO_COLOR`` environment variable), the ``colored`` formatter will be replaced
with the ``simple`` formatter.
You can find more information on the used logging handlers in the Python documentation on
:py:mod:`logging.handlers`.
@@ -95,6 +101,20 @@ expressed in YAML as follows:
formatters:
simple:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
colored:
format: "%(log_color)s%(asctime)s - %(name)s - %(levelname)s - %(message)s%(reset)s"
As example, if you want to change the format to include the full file and line number in which the logging statement was issued, you
could redefine the formatters as follows:
.. code-block:: yaml
formatters:
simple:
format: "%(asctime)s - %(name)s - %(pathname)s%(filename)s#%(lineno)d - %(levelname)s - %(message)s"
colored:
format: "%(log_color)s%(asctime)s - %(name)s - %(pathname)s%(filename)s#%(lineno)d - %(levelname)s - %(message)s%(reset)s"
The possible keys for the logging format can be found in the
:ref:`Python documentation on LogRecord attributes <logrecord-attributes>`.
+4 -2
View File
@@ -203,12 +203,14 @@ Error
* ``error``: the error string
* ``reason``: the reason for the error, one of ``firmware``, ``resend``, ``resend_loop``, ``timeout``,
``connection``, ``start_print``, ``autodetect`` or unset.
* ``m112``: whether this error will cause an emergency stop command ``M112`` to be sent to the printer
* ``consequence``: What was done as a consequence of that error. ``emergency`` if an ``M112`` emergency stop was sent
and the connection to the printer closed, ``disconnect`` if the connection was just closed, ``cancel`` if the ongoing
print job was cancelled. Might also be missing if nothing happened as a consequence.
In case of errors with reason ``firmware``, the following additional fields might be present in the payload:
* ``faq``: a link to the FAQ entry for the error
* ``log``: the last lines from the communication log
* ``logs``: the last lines from the communication log
PrinterStateChanged
The state of the printer changed.
+4
View File
@@ -604,6 +604,10 @@ class PrinterInterface:
def firmware_info(self):
raise NotImplementedError()
@property
def error_info(self):
raise NotImplementedError()
class PrinterCallback:
def on_printer_add_log(self, data):
+26
View File
@@ -11,6 +11,7 @@ import logging
import os
import threading
import time
from typing import List
from frozendict import frozendict
@@ -27,6 +28,7 @@ from octoprint.printer import (
UnknownScript,
)
from octoprint.printer.estimation import PrintTimeEstimator
from octoprint.schema import BaseModel
from octoprint.settings import settings
from octoprint.util import InvariantContainer
from octoprint.util import comm as comm
@@ -34,6 +36,14 @@ from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util import to_unicode
class ErrorInformation(BaseModel):
error: str
reason: str
consequence: str = None
faq: str = None
logs: List[str] = None
class Printer(PrinterInterface, comm.MachineComPrintCallback):
"""
Default implementation of the :class:`PrinterInterface`. Manages the communication layer object and registers
@@ -74,6 +84,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._posAfterSelect = None
self._firmware_info = None
self._error_info = None
# sd handling
self._sdPrinting = False
@@ -185,6 +196,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
def firmware_info(self):
return frozendict(self._firmware_info) if self._firmware_info else None
@property
def error_info(self):
return self._error_info.dict() if self._error_info else None
# ~~ handling of PrinterCallbacks
def register_callback(self, callback, *args, **kwargs):
@@ -370,6 +385,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
extra={"plugin": name},
)
self._error_info = None
eventManager().fire(Events.CONNECTING)
self._printerProfileManager.select(profile)
@@ -1506,6 +1523,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setState(state, state_string=state_string, error_string=error_string)
def on_comm_error(self, error, reason, consequence=None, faq=None, logs=None):
# store error info
self._error_info = ErrorInformation(
error=error, reason=reason, consequence=consequence, faq=faq, logs=logs
)
def on_comm_message(self, message):
"""
Callback method for the comm object, called upon message exchanges via serial.
@@ -1584,6 +1607,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self.start_print(pos=self._posAfterSelect, user=user)
def on_comm_print_job_started(self, suppress_script=False, user=None):
# clear error info
self._error_info = None
self._updateJobUser(
user
) # the final job owner should always be whoever _started_ the job
+14
View File
@@ -472,6 +472,20 @@ def _get_temperature_data(preprocessor):
return preprocessor(tempData)
@api.route("/printer/error", methods=["GET"])
@no_firstrun_access
@Permissions.STATUS.require(403)
def getLastPrinterError():
error_info = printer.error_info
if error_info is None:
return jsonify(error="", reason="")
if not Permissions.MONITOR_TERMINAL.can() and "logs" in error_info:
del error_info["logs"]
return jsonify(**error_info)
def _keep_tools(x):
return _delete_from_data(x, lambda k: not k.startswith("tool") and k != "history")
@@ -11,6 +11,7 @@
var bedUrl = url + "/bed";
var chamberUrl = url + "/chamber";
var sdUrl = url + "/sd";
var errorUrl = url + "/error";
var OctoPrintPrinterClient = function (base) {
this.base = base;
@@ -128,6 +129,10 @@
return this.base.get(sdUrl, opts);
};
OctoPrintPrinterClient.prototype.getErrorInfo = function (opts) {
return this.base.get(errorUrl, opts);
};
OctoPrintPrinterClient.prototype.jog = function (params, opts) {
params = params || {};
@@ -338,45 +338,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
{error: _.escape(payload.error)}
);
const modal = $("#firmwareErrorModal");
if (modal.length) {
$("#firmwareErrorModalError", modal).text(payload.error);
if (payload.m112) {
$("#firmwareErrorModalDisconnect", modal).hide();
$("#firmwareErrorModalM112", modal).show();
} else {
$("#firmwareErrorModalDisconnect", modal).show();
$("#firmwareErrorModalM112", modal).hide();
}
if (payload.faq) {
$("#firmwareErrorModalFaq a", modal).attr(
"href",
"https://faq.octoprint.org/" + payload.faq
);
$("#firmwareErrorModalFaq", modal).show();
} else {
$("#firmwareErrorModalFaq", modal).hide();
}
const log = $("#firmwareErrorModalLog", modal);
if (payload.log) {
log.empty();
_.each(payload.log, (line) => {
log.append(
'<span class="line">' +
_.escape(line) +
"\n" +
"</span>"
);
});
}
modal.modal("show");
log.scrollTop(log.prop("scrollHeight"));
}
break;
}
case "resend":
@@ -97,6 +97,9 @@ $(function () {
self.currentHeight = ko.observable(undefined);
self.errorInfoAvailable = ko.observable(false);
self.errorInfo = {};
self.TITLE_PRINT_BUTTON_PAUSED = gettext(
"Restarts the print job from the beginning"
);
@@ -499,7 +502,108 @@ $(function () {
}
};
self.onAllBound = function (allViewModels) {
self.showFirmwareErrorModal = (data) => {
if (!data) {
data = self.errorInfo;
}
if (!data) return;
const modal = $("#firmwareErrorModal");
if (!modal.length) return;
$("#firmwareErrorModalError", modal).text(data.error);
switch (data.consequence) {
case "emergency": {
$("#firmwareErrorModalM112", modal).show();
$("#firmwareErrorModalDisconnect", modal).hide();
$("#firmwareErrorModalCancel", modal).hide();
break;
}
case "disconnect": {
$("#firmwareErrorModalM112", modal).hide();
$("#firmwareErrorModalDisconnect", modal).show();
$("#firmwareErrorModalCancel", modal).hide();
break;
}
case "cancel": {
$("#firmwareErrorModalM112", modal).hide();
$("#firmwareErrorModalDisconnect", modal).hide();
$("#firmwareErrorModalCancel", modal).show();
break;
}
default: {
$("#firmwareErrorModalM112", modal).hide();
$("#firmwareErrorModalDisconnect", modal).hide();
$("#firmwareErrorModalCancel", modal).hide();
break;
}
}
if (data.faq) {
$("#firmwareErrorModalFaq a", modal).attr(
"href",
"https://faq.octoprint.org/" + data.faq
);
$("#firmwareErrorModalFaq", modal).show();
} else {
$("#firmwareErrorModalFaq", modal).hide();
}
const logs = $("#firmwareErrorModalLogs", modal);
const logOutput = $("#firmwareErrorModalLogsOutput", logs);
if (data.logs) {
logOutput.empty();
_.each(data.logs, (line) => {
logOutput.append(
'<span class="line">' + _.escape(line) + "\n" + "</span>"
);
});
logs.show();
} else {
logs.hide();
}
modal.modal("show");
logOutput.scrollTop(logOutput.prop("scrollHeight"));
};
self.requestErrorInfo = () => {
OctoPrint.printer.getErrorInfo().then((data) => {
if (data && data.error && data.error !== "") {
self.errorInfoAvailable(true);
self.errorInfo = data;
} else {
self.errorInfoAvailable(false);
self.errorInfo = {};
}
});
};
self.onEventError = (payload) => {
if (payload.reason === "firmware") {
self.errorInfo = payload;
self.errorInfoAvailable(true);
self.showFirmwareErrorModal();
}
};
self.onEventConnecting =
self.onEventPrintCancelling =
self.onEventPrintStarted =
() => {
self.requestErrorInfo();
};
self.onUserPermissionsChanged =
self.onUserLoggedIn =
self.onUserLoggedOut =
() => {
self.requestErrorInfo();
};
self.onAllBound = (allViewModels) => {
self.allViewModels = allViewModels;
};
}
@@ -8,25 +8,30 @@
Your printer's firmware reported an error:
{% endtrans %}</p>
<p style="text-align: center"><strong class="text-error" id="firmwareErrorModalError"></strong></p>
<p id="firmwareErrorModalDisconnect">{% trans %}
Due to this error, OctoPrint was not able to continue to communicate with your printer and
disconnected.
{% endtrans %}</p>
<p id="firmwareErrorModalM112">{% trans %}
Due to this error, OctoPrint was not able to continue to communicate with your printer and
sent an emergency stop command <code>M112</code> to ensure all heaters are turned off, then disconnected.
{% endtrans %}</p>
<p id="firmwareErrorModalDisconnect">{% trans %}
Due to this error, OctoPrint was not able to continue to communicate with your printer and
had to disconnect.
{% endtrans %}</p>
<p id="firmwareErrorModalCancel">{% trans %}
Due to this error, OctoPrint cancelled the ongoing print job.
{% endtrans %}</p>
<p id="firmwareErrorModalFaq">{% trans %}
You might be able to find more information on this error and how to solve it
<a target="_blank" rel="noreferrer noopener">in this FAQ entry</a>!
{% endtrans %}</p>
<p>{% trans %}
Here's the last communication with your printer before this error occurred:
{% endtrans %}</p>
<pre id="firmwareErrorModalLog" class="pre-scrollable pre-output" style="min-height: 200px; max-height: 200px"></pre>
<p><strong>{% trans %}
This error is not caused by OctoPrint, it is a problem that was reported by your printer's firmware to which OctoPrint reacted!
{% endtrans %}</strong></p>
<div id="firmwareErrorModalLogs">
<p>{% trans %}
Here's the last communication with your printer before this error occurred:
{% endtrans %}</p>
<pre id="firmwareErrorModalLogsOutput" class="pre-scrollable pre-output" style="min-height: 200px; max-height: 200px"></pre>
<p><strong>{% trans %}
This error is not caused by OctoPrint, it is a problem that was reported by your printer's firmware to which OctoPrint reacted!
{% endtrans %}</strong></p>
</div>
</div>
<div class="modal-footer">
<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</a>
+1 -1
View File
@@ -1,4 +1,4 @@
<span title="{{ _('Current printer state')|edq }}">{{ _('State') }}</span>: <strong data-test-id="state-string" data-bind="text: stateString"></strong><br>
<span title="{{ _('Current printer state')|edq }}">{{ _('State') }}</span>: <strong data-test-id="state-string" data-bind="text: stateString"></strong> <a href="javascript:void(0)" class="text-error" data-bind="visible: errorInfoAvailable, click: function() { showFirmwareErrorModal() }"><i class="fas fa-exclamation-circle"></i></a><br>
<span data-bind="visible: hasErrorString" class="text-error"><span data-test-id="error-string" data-bind="text: errorString"></span><br></span>
<span data-bind="visible: isOperational"><span title="{{ _('Count of resend requests, transmitted lines and resend ratio')|edq }}">{{ _('Resend ratio') }}</span>: <strong data-bind="css: {'text-error': resendRatioCritical}"><span title="{{ _('resend requests') | edq }}" data-bind="text: formatHuman(resendCount())"></span> / <span title="{{ _('transmitted lines') | edq }}" data-bind="text: formatHuman(resendTotalTransmitted())"></span> (<span title="{{ _('resend ratio') }}" data-bind="text: resendRatio"></span>%) <a href="https://faq.octoprint.org/communication-errors" target="_blank" class="text-error" data-bind="visible: resendRatioCritical"><i class="fas fa-question-circle"></i></a></strong><br></span>
<hr>
+40 -9
View File
@@ -4053,7 +4053,20 @@ class MachineCom:
map(lambda x: x in lower_line, self._fatal_errors)
):
self._trigger_error(stripped_error, "firmware")
elif self.isPrinting():
consequence = "cancel"
payload = self._payload_for_error(
"firmware", consequence=consequence, error=stripped_error
)
self._callback.on_comm_error(
stripped_error,
"firmware",
consequence=consequence,
faq=payload.get("faq"),
logs=payload.get("logs"),
)
self.cancelPrint(firmware_error=stripped_error)
self._clear_to_send.set()
@@ -4079,7 +4092,21 @@ class MachineCom:
and reason not in ("connection", "autodetect")
)
payload = self._payload_for_error(reason, close and trigger_m112)
if close and trigger_m112:
consequence = "emergency"
elif close:
consequence = "disconnect"
else:
consequence = None
payload = self._payload_for_error(reason, consequence=consequence)
self._callback.on_comm_error(
text,
reason,
consequence=consequence,
faq=payload.get("faq"),
logs=payload.get("logs"),
)
eventManager().fire(Events.ERROR, payload)
if close:
@@ -4100,16 +4127,17 @@ class MachineCom:
),
}
def _payload_for_error(self, reason, trigger_m112):
error = self.getErrorString()
payload = {
"error": error,
"reason": reason,
"m112": trigger_m112,
}
def _payload_for_error(self, reason, consequence=None, error=None):
if error is None:
error = self.getErrorString()
payload = {"error": error, "reason": reason}
if consequence:
payload["consequence"] = consequence
if reason == "firmware":
payload["log"] = list(self._terminal_log)
payload["logs"] = list(self._terminal_log)
error_lower = error.lower()
for faq, triggers in self._error_faqs.items():
@@ -5657,6 +5685,9 @@ class MachineComPrintCallback:
def on_comm_message(self, message):
pass
def on_comm_error(self, error, reason, consequence=None, faq=None, logs=None):
pass
def on_comm_progress(self):
pass
+1
View File
@@ -36,6 +36,7 @@ class TestCommErrorHandling(unittest.TestCase):
self._comm._clear_to_send = mock.Mock()
self._comm._error_message_hooks = {}
self._comm._trigger_emergency_stop = mock.Mock()
self._comm._callback = mock.Mock()
# settings
self._comm._ignore_errors = False