♻️ Extract PiSupport plugin into own repo

This commit is contained in:
Gina Häußge committed 2021-03-26 16:46:54 +01:00
1 parent 84373a7617
commit 631085f78f
14 files changed
+3 -936

No files matched your search

+2 -1
View File
@@ -24,8 +24,9 @@ SETUP_REQUIRES = ["markdown>=3.1,<3.2"] # newer versions require Python 3
# Requirements for our application
INSTALL_REQUIRES = [
# additional OctoPrint plugins that are maintained on a different release cycle
"OctoPrint-FileCheck>=2020.8.7",
"OctoPrint-FirmwareCheck>=2021.2.4",
"OctoPrint-FileCheck>=2020.08.07",
"OctoPrint-PiSupport>=2021.3.26",
# the following dependencies are non trivial to update since later versions
# introduce backwards incompatible changes that might affect plugins, or due to
# other observed problems
+1 -1
View File
@@ -110,7 +110,7 @@ def plugin_manager(
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
if plugin_considered_bundled is None:
plugin_considered_bundled = ["firmware_check", "file_check"]
plugin_considered_bundled = ["firmware_check", "file_check", "pi_support"]
if plugin_validators is None:
plugin_validators = [_validate_plugin]
@@ -1,463 +0,0 @@
# -*- 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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import io
import os
import flask
import sarge
from flask_babel import gettext
import octoprint.events
import octoprint.plugin
from octoprint.access.groups import USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.util import RepeatedTimer
from octoprint.util.platform import CLOSE_FDS
_PROC_DT_MODEL_PATH = "/proc/device-tree/model"
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
_VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled"
_CHECK_INTERVAL_OK = 300
_CHECK_INTERVAL_THROTTLED = 30
__LOCAL_DEBUG = os.path.exists(
os.path.realpath(os.path.join(os.path.dirname(__file__), ".local_debug"))
)
if __LOCAL_DEBUG:
### mocks & settings for local debugging
import sys
base = os.path.realpath(
os.path.join(
os.path.dirname(__file__),
"..",
"..",
"..",
"..",
"tests",
"plugins",
"pi_support",
"fakes",
)
)
_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
_VCGENCMD_THROTTLE = "{} {}".format(
sys.executable, os.path.join(base, "fake_vcgencmd.py")
)
import itertools
_VCGENCMD_OUTPUT = itertools.chain(
iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005")
)
_CHECK_INTERVAL_OK = 10
_CHECK_INTERVAL_THROTTLED = 5
# see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790
_FLAG_UNDERVOLTAGE = 1 << 0
_FLAG_FREQ_CAPPED = 1 << 1
_FLAG_THROTTLED = 1 << 2
_FLAG_PAST_UNDERVOLTAGE = 1 << 16
_FLAG_PAST_FREQ_CAPPED = 1 << 17
_FLAG_PAST_THROTTLED = 1 << 18
class ThrottleState(object):
@classmethod
def from_value(cls, value=0):
if value == 0:
return ThrottleState(raw_value=value)
kwargs = {
"undervoltage": _FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE,
"freq_capped": _FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED,
"throttled": _FLAG_THROTTLED & value == _FLAG_THROTTLED,
"past_undervoltage": _FLAG_PAST_UNDERVOLTAGE & value
== _FLAG_PAST_UNDERVOLTAGE,
"past_freq_capped": _FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
"past_throttled": _FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED,
"raw_value": value,
}
return ThrottleState(**kwargs)
def __init__(self, **kwargs):
self._raw_value = kwargs.get("raw_value", -1)
self._undervoltage = False
self._freq_capped = False
self._throttled = False
self._past_undervoltage = False
self._past_freq_capped = False
self._past_throttled = False
for key, value in kwargs.items():
local_key = "_{}".format(key)
if hasattr(self, local_key) and isinstance(value, bool):
setattr(self, local_key, value)
@property
def undervoltage(self):
return self.current_undervoltage or self.past_undervoltage
@property
def current_undervoltage(self):
return self._undervoltage
@property
def past_undervoltage(self):
return self._past_undervoltage
@property
def overheat(self):
return self.current_overheat or self.past_overheat
@property
def current_overheat(self):
return self._freq_capped
@property
def past_overheat(self):
return self._past_freq_capped
@property
def issue(self):
return self.current_issue or self.past_issue
@property
def current_issue(self):
return self._undervoltage or self._freq_capped or self._throttled
@property
def past_issue(self):
return self._past_undervoltage or self._past_freq_capped or self._past_throttled
@property
def raw_value(self):
return self._raw_value
@property
def raw_value_hex(self):
return "0x{:X}".format(self._raw_value)
def __eq__(self, other):
if not isinstance(other, ThrottleState):
return False
return (
self._undervoltage == other._undervoltage
and self._freq_capped == other._freq_capped
and self._throttled == other._throttled
and self._past_undervoltage == other._past_undervoltage
and self._past_freq_capped == other._past_freq_capped
and self._past_throttled == other._past_throttled
and self._raw_value == other._raw_value
)
def as_dict(self):
return {
"raw_value": self._raw_value,
"current_undervoltage": self.current_undervoltage,
"past_undervoltage": self.past_undervoltage,
"current_overheat": self.current_overheat,
"past_overheat": self.past_overheat,
"current_issue": self.current_issue,
"past_issue": self.past_issue,
}
_proc_dt_model = None
def get_proc_dt_model():
global _proc_dt_model
if _proc_dt_model is None:
with io.open(_PROC_DT_MODEL_PATH, "rt", encoding="utf-8") as f:
_proc_dt_model = f.readline().strip(" \t\r\n\0")
return _proc_dt_model
def get_vcgencmd_throttled_state(command):
if __LOCAL_DEBUG:
output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging
else:
output = sarge.get_stdout(command, close_fds=CLOSE_FDS)
if "throttled=0x" not in output:
raise ValueError('cannot parse "{}" output: {}'.format(command, output))
value = output[len("throttled=") :].strip(" \t\r\n\0")
value = int(value, 0)
return ThrottleState.from_value(value)
def is_octopi():
return os.path.exists(_OCTOPI_VERSION_PATH)
_octopi_version = None
def get_octopi_version():
global _octopi_version
if _octopi_version is None:
with io.open(_OCTOPI_VERSION_PATH, "rt", encoding="utf-8") as f:
_octopi_version = f.readline().strip(" \t\r\n\0")
return _octopi_version
class PiSupportPlugin(
octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.SettingsPlugin,
):
# noinspection PyMissingConstructor
def __init__(self):
self._throttle_state = ThrottleState()
self._throttle_check = None
self._throttle_undervoltage = False
self._throttle_overheat = False
self._throttle_functional = True
# Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "STATUS",
"name": "Status",
"description": gettext(
"Allows to check for the Pi's throttling status and environment info"
),
"roles": ["check"],
"default_groups": [USER_GROUP],
}
]
# ~~ EnvironmentDetectionPlugin
def get_additional_environment(self):
result = {"model": get_proc_dt_model()}
self._check_throttled_state()
if self._throttle_functional:
result["throttle_state"] = self._throttle_state.raw_value_hex
if is_octopi():
result["octopi_version"] = get_octopi_version()
return result
# ~~ SimpleApiPlugin
def on_api_get(self, request):
if not Permissions.PLUGIN_PI_SUPPORT_STATUS.can():
return flask.abort(403)
environment = self.get_additional_environment()
result = {
"throttle_state": self._throttle_state.as_dict(),
"model_unrecommended": "zero" in environment.get("model").lower(),
}
result.update(environment)
return flask.jsonify(**result)
# ~~ AssetPlugin
def get_assets(self):
return {
"js": ["js/pi_support.js"],
"clientjs": ["clientjs/pi_support.js"],
"css": ["css/pi_support.css"],
}
# ~~ TemplatePlugin
def get_template_configs(self):
configs = [
{
"type": "settings",
"name": gettext("Pi Support"),
"template": "pi_support_settings.jinja2",
"custom_bindings": False,
}
]
if is_octopi():
configs.append(
{
"type": "about",
"name": "About OctoPi",
"template": "pi_support_about_octopi.jinja2",
}
)
return configs
def get_template_vars(self):
return self.get_additional_environment()
# ~~ StartupPlugin
def on_startup(self, *args, **kwargs):
if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]):
self._check_throttled_state()
self._throttle_check = RepeatedTimer(
self._check_throttled_state_interval,
self._check_throttled_state,
condition=self._check_throttled_state_condition,
)
self._throttle_check.start()
# ~~ SettingsPlugin
def get_settings_defaults(self):
return {
"vcgencmd_throttle_check_enabled": True,
"vcgencmd_throttle_check_command": _VCGENCMD_THROTTLE,
"ignore_unrecommended_model": False,
}
def get_settings_restricted_paths(self):
return {
"admin": [
["vcgencmd_throttle_check_enabled"],
["vcgencmd_throttle_check_command"],
]
}
# ~~ Helpers
def _check_throttled_state_interval(self):
if self._throttle_state.current_issue:
return _CHECK_INTERVAL_THROTTLED
else:
return _CHECK_INTERVAL_OK
def _check_throttled_state_condition(self):
return self._throttle_functional
def get_throttle_state(self, run_now=False):
"""Exposed as public helper."""
if run_now:
self._check_throttled_state()
if not self._throttle_functional:
return False
return self._throttle_state.as_dict()
def _check_throttled_state(self):
command = self._settings.get(["vcgencmd_throttle_check_command"])
self._logger.debug('Retrieving throttle state via "{}"'.format(command))
try:
state = get_vcgencmd_throttled_state(command)
except ValueError:
self._logger.warning(
'Fetching the current throttle state via "{}" doesn\'t work'.format(
command
)
)
self._throttle_functional = False
return
if self._throttle_state == state:
# no change
return
self._throttle_state = state
if (not self._throttle_undervoltage and self._throttle_state.undervoltage) or (
not self._throttle_overheat and self._throttle_state.overheat
):
message = (
"This Raspberry Pi is reporting problems that might lead to bad performance or errors caused "
"by overheating or insufficient power."
)
if self._throttle_state.undervoltage:
self._throttle_undervoltage = True
message += (
"\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are "
"capable of supplying enough voltage and current to your Pi."
)
if self._throttle_state.overheat:
self._throttle_overheat = True
message += (
"\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's "
"CPU and GPU."
)
self._logger.warning(message)
self._plugin_manager.send_plugin_message(
self._identifier,
{"type": "throttle_state", "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"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides additional information about your Pi in the UI."
__plugin_disabling_discouraged__ = gettext(
"Without this plugin OctoPrint will no longer be able to "
"provide additional information about your Pi, "
"which will make it more tricky to help you if you need support."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
def __plugin_check__():
try:
proc_dt_model = get_proc_dt_model()
if proc_dt_model is None:
return False
except Exception:
return False
return "raspberry pi" in proc_dt_model.lower()
def __plugin_load__():
plugin = PiSupportPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.events.register_custom_events": register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
global __plugin_helpers__
__plugin_helpers__ = {"get_throttled": plugin.get_throttle_state}
@@ -1,18 +0,0 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function (OctoPrintClient) {
var OctoPrintPiSupportClient = function (base) {
this.base = base;
};
OctoPrintPiSupportClient.prototype.get = function (opts) {
return this.base.get(this.base.getSimpleApiUrl("pi_support"));
};
OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient);
return OctoPrintPiSupportClient;
});
@@ -1,8 +0,0 @@
#octopi_support_footer {
white-space: nowrap;
}
.pi_support_state_pulsate {
animation: pulsate 1s ease-out;
animation-iteration-count: infinite;
}
@@ -1,172 +0,0 @@
$(function () {
function PiSupportViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.access = parameters[1];
self.settings = parameters[2];
self.model = ko.observable();
self.currentUndervoltage = ko.observable(false);
self.currentOverheat = ko.observable(false);
self.pastUndervoltage = ko.observable(false);
self.pastOverheat = ko.observable(false);
self.currentIssue = ko.observable(false);
self.pastIssue = ko.observable(false);
self.requestData = function () {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_PI_SUPPORT_STATUS
)
) {
return;
}
OctoPrint.plugins.pi_support.get().done(function (response) {
// Raspberry Pi model
self.model(response.model);
// Unrecommended model
if (
response.model_unrecommended &&
!self.settings.settings.plugins.pi_support.ignore_unrecommended_model()
) {
var warning = gettext(
"OctoPrint does not and never has supported the " +
"RPi Zero or Zero W. Use at least a Raspberry Pi 3, or " +
"risk bad performance and failed prints."
);
var faq = gettext(
"" +
'You can read more <a href="%(url)s" target="_blank">in the FAQ</a>.'
);
var remove = gettext(
"You can disable this message via Settings > " +
"Pi Support > Ignore warning on unsupported hardware"
);
new PNotify({
title: gettext("Unsupported hardware detected"),
text:
"<p>" +
warning +
"</p><p>" +
_.sprintf(faq, {
url: "https://faq.octoprint.org/recommended-hardware"
}) +
"</p><p>" +
"<small>" +
remove +
"</small></p>",
type: "error",
hide: false
});
}
// Throttle state
self.fromThrottleState(response.throttle_state);
// OctoPi version
$("#pi_support_footer").remove();
if (!response.octopi_version) return;
var octoPiVersion = $(
"<li id='pi_support_footer'><small>" +
gettext("OctoPi") +
" " +
"<span class='octopi_version'>" +
response.octopi_version +
"</span></small></li>"
);
$("#footer_version").append(octoPiVersion);
});
};
self.fromThrottleState = function (state) {
self.currentUndervoltage(state.current_undervoltage);
self.pastUndervoltage(state.past_undervoltage);
self.currentOverheat(state.current_overheat);
self.pastOverheat(state.past_overheat);
self.currentIssue(state.current_issue);
self.pastIssue(state.past_issue);
};
self.popoverContent = ko.pureComputed(function () {
var undervoltageParagraphClasses = "muted";
var undervoltageSymbolClasses = "";
var overheatParagraphClasses = "muted";
var overheatSymbolClasses = "";
if (self.currentUndervoltage()) {
undervoltageSymbolClasses = "text-error pi_support_state_pulsate";
undervoltageParagraphClasses = "";
} else if (self.pastUndervoltage()) {
undervoltageSymbolClasses = "text-error";
undervoltageParagraphClasses = "";
}
if (self.currentOverheat()) {
overheatSymbolClasses = "text-error pi_support_state_pulsate";
overheatParagraphClasses = "";
} else if (self.pastOverheat()) {
overheatSymbolClasses = "text-error";
overheatParagraphClasses = "";
}
return (
"<p class='" +
undervoltageParagraphClasses +
"'><strong class='" +
undervoltageSymbolClasses +
'\'><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></strong></strong> - ' +
gettext(
"Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi."
) +
"</p>" +
"<p class='" +
overheatParagraphClasses +
"'><strong class='" +
overheatSymbolClasses +
'\'><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></strong> - ' +
gettext(
"Frequency capping due to overheating. Improve cooling of the CPU and GPU."
) +
"</p>" +
"<p>" +
gettext(
"A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up."
) +
"</p>" +
"<p><small>" +
gettext("Click the symbol in the navbar for more information.") +
"</small></p>"
);
});
self.onStartup = self.onServerReconnect = self.onUserLoggedIn = self.onUserLoggedOut = function () {
self.requestData();
};
self.onDataUpdaterPluginMessage = function (plugin, data) {
if (plugin !== "pi_support") return;
if (!data.hasOwnProperty("state") || !data.hasOwnProperty("type")) return;
if (data.type !== "throttle_state") return;
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_PI_SUPPORT_STATUS
)
)
return;
self.fromThrottleState(data.state);
};
}
OCTOPRINT_VIEWMODELS.push({
construct: PiSupportViewModel,
elements: ["#navbar_plugin_pi_support"],
dependencies: ["loginStateViewModel", "accessViewModel", "settingsViewModel"]
});
});
@@ -1,31 +0,0 @@
<h3>{{ _('About OctoPi') }}</h3>
<h4>The ready-to-go Raspberry Pi image with OctoPrint</h4>
<p>Version <span class="plugin_pi_support_octopi_version">{{ plugin_pi_support_octopi_version }}</span>, running on <span class="plugin_pi_support_model">{{ plugin_pi_support_model }}</span></p>
<ul>
<li>Website: <a href="https://octoprint.org/download/" target="_blank" rel="noreferrer noopener">octoprint.org/download</a></li>
<li>Source Code: <a href="https://github.com/guysoft/OctoPi" target="_blank" rel="noreferrer noopener">github.com/guysoft/OctoPi</a></li>
</ul>
<p>
&copy; 2013-{{ now.strftime("%Y") }} <a href="https://github.com/guysoft/OctoPi/graphs/contributors" target="_blank" rel="noreferrer noopener">The OctoPi Authors</a>
</p>
<p>
OctoPi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
</p>
<p>
OctoPi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
</p>
<p>
For a copy of the GNU General Public License, see
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html" target="_blank" rel="noreferrer noopener">www.gnu.org/licenses/gpl-3.0.en.html</a>.
</p>
@@ -1,4 +0,0 @@
<a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('What do the symbols mean?')|esq }}', html: true, content: popoverContent, trigger: 'hover' }" style="display: none">
<span data-bind="visible: currentUndervoltage() || pastUndervoltage(), css: {'pi_support_state_pulsate': currentUndervoltage}" title="{{ _('Undervoltage')|edq }}"><i class="fas fa-bolt"></i><i class="fas fa-exclamation"></i></span>
<span data-bind="visible: currentOverheat() || pastOverheat(), css: {'pi_support_state_pulsate': currentOverheat}" title="{{ _('Overheat')|edq }}"><i class="fas fa-thermometer-full"></i><i class="fas fa-exclamation"></i></span>
</a>
@@ -1,38 +0,0 @@
<h3>{{ _('Pi Support') }}</h3>
<p>{{ _('Please restart OctoPrint after changing any of this plugin\'s settings.') }}</p>
<form class="form-horizontal" onsubmit="return false;">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.pi_support.ignore_unrecommended_model"> {{ _('Disable warning about unsupported hardware') }} <label class="label label-important">{{ _('Warning') }}</label>
</label>
<span class="help-block">{{ _('If you check this, you will no longer get warned if you run OctoPrint on Raspberry Pi models that are not officially supported due to bad performance that can lead to failed prints. Do so at your own risk.') }}</span>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.pi_support.vcgencmd_throttle_check_enabled"> {{ _('Enable under voltage and overheat detection via <code>vcgencmd get_throttled</code>') }}
</label>
<span class="help-block">{{ _('This will regularly check with the Pi if something is amiss either with power regulation or CPU/GPU temperature.') }}</span>
</div>
</div>
<div>
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<form class="form-horizontal" onsubmit="return false;">
<div class="control-group">
<label class="control-label">{{ _('Command for under voltage/overheat detection') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.pi_support.vcgencmd_throttle_check_command">
<span class="help-block">{{ _('Defaults to <code>/usr/bin/vcgencmd get_throttled</code>. You usually shouldn\'t have to change this.') }}</span>
</div>
</div>
</form>
</div>
</div>
</form>
-2
View File
@@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
@@ -1 +0,0 @@
Raspberry Pi Zero W Rev 1.1
@@ -1 +0,0 @@
0.15.1
@@ -1,5 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
print("throttled=0x50005")
-191
View File
@@ -1,191 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
import _fixups
import ddt
import mock
from octoprint.util.platform import CLOSE_FDS
OCTOPI_VERSION = "0.14.0"
DT_MODEL = "Raspberry Pi Model F Rev 1.1"
VCGENCMD = "/usr/bin/vcgencmd get_throttled"
class PiSupportTestCase(unittest.TestCase):
def test_get_octopi_version(self):
from octoprint.plugins.pi_support import get_octopi_version
# import _fixups
with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m:
m.return_value.readline.return_value = OCTOPI_VERSION
version = get_octopi_version()
m.assert_called_once_with("/etc/octopi_version", "rt", encoding="utf-8")
self.assertEqual(version, OCTOPI_VERSION)
def test_get_proc_dt_model(self):
from octoprint.plugins.pi_support import get_proc_dt_model
# import _fixups
with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m:
m.return_value.readline.return_value = DT_MODEL
model = get_proc_dt_model()
m.assert_called_once_with("/proc/device-tree/model", "rt", encoding="utf-8")
self.assertEqual(model, DT_MODEL)
def test_get_vcgencmd_throttle_state(self):
from octoprint.plugins.pi_support import get_vcgencmd_throttled_state
with mock.patch("sarge.get_stdout", mock.MagicMock()) as m:
m.return_value = "throttled=0x70005"
state = get_vcgencmd_throttled_state(VCGENCMD)
m.assert_called_once_with(VCGENCMD, close_fds=CLOSE_FDS)
self.assertTrue(state.current_undervoltage)
self.assertFalse(state.current_overheat)
self.assertTrue(state.current_issue)
self.assertTrue(state.past_undervoltage)
self.assertTrue(state.past_overheat)
self.assertTrue(state.past_issue)
def test_get_vcgencmd_throttle_state_unparseable1(self):
from octoprint.plugins.pi_support import get_vcgencmd_throttled_state
with mock.patch("sarge.get_stdout", mock.MagicMock()) as m:
m.return_value = "invalid"
try:
get_vcgencmd_throttled_state(VCGENCMD)
except ValueError:
# expected
pass
else:
self.fail("Expected ValueError")
def test_get_vcgencmd_throttle_state_unparseable2(self):
from octoprint.plugins.pi_support import get_vcgencmd_throttled_state
with mock.patch("sarge.get_stdout", mock.MagicMock()) as m:
m.return_value = "throttled=0xinvalid"
try:
get_vcgencmd_throttled_state(VCGENCMD)
except ValueError:
# expected
pass
else:
self.fail("Expected ValueError")
@ddt.ddt
class ThrottleStateTestCase(unittest.TestCase):
@ddt.data(
(
0x00000,
{
"_undervoltage": False,
"_freq_capped": False,
"_throttled": False,
"_past_undervoltage": False,
"_past_freq_capped": False,
"_past_throttled": False,
"current_undervoltage": False,
"past_undervoltage": False,
"current_overheat": False,
"past_overheat": False,
"current_issue": False,
"past_issue": False,
},
),
(
0x50005,
{
"_undervoltage": True,
"_freq_capped": False,
"_throttled": True,
"_past_undervoltage": True,
"_past_freq_capped": False,
"_past_throttled": True,
"current_undervoltage": True,
"past_undervoltage": True,
"current_overheat": False,
"past_overheat": False,
"current_issue": True,
"past_issue": True,
},
),
(
0x50000,
{
"_undervoltage": False,
"_freq_capped": False,
"_throttled": False,
"_past_undervoltage": True,
"_past_freq_capped": False,
"_past_throttled": True,
"current_undervoltage": False,
"past_undervoltage": True,
"current_overheat": False,
"past_overheat": False,
"current_issue": False,
"past_issue": True,
},
),
(
0x00006,
{
"_undervoltage": False,
"_freq_capped": True,
"_throttled": True,
"_past_undervoltage": False,
"_past_freq_capped": False,
"_past_throttled": False,
"current_undervoltage": False,
"past_undervoltage": False,
"current_overheat": True,
"past_overheat": False,
"current_issue": True,
"past_issue": False,
},
),
)
@ddt.unpack
def test_conversion(self, input, expected_flags):
from octoprint.plugins.pi_support import ThrottleState
output = ThrottleState.from_value(input)
for key, value in expected_flags.items():
self.assertEqual(getattr(output, key), value)
def test_as_dict(self):
from octoprint.plugins.pi_support import ThrottleState
state = ThrottleState(
undervoltage=True,
throttled=True,
past_undervoltage=True,
past_freq_capped=True,
past_throttled=True,
)
self.assertDictEqual(
state.as_dict(),
{
"current_undervoltage": True,
"past_undervoltage": True,
"current_overheat": False,
"past_overheat": True,
"current_issue": True,
"past_issue": True,
"raw_value": -1,
},
)