Merge branch 'maintenance' into devel

# Conflicts:
#	src/octoprint/static/js/app/viewmodels/printerstate.js
This commit is contained in:
Gina Häußge committed 2018-07-20 12:27:36 +02:00
commit b83dd76c89
34 files changed
+768 -404

No files matched your search

+1
View File
@@ -11,6 +11,7 @@ trim_trailing_whitespace = true
[**.py]
indent_style = tab
indent_size = 4
[src/octoprint/static/js/app/**.js]
indent_style = space
+3 -3
View File
@@ -24,10 +24,10 @@ maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.9rc4
# staging/maintenance is currently the branch for preparation of 1.3.9rc5
# so is regressionfix/...
staging/maintenance 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 pep440-dev
regressionfix/.* 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 pep440-dev
staging/maintenance 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
regressionfix/.* 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
+12
View File
@@ -1,5 +1,17 @@
# OctoPrint Changelog
## 1.3.9rc4 (2018-07-20)
### Bug fixes
* [#2737](https://github.com/foosel/OctoPrint/issues/2737) (regression) - Fix print button being enabled even though no file is selected.
* [#2738](https://github.com/foosel/OctoPrint/issues/2738) (regression) - Limit the use of the `--no-cache-dir` argument added to `pip` calls to such versions of `pip` that already support it (anything newer than 1.5.6).
* Only perform write tests on directories where necessary. Especially avoid them on page rendition to prevent misconfigured folders from triggering an HTTP 500. (regression)
### More information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.9rc3...1.3.9rc4)
## 1.3.9rc3 (2018-07-16)
### Improvements
+1 -1
View File
@@ -60,4 +60,4 @@ thanks to everyone who contributed!
* Timothy D Hoogland
* Trent Shumay
and 1333 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1337 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+6 -9
View File
@@ -256,7 +256,7 @@ class FileManager(object):
file_name = storage_manager.split_path(path)
# we'll use the default printer profile for the backlog since we don't know better
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default(), None)
if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority):
counter += 1
@@ -476,12 +476,9 @@ class FileManager(object):
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display)
if analysis is None:
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile)
if queue_entry:
self._analysis_queue.enqueue(queue_entry, high_priority=True)
else:
self._add_analysis_result(destination, path, analysis)
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile, analysis=analysis)
if queue_entry:
self._analysis_queue.enqueue(queue_entry, high_priority=True)
_, name = self._storage(destination).split_path(path_in_storage)
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
@@ -700,7 +697,7 @@ class FileManager(object):
def _on_analysis_finished(self, entry, result):
self._add_analysis_result(entry.location, entry.path, result)
def _analysis_queue_entry(self, destination, path, printer_profile=None):
def _analysis_queue_entry(self, destination, path, printer_profile=None, analysis=None):
if printer_profile is None:
printer_profile = self._printer_profile_manager.get_current_or_default()
@@ -709,6 +706,6 @@ class FileManager(object):
file_type = get_file_type(absolute_path)
if file_type:
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile)
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile, analysis)
else:
return None
+4 -1
View File
@@ -20,7 +20,7 @@ from octoprint.events import Events, eventManager
from octoprint.settings import settings
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
"""
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
for processing.
@@ -33,6 +33,7 @@ class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, locatio
location (str): Location the file is located on.
absolute_path (str): Absolute path on disk through which to access the file.
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
"""
def __str__(self):
@@ -341,6 +342,8 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
import sys
import yaml
if self._current.analysis:
return self._current.analysis
try:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
+1 -1
View File
@@ -861,7 +861,7 @@ class PluginManager(object):
if plugin.check():
return plugin
else:
self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin)))
self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
return None
def _is_plugin_disabled(self, key):
+2 -2
View File
@@ -113,12 +113,12 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
def _get_usage(self):
import psutil
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False))
return usage.free, usage.total
def _getLogFiles(self):
files = []
basedir = settings().getBaseFolder("logs")
basedir = settings().getBaseFolder("logs", check_writable=False)
for entry in scandir(basedir):
files.append({
"name": entry.name,
@@ -1,176 +0,0 @@
# 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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import flask
import os
from flask_babel import gettext
import octoprint.plugin
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
_CPUINFO_PATH = "/proc/cpuinfo"
# based on https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F
_RPI_REVISION_MAP = {
"Beta": "1B (Beta)",
"0002": "1B",
"0003": "1B",
"0004": "1B",
"0005": "1B",
"0006": "1B",
"0007": "1A",
"0008": "1A",
"0009": "1A",
"000d": "1B",
"000e": "1B",
"000f": "1B",
"0010": "B+",
"0011": "CM1",
"0012": "A+",
"0013": "B+",
"0014": "CM1",
"0015": "A+",
"a01040": "2B",
"a01041": "2B",
"a21041": "2B",
"a22042": "2B",
"900021": "A+",
"900032": "B+",
"900092": "Zero",
"900093": "Zero",
"920093": "Zero",
"9000c1": "Zero W",
"a02082": "3B",
"a020a0": "CM3",
"a22082": "3B",
"a32082": "3B",
"a020d3": "3B+"
}
def get_octopi_version():
with open(_OCTOPI_VERSION_PATH, "r") as f:
version_line = f.readline()
return version_line.strip()
def get_pi_cpuinfo():
fields = dict(revision="Revision",
hardware="Hardware",
serial="Serial")
result = dict()
with open(_CPUINFO_PATH) as f:
for line in f:
if not line:
continue
for key, prefix in fields.items():
if line.startswith(prefix):
result[key] = line[line.index(":") + 1:].strip()
return result
def get_pi_model(hardware, revision):
if hardware not in ("BCM2835",):
return "unknown"
if revision.startswith("1000"):
# strip flag for over-volted (https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F)
revision = revision[4:]
return _RPI_REVISION_MAP.get(revision.lower(), "unknown")
class OctoPiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin):
# noinspection PyMissingConstructor
def __init__(self):
self._version = None
self._cpuinfo = None
self._model = None
#~~ EnvironmentDetectionPlugin
def get_additional_environment(self):
return dict(version=self._get_version(),
revision=self._get_cpuinfo().get("revision", "unknown"),
model=self._get_model())
#~~ SimpleApiPlugin
def on_api_get(self, request):
return flask.jsonify(version=self._get_version())
#~~ AssetPlugin
def get_assets(self):
return dict(
js=["js/octopi_support.js"],
css=["css/octopi_support.css"]
)
#~~ TemplatePlugin
def get_template_configs(self):
return [
dict(type="about", name="About OctoPi", template="octopi_support_about.jinja2")
]
def get_template_vars(self):
return dict(version=self._get_version())
#~~ Helpers
def _get_version(self):
if self._version is None:
try:
self._version = get_octopi_version()
except:
self._logger.exception("Error while reading OctoPi version from file {}".format(_OCTOPI_VERSION_PATH))
self._version = "unknown"
return self._version
def _get_model(self):
if self._model is None:
try:
cpuinfo = self._get_cpuinfo()
self._model = get_pi_model(cpuinfo.get("hardware", "unknown"),
cpuinfo.get("revision", "unknown"))
except:
self._logger.exception("Error while detecting RPi model")
self._model = "unknown"
return self._model
def _get_cpuinfo(self):
if self._cpuinfo is None:
try:
self._cpuinfo = get_pi_cpuinfo()
except:
self._logger.exception("Error while fetching cpu info")
self._cpuinfo = dict()
return self._cpuinfo
__plugin_name__ = "OctoPi Support Plugin"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides additional information about your OctoPi instance in the UI."
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
"provide additional information about your OctoPi instance,"
"which will make it more tricky to help you if you need support.")
__plugin_license__ = "AGPLv3"
def __plugin_check__():
from octoprint.util.platform import get_os
return get_os() == "linux" and os.path.exists(_OCTOPI_VERSION_PATH)
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = OctoPiSupportPlugin()
@@ -1,3 +0,0 @@
#octopi_support_footer {
white-space: nowrap;
}
@@ -1,50 +0,0 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintOctoPiSupportClient = function(base) {
this.base = base;
};
OctoPrintOctoPiSupportClient.prototype.get = function(opts) {
return this.base.get(this.base.getSimpleApiUrl("octopi_support"));
};
OctoPrintClient.registerPluginComponent("octopi_support", OctoPrintOctoPiSupportClient);
return OctoPrintOctoPiSupportClient;
});
$(function() {
function OctoPiSupportViewModel(parameters) {
var self = this;
self.requestData = function() {
OctoPrint.plugins.octopi_support.get()
.done(function(response) {
$("#octopi_support_footer").remove();
if (!response.version) return;
var octoPrintVersion = $(".footer span.version");
var octoPiVersion = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
+ " <span class='octopi_version'>" + response.version + "</span></span>")
$(octoPiVersion).insertAfter(octoPrintVersion);
})
};
self.onStartup = function() {
self.requestData();
};
self.onServerReconnect = function() {
self.requestData();
};
}
OCTOPRINT_VIEWMODELS.push({
construct: OctoPiSupportViewModel
});
});
@@ -0,0 +1,302 @@
# 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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import flask
import os
import sarge
from flask_babel import gettext
from octoprint.util import RepeatedTimer
import octoprint.plugin
_PROC_DT_MODEL_PATH = "/proc/device-tree/model"
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
_VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled"
### uncomment 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("0x70000"))
# 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):
if value == 0:
return ThrottleState()
kwargs = dict(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)
return ThrottleState(**kwargs)
def __init__(self, **kwargs):
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
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
def as_dict(self):
return dict(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 open(_PROC_DT_MODEL_PATH, "r") as f:
_proc_dt_model = f.readline().strip(" \t\r\n\0")
return _proc_dt_model
def get_vcgencmd_throttled_state(command):
output = sarge.get_stdout(command)
#output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # for local debugging
if not "throttled=0x" 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 open(_OCTOPI_VERSION_PATH, "r") 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
#~~ EnvironmentDetectionPlugin
def get_additional_environment(self):
result = dict(model=get_proc_dt_model())
if is_octopi():
result.update(dict(octopi_version=get_octopi_version()))
return result
#~~ SimpleApiPlugin
def on_api_get(self, request):
result = dict(throttle_state=self._throttle_state.as_dict())
result.update(self.get_additional_environment())
return flask.jsonify(**result)
#~~ AssetPlugin
def get_assets(self):
return dict(
js=["js/pi_support.js"],
css=["css/pi_support.css"]
)
#~~ TemplatePlugin
def get_template_configs(self):
configs = [dict(type="settings", name=gettext("Pi Support"), template="pi_support_settings.jinja2", custom_bindings=False)]
if is_octopi():
configs.append(dict(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 dict(vcgencmd_throttle_check_enabled=True,
vcgencmd_throttle_check_command=_VCGENCMD_THROTTLE)
def get_settings_restricted_paths(self):
return dict(admin=[["vcgencmd_throttle_check_enabled"], ["vcgencmd_throttle_check_command"]])
#~~ Helpers
def _check_throttled_state_interval(self):
if self._throttle_state.current_issue:
# check state every 30s if something's currently amiss
return 30
else:
# check state every 5min if nothing's currently amiss
return 300
def _check_throttled_state_condition(self):
return self._throttle_functional
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:
self._logger.exception("Got an error while trying to fetch the current throttle state via \"{}\"".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.warn(message)
self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state",
state=self._throttle_state.as_dict()))
__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"
def __plugin_check__():
try:
proc_dt_model = get_proc_dt_model()
if proc_dt_model is None:
return False
except:
return False
return "raspberry pi" in proc_dt_model.lower()
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = PiSupportPlugin()
@@ -0,0 +1,8 @@
#octopi_support_footer {
white-space: nowrap;
}
.pi_support_state_pulsate {
animation: pulsate 1s ease-out;
animation-iteration-count: infinite;
}
@@ -0,0 +1,90 @@
(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;
});
$(function() {
function PiSupportViewModel(parameters) {
var self = this;
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() {
OctoPrint.plugins.pi_support.get()
.done(function(response) {
// Raspberry Pi model
self.model(response.model);
// Throttle state
self.fromThrottleState(response.throttle_state);
// OctoPi version
$("#octopi_support_footer").remove();
if (!response.octopi_version) return;
var octoPrintVersion = $(".footer span.version");
var octoPiVersion = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
+ " <span class='octopi_version'>" + response.octopi_version + "</span></span>")
$(octoPiVersion).insertAfter(octoPrintVersion);
})
};
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.issuePopoverContent = function() {
return "<p><strong><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><strong><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 icon indicates an acute issue!") + "</p>"
};
self.onStartup = function() {
self.requestData();
};
self.onServerReconnect = 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;
self.fromThrottleState(data.state);
}
}
OCTOPRINT_VIEWMODELS.push({
construct: PiSupportViewModel,
elements: ["#navbar_plugin_pi_support"]
});
});
@@ -2,10 +2,10 @@
<h4>The ready-to-go Raspberry Pi image with OctoPrint</h4>
<p>Version <span class="plugin_octopi_support_version">{{ plugin_octopi_support_version }}</span></p>
<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> &amp; <a href="https://octopi.octoprint.org" target="_blank" rel="noreferrer noopener">octopi.octoprint.org</a></li>
<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>
@@ -0,0 +1,4 @@
<a href="javascript:void(0)" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('Issues reported by the Pi') }}', html: true, content: issuePopoverContent(), trigger: 'hover' }" style="display: none">
<span data-bind="visible: currentUndervoltage() || pastUndervoltage(), css: {'pi_support_state_pulsate': currentUndervoltage}" title="{{ _('Undervoltage') }}"><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></span>
<span data-bind="visible: currentOverheat() || pastOverheat(), css: {'pi_support_state_pulsate': currentOverheat}" title="{{ _('Overheat') }}"><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></span>
</a>
@@ -0,0 +1,31 @@
<h3>{{ _('Pi Support') }}</h3>
<p>{{ _('Please restart OctoPrint after changing any of this plugin\'s settings.') }}</p>
<form class="form-horizontal">
<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="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<form class="form-horizontal">
<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>
+64 -8
View File
@@ -12,6 +12,12 @@ import requests
import hashlib
import logging
try:
# noinspection PyCompatibility
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
# noinspection PyCompatibility
import concurrent.futures
@@ -33,10 +39,13 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
def __init__(self):
self._environment = None
self._printer_connection_parameters = None
self._url = None
self._ping_worker = None
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
self._record_next_firmware_info = False
def initialize(self):
self._init_tracking()
@@ -46,7 +55,16 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
return dict(enabled=None,
unique_id=None,
server=TRACKING_URL,
ping=15*60)
ping=15*60,
events=dict(startup=True,
printjob=True,
plugin=True,
update=True,
printer=True))
def get_settings_restricted_paths(self):
return dict(admin=[["enabled"], ["unique_id"], ["events"]],
never=[["server"], ["ping"]])
def on_settings_save(self, data):
enabled = self._settings.get([b"enabled"])
@@ -87,6 +105,13 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._track_update_event(event, payload)
elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED):
self._track_printjob_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)
##~~ TemplatePlugin
@@ -120,7 +145,13 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._settings.set([b"unique_id"], str(uuid.uuid4()))
self._settings.save()
def _track_ping(self):
self._track("ping")
def _track_startup(self):
if not self._settings.get_boolean(["events", "startup"]):
return
payload = dict(version=get_octoprint_version_string(),
os=self._environment[b"os"][b"id"],
python=self._environment[b"python"][b"version"],
@@ -129,19 +160,23 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
freq=self._environment[b"hardware"][b"freq"],
ram=self._environment[b"hardware"][b"ram"])
if b"plugins" in self._environment and b"octopi_support" in self._environment[b"plugins"]:
payload[b"octopi_version"] = self._environment[b"plugins"][b"octopi_support"][b"version"]
payload[b"pi_model"] = self._environment[b"plugins"][b"octopi_support"][b"model"]
if b"plugins" in self._environment and b"pi_support" in self._environment[b"plugins"]:
payload[b"pi_model"] = self._environment[b"plugins"][b"pi_support"][b"model"]
if b"octopi_version" in self._environment[b"plugins"][b"pi_support"]:
payload[b"octopi_version"] = self._environment[b"plugins"][b"pi_support"][b"octopi_version"]
self._track("startup", **payload)
def _track_shutdown(self):
if not self._settings.get_boolean(["events", "startup"]):
return
self._track("shutdown")
def _track_ping(self):
self._track("ping")
def _track_plugin_event(self, event, payload):
if not self._settings.get_boolean(["events", "plugin"]):
return
if event.endswith("_installplugin"):
self._track("install_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
elif event.endswith("_uninstallplugin"):
@@ -152,12 +187,18 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._track("disable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version"))
def _track_update_event(self, event, payload):
if not self._settings.get_boolean(["events", "update"]):
return
if event.endswith("_update_succeeded"):
self._track("update_successful", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version"))
elif event.endswith("_update_failed"):
self._track("update_failed", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version"))
def _track_printjob_event(self, event, payload):
if not self._settings.get_boolean(["events", "printjob"]):
return
sha = hashlib.sha1()
sha.update(payload.get("name"))
@@ -181,6 +222,17 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
if track_event is not None:
self._track(track_event, **args)
def _track_printer_event(self, event, payload):
if not self._settings.get_boolean(["events", "printer"]):
return
if event in (Events.FIRMWARE_DATA,):
args = dict(firmware_name=payload["name"])
if self._printer_connection_parameters:
args["printer_port"] = self._printer_connection_parameters["port"]
args["printer_baudrate"] = self._printer_connection_parameters["baudrate"]
self._track("printer_connected", **args)
def _track(self, event, **kwargs):
if not self._settings.get_boolean([b"enabled"]):
return
@@ -188,13 +240,17 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin,
self._executor.submit(self._do_track, event, **kwargs)
def _do_track(self, event, **kwargs):
if not self._connectivity_checker.online:
return
server = self._settings.get([b"server"])
url = server.format(id=self._settings.get([b"unique_id"]), event=event)
headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())}
try:
params = urlencode(kwargs, doseq=True).replace("+", "%20")
requests.get(url,
params=kwargs,
params=params,
timeout=3.1,
headers=headers)
self._logger.debug("Sent tracking event to {}".format(url))
@@ -16,6 +16,29 @@
<span style="padding-top: 5px; margin-bottom: 5px; display: inline-block" data-bind="text: settings.plugins.tracking.unique_id() || 'N/A'"></span>
</div>
</div>
<div class="control-group">
<label class="control-label" title="{{ _('Events to track. The ping is mandatory.') }}">{{ _('Tracked events') }}</label>
<div class="controls">
<label class="checkbox">
<input type="checkbox" checked="checked" disabled="disabled"> {{ _('Regular ping') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.startup"> {{ _('Server startup & shutdown') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.printer"> {{ _('Connected to printer') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.printjob"> {{ _('Print started/cancelled/finished') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.plugin"> {{ _('Plugin installed/uninstalled/enabled/disabled') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.update"> {{ _('OctoPrint or a plugin updated successfully or unsuccessfully') }}
</label>
</div>
</div>
</form>
{% include "snippets/plugins/tracking/trackingDetails.jinja2" %}
@@ -4,9 +4,13 @@
{% include "snippets/plugins/tracking/trackingDetails.jinja2" %}
<p>
{{ _('<strong>Note:</strong> You can always change your decision and also access more granular controls via Settings > Anonymous Usage Tracking.') }}
</p>
<div class="row-fluid">
<a href="#" class="btn btn-danger span6" data-bind="click: function() { if(!setup()){disableTracking()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Anonymous Usage Tracking') }}</a>
<a href="#" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enableTracking()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Enable Anonymous Usage Tracking') }}</a>
<a href="javascript:void(0)" class="btn span6" data-bind="click: function() { if(!setup()){disableTracking()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Anonymous Usage Tracking') }}</a>
<a href="javascript:void(0)" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enableTracking()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Enable Anonymous Usage Tracking') }}</a>
</div>
<div class="tracking_decision" style="display: none" data-bind="visible: setup()">
+2 -2
View File
@@ -105,7 +105,7 @@ def readGcodeFiles():
files = _getFileList(FileDestinations.LOCAL, filter=filter, recursive=recursive, allow_from_cache=not force)
files.extend(_getFileList(FileDestinations.SDCARD))
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
usage = psutil.disk_usage(settings().getBaseFolder("uploads", check_writable=False))
return jsonify(files=files, free=usage.free, total=usage.total)
@@ -129,7 +129,7 @@ def readGcodeFilesForOrigin(origin):
files = _getFileList(origin, filter=filter, recursive=recursive, allow_from_cache=not force)
if origin == FileDestinations.LOCAL:
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
usage = psutil.disk_usage(settings().getBaseFolder("uploads", check_writable=False))
return jsonify(files=files, free=usage.free, total=usage.total)
else:
return jsonify(files=files)
+1 -1
View File
@@ -32,7 +32,7 @@ from flask_babel import Locale
@require_firstrun
@Permissions.SETTINGS.require(403)
def getInstalledLanguagePacks():
translation_folder = settings().getBaseFolder("translations")
translation_folder = settings().getBaseFolder("translations", check_writable=False)
if not os.path.exists(translation_folder):
return jsonify(language_packs=dict(_core=[]))
+1 -1
View File
@@ -960,7 +960,7 @@ def _get_all_translationfiles(locale, domain):
po_files = []
user_base_path = os.path.join(settings().getBaseFolder("translations"))
user_base_path = os.path.join(settings().getBaseFolder("translations", check_writable=False))
user_plugin_path = os.path.join(user_base_path, "_plugins")
# plugin translations
+11 -10
View File
@@ -284,7 +284,7 @@ default_settings = {
"showFahrenheitAlso": False,
"components": {
"order": {
"navbar": ["settings", "systemmenu", "plugin_announcements", "login"],
"navbar": ["settings", "systemmenu", "plugin_announcements", "plugin_pi_support", "login"],
"sidebar": ["plugin_printer_safety_check", "connection", "state", "files"],
"tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"],
"settings": [
@@ -294,7 +294,7 @@ default_settings = {
],
"usersettings": ["access", "interface"],
"wizard": ["access"],
"about": ["about", "plugin_octopi_support", "supporters", "authors", "changelog", "license", "thirdparty", "plugin_pluginmanager"],
"about": ["about", "plugin_pi_support", "supporters", "authors", "changelog", "license", "thirdparty", "plugin_pluginmanager"],
"generic": []
},
"disabled": {
@@ -647,7 +647,7 @@ class Settings(object):
if folders is None:
folders = default_settings["folder"].keys()
for folder in folders:
self.getBaseFolder(folder, log_error=True)
self.getBaseFolder(folder, check_writable=True, deep_check_writable=True, log_error=True)
def _get_default_folder(self, type):
folder = default_settings["folder"][type]
@@ -1501,7 +1501,7 @@ class Settings(object):
return value.lower() in valid_boolean_trues
return value is not None
def getBaseFolder(self, type, create=True, allow_fallback=True, log_error=False):
def getBaseFolder(self, type, create=True, allow_fallback=True, log_error=False, check_writable=True, deep_check_writable=False):
if type not in default_settings["folder"].keys() + ["base"]:
return None
@@ -1514,7 +1514,7 @@ class Settings(object):
folder = default_folder
try:
_validate_folder(folder, create=create, writable=True, log_error=log_error)
_validate_folder(folder, create=create, check_writable=check_writable, deep_check_writable=deep_check_writable, log_error=log_error)
except:
if folder != default_folder and allow_fallback:
if log_error:
@@ -1522,7 +1522,7 @@ class Settings(object):
"fall back on default folder at {}".format(type,
folder,
default_folder))
_validate_folder(default_folder, create=create, writable=True, log_error=log_error)
_validate_folder(default_folder, create=create, check_writable=check_writable, deep_check_writable=deep_check_writable, log_error=log_error)
folder = default_folder
try:
@@ -1715,7 +1715,7 @@ class Settings(object):
self._dirty_time = time.time()
elif (path != currentPath and path != defaultPath) or force:
if validate:
_validate_folder(path)
_validate_folder(path, check_writable=True, deep_check_writable=True)
if not "folder" in self._config.keys():
self._config["folder"] = {}
@@ -1758,7 +1758,7 @@ def _default_basedir(applicationName):
return os.path.expanduser(os.path.join("~", "." + applicationName.lower()))
def _validate_folder(folder, create=True, writable=True, log_error=False):
def _validate_folder(folder, create=True, check_writable=True, deep_check_writable=False, log_error=False):
logger = logging.getLogger(__name__)
if not os.path.exists(folder):
@@ -1783,12 +1783,13 @@ def _validate_folder(folder, create=True, writable=True, log_error=False):
# hardening against misconfiguration, see #1953
raise IOError("Expected a folder at {} but found a file instead".format(folder))
elif writable:
elif check_writable:
# make sure we can also write into the folder
error = "Folder at {} doesn't appear to be writable, please fix its permissions".format(folder)
if not os.access(folder, os.W_OK):
raise IOError(error)
else:
elif deep_check_writable:
# try to write a file to the folder - on network shares that might be the only reliable way
# to determine whether things are *actually* writable
testfile = os.path.join(folder, ".testballoon.txt")
@@ -25,7 +25,7 @@ $(function() {
!self.isCancelling() &&
!self.isPausing() &&
self.loginState.hasPermission(self.access.permissions.PRINT) &&
self.filename() !== undefined;
self.filename();
});
self.enablePause = ko.pureComputed(function() {
return self.isOperational() &&
+4 -4
View File
@@ -107,16 +107,16 @@ def _extract_prefix(filename):
def last_modified_finished():
return os.stat(settings().getBaseFolder("timelapse")).st_mtime
return os.stat(settings().getBaseFolder("timelapse", check_writable=False)).st_mtime
def last_modified_unrendered():
return os.stat(settings().getBaseFolder("timelapse_tmp")).st_mtime
return os.stat(settings().getBaseFolder("timelapse_tmp", check_writable=False)).st_mtime
def get_finished_timelapses():
files = []
basedir = settings().getBaseFolder("timelapse")
basedir = settings().getBaseFolder("timelapse", check_writable=False)
for entry in scandir(basedir):
if util.is_hidden_path(entry.path) or not valid_timelapse(entry.path):
continue
@@ -135,7 +135,7 @@ def get_unrendered_timelapses():
delete_old_unrendered_timelapses()
basedir = settings().getBaseFolder("timelapse_tmp")
basedir = settings().getBaseFolder("timelapse_tmp", check_writable=False)
jobs = collections.defaultdict(lambda: dict(count=0, size=None, bytes=0, date=None, timestamp=None))
for entry in scandir(basedir):
+25 -38
View File
@@ -43,15 +43,9 @@ class Vector3D(object):
True
"""
def __init__(self, *args, **kwargs):
self.x = kwargs.get("x", 0.0)
self.y = kwargs.get("y", 0.0)
self.z = kwargs.get("z", 0.0)
def __init__(self, *args):
if len(args) == 3:
self.x = args[0]
self.y = args[1]
self.z = args[2]
(self.x, self.y, self.z) = args
elif len(args) == 1:
# copy constructor
@@ -134,30 +128,25 @@ class MinMax3D(object):
>>> empty = MinMax3D()
>>> empty.size == Vector3D(0.0, 0.0, 0.0)
True
>>> partial = MinMax3D()
>>> partial.record(Vector3D(2.0, None, 2.0))
>>> partial.min.x == 2.0 == partial.max.x and partial.min.y == None == partial.max.y and partial.min.z == 2.0 == partial.max.z
True
>>> partial.record(Vector3D(1.0, None, 3.0))
>>> partial.min.x == 1.0 and partial.min.y == None and partial.min.z == 2.0
True
>>> partial.max.x == 2.0 and partial.max.y == None and partial.max.z == 3.0
True
>>> partial.size == Vector3D(1.0, 0.0, 1.0)
True
"""
def __init__(self):
self.min = Vector3D(None, None, None)
self.max = Vector3D(None, None, None)
self.min = Vector3D(float("inf"), float("inf"), float("inf"))
self.max = Vector3D(-float("inf"), -float("inf"), -float("inf"))
def record(self, coordinate):
self.min.x = coordinate.x if not self.min.x else min(self.min.x, coordinate.x)
self.min.y = coordinate.y if not self.min.y else min(self.min.y, coordinate.y)
self.min.z = coordinate.z if not self.min.z else min(self.min.z, coordinate.z)
self.max.x = coordinate.x if not self.max.x else max(self.max.x, coordinate.x)
self.max.y = coordinate.y if not self.max.y else max(self.max.y, coordinate.y)
self.max.z = coordinate.z if not self.max.z else max(self.max.z, coordinate.z)
"""
Records the coordinate, storing the min and max values.
The input vector components must not be None.
"""
self.min.x = min(self.min.x, coordinate.x)
self.min.y = min(self.min.y, coordinate.y)
self.min.z = min(self.min.z, coordinate.z)
self.max.x = max(self.max.x, coordinate.x)
self.max.y = max(self.max.y, coordinate.y)
self.max.z = max(self.max.z, coordinate.z)
@property
def size(self):
@@ -165,7 +154,7 @@ class MinMax3D(object):
for c in "xyz":
min = getattr(self.min, c)
max = getattr(self.max, c)
value = abs(max - min) if min is not None and max is not None else 0.0
value = abs(max - min) if max >= min else 0.0
setattr(result, c, value)
return result
@@ -199,12 +188,12 @@ class gcode(object):
@property
def printing_area(self):
return dict(minX=self._minMax.min.x,
minY=self._minMax.min.y,
minZ=self._minMax.min.z,
maxX=self._minMax.max.x,
maxY=self._minMax.max.y,
maxZ=self._minMax.max.z)
return dict(minX=None if math.isinf(self._minMax.min.x) else self._minMax.min.x,
minY=None if math.isinf(self._minMax.min.y) else self._minMax.min.y,
minZ=None if math.isinf(self._minMax.min.z) else self._minMax.min.z,
maxX=None if math.isinf(self._minMax.max.x) else self._minMax.max.x,
maxY=None if math.isinf(self._minMax.max.y) else self._minMax.max.y,
maxZ=None if math.isinf(self._minMax.max.z) else self._minMax.max.z)
def load(self, filename, throttle=None, speedx=6000, speedy=6000, offsets=None, max_extruders=10, g90_extruder=False):
if os.path.isfile(filename):
@@ -504,9 +493,7 @@ def getCodeFloat(line, code):
m = line.find(' ', n)
try:
if m < 0:
val = float(line[n:])
else:
val = float(line[n:m])
return val if not (math.isnan(val) or math.isinf(val)) else None
return float(line[n:])
return float(line[n:m])
except:
return None
+6
View File
@@ -26,6 +26,7 @@ class UnknownPip(Exception):
class PipCaller(CommandlineCaller):
process_dependency_links = pkg_resources.Requirement.parse("pip>=1.5")
no_cache_dir = pkg_resources.Requirement.parse("pip>=1.6")
no_use_wheel = pkg_resources.Requirement.parse("pip==1.5.0")
broken = pkg_resources.Requirement.parse("pip>=6.0.1,<=6.0.3")
@@ -41,6 +42,11 @@ class PipCaller(CommandlineCaller):
pip_version))
args.remove("--process-dependency-links")
# strip --no-cache-dir for versions that don't support it
if not pip_version in cls.no_cache_dir and "--no-cache-dir" in args:
logger.debug("Found --no-cache-dir flag, version {} doesn't support that yet though, removing.".format(pip_version))
args.remove("--no-cache-dir")
# add --no-use-wheel for versions that otherwise break
if pip_version in cls.no_use_wheel and not "--no-use-wheel" in args:
logger.debug("Version {} needs --no-use-wheel to properly work.".format(pip_version))
Whitespace-only changes.
@@ -0,0 +1 @@
Raspberry Pi Model F Rev 1.1
@@ -0,0 +1 @@
0.15.1
@@ -0,0 +1,2 @@
#!/usr/bin/env python2
print("throttled=0x50005")
+153
View File
@@ -0,0 +1,153 @@
import unittest
import ddt
import mock
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
with mock.patch("__builtin__.open", 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", "r")
self.assertEqual(version, OCTOPI_VERSION)
def test_get_proc_dt_model(self):
from octoprint.plugins.pi_support import get_proc_dt_model
with mock.patch("__builtin__.open", 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", "r")
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)
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, dict(_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, dict(_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, dict(_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, dict(_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(), dict(current_undervoltage=True,
past_undervoltage=True,
current_overheat=False,
past_overheat=True,
current_issue=True,
past_issue=True))
-89
View File
@@ -1,89 +0,0 @@
import unittest
import ddt
import mock
OCTOPI_VERSION = "0.14.0"
CPUINFO = """
processor : 0
model name : ARMv7 Processor rev 4 (v7l)
BogoMIPS : 38.40
Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xd03
CPU revision : 4
processor : 1
model name : ARMv7 Processor rev 4 (v7l)
BogoMIPS : 38.40
Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xd03
CPU revision : 4
processor : 2
model name : ARMv7 Processor rev 4 (v7l)
BogoMIPS : 38.40
Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xd03
CPU revision : 4
processor : 3
model name : ARMv7 Processor rev 4 (v7l)
BogoMIPS : 38.40
Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xd03
CPU revision : 4
Hardware : BCM2835
Revision : a02082
Serial : 000000000abcdef1
"""
@ddt.ddt
class OctoPiSupportTestCase(unittest.TestCase):
def test_get_octopi_version(self):
from octoprint.plugins.octopi_support import get_octopi_version
with mock.patch("__builtin__.open", 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", "r")
self.assertEqual(version, "0.14.0")
def test_get_pi_cpuinfo(self):
from octoprint.plugins.octopi_support import get_pi_cpuinfo
with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m:
m.return_value.__iter__.return_value = CPUINFO.splitlines()
cpuinfo = get_pi_cpuinfo()
m.assert_called_once_with("/proc/cpuinfo")
self.assertDictEqual(cpuinfo, dict(hardware="BCM2835", revision="a02082", serial="000000000abcdef1"))
@ddt.data(
("BCM2835", "a02082", "3B"),
("BCM2835", "1000a02082", "3B"),
# failures
("something else", "a02082", "unknown"),
("BCM2835", "aabbccdd", "unknown")
)
@ddt.unpack
def test_get_pi_model(self, hardware, revision, expected):
from octoprint.plugins.octopi_support import get_pi_model
actual = get_pi_model(hardware, revision)
self.assertEqual(actual, expected)