Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f9fe8c868 | ||
|
|
8f2e4ad978 | ||
|
|
b82d955ec7 | ||
|
|
832d2f4155 | ||
|
|
c336452f6c | ||
|
|
a9b6edde2b | ||
|
|
d59ef5c711 | ||
|
|
375480c707 | ||
|
|
60cacb9447 | ||
|
|
c159ab7fe2 | ||
|
|
e949e0198f | ||
|
|
1a6dbb3f4a | ||
|
|
10e834f623 | ||
|
|
5ce34f774e | ||
|
|
0456896d71 | ||
|
|
e06c09e206 | ||
|
|
a6d3299b91 | ||
|
|
0a7f2a209b | ||
|
|
67f7580506 | ||
|
|
aab3a7bd63 | ||
|
|
d0f5592421 | ||
|
|
bb6ea4d81b | ||
|
|
7e32e5be8f | ||
|
|
266cae3509 | ||
|
|
0dcbffb9d2 | ||
|
|
fb8c56be57 | ||
|
|
2bc0c4a77f | ||
|
|
187c09e7da | ||
|
|
5c62b33967 | ||
|
|
5db9acb359 | ||
|
|
962d6ab27f | ||
|
|
21699699b6 | ||
|
|
8fec0859d9 | ||
|
|
1b9ff1b0e2 | ||
|
|
ee2d644239 | ||
|
|
a50db4b08e | ||
|
|
6f5707a0fc | ||
|
|
cf053ddbed | ||
|
|
b1101f5150 | ||
|
|
3a9d581423 | ||
|
|
142a1b0dcb | ||
|
|
a33f44ea25 | ||
|
|
23e58d2fc1 | ||
|
|
2e897f19ac | ||
|
|
16e96743c5 | ||
|
|
4c6c764c5c | ||
|
|
e86ba9a395 | ||
|
|
c1c09d417d | ||
|
|
f8d225a768 | ||
|
|
4c3f4c2a8b | ||
|
|
cc3d34635e | ||
|
|
c81c93896b | ||
|
|
3bb06a1a33 |
No files matched your search
+7
-5
@@ -18,12 +18,14 @@ HEAD
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.5
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
|
||||
fix/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
|
||||
improve/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
|
||||
maintenance 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
fix/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
improve/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.5rc1
|
||||
staging/maintenance 1.3.5rc1 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.5rc2
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.5rc2 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
regressionfix/.* 1.3.5rc2 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 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
|
||||
@@ -1,5 +1,90 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.3.5rc2 (2017-07-27)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) - Temperature tab: Fix for legend in graph not updating with current values on mouse over.
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) - Temperature tab: Fix for new temperature inputs not fitting on one line in Firefox.
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) - Temperature tab & GCODE viewer: Fix for available tools (and offsets) not properly updating on change of printer profile.
|
||||
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) - Wizard: Fix sorting of required wizards not properly handling non-ASCII unicode.
|
||||
* [#2035](https://github.com/foosel/OctoPrint/issues/2035) - Fix an issue of the server not starting up if there's a file in the analysis backlog. The reason for this is that spawning a new process while the intermediary server is active causes the server port to be blocked (this is due to how subprocessing works by default), in turn leading to an error on startup since the port cannot be bound by the actual server. Since the GCODE analysis takes now place in its own subprocess and hence triggers this problem, it had to be moved until after the actual server has already started up to avoid this problem.
|
||||
* Wizard: Fix `onWizardPreventSettingsRefreshDialog` callback invocation.
|
||||
* Corewizard plugin: Fix `firstrunonly` wizards (e.g. for printer profile configuration) being displayed again if _any_ of the sub wizards (e.g. for the online check opt-in and configuration) is active.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.3.5rc1...1.3.5rc2))
|
||||
|
||||
## 1.3.5rc1 (2017-07-26)
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#1162](https://github.com/foosel/OctoPrint/pull/1162) - Allow `octoprint.comm.protocol.gcode.queuing` hook to return a list of commands.
|
||||
* [#1572](https://github.com/foosel/OctoPrint/issues/1572) & [#1881](https://github.com/foosel/OctoPrint/issues/1881) - Refactored web interface startup process to minimise risk of race conditions and speed improvements. Also added sequence diagram to the documentation showing the new processing order.
|
||||
* [#1640](https://github.com/foosel/OctoPrint/issues/1640) - Mouse over temperature graph to get exact data for that time.
|
||||
* [#1679](https://github.com/foosel/OctoPrint/issues/1679) - Support temperature autoreporting by the firmware instead of polling if the firmware reports to support it. For this to work with Marlin 1.1.0 to 1.1.3 you'll need to explicitly enable `EXTENDED_CAPABILITIES_REPORT` *and* `AUTO_REPORT_TEMPERATURES` in your firmware configuration, otherwise your firmware won't report that it actually supports this feature.
|
||||
* [#1737](https://github.com/foosel/OctoPrint/issues/1737) - Auto-detect Anet A8 firmware and treat as Repetier Firmware (which it actually appears to be, just renamed - thanks Anet for making this even harder).
|
||||
* [#1842](https://github.com/foosel/OctoPrint/issues/1842) - Update bundled FontAwesome to 4.7 (see also [#1915](https://github.com/foosel/OctoPrint/pull/1915)).
|
||||
* [#1910](https://github.com/foosel/OctoPrint/issues/1910) - Make last/pause/cancel temperature available for GCODE scripts.
|
||||
* [#1925](https://github.com/foosel/OctoPrint/issues/1925) - Include configured webcam stream URL in "Webcam stream not loaded" message for logged in users/admins. Slightly different wording for guests vs users vs admins.
|
||||
* [#1941](https://github.com/foosel/OctoPrint/issues/1941) - Enable "block while dwelling" flag when Malyan firmware is detected since that firmware seems to handle `G4` identically to Repetier Firmware instead of Marlin (like it claims to). See also [#1762](https://github.com/foosel/OctoPrint/issues/1762).
|
||||
* [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Add option to disable position logging on cancel/pause. See "Log position on cancel" and "Log position on pause" under Settings > Serial > Advanced options.
|
||||
* [#1971](https://github.com/foosel/OctoPrint/issues/1971) - Refactored temperature inputs. They now sport some fancy +/- buttons to increment/decrement the current temperature (which also auto submit after a couple of seconds) and easier editing by keyboard. The temperature offset was also slightly redesigned to make room for that.
|
||||
* [#1975](https://github.com/foosel/OctoPrint/issues/1975) - Better error reporting when deleting timelapses.
|
||||
* [#2010](https://github.com/foosel/OctoPrint/pull/2010) - Slight refactoring in the terminal tab: Full width input field, auto focus of input field when just clicking on terminal output.
|
||||
* [#2011](https://github.com/foosel/OctoPrint/issues/2011) - Centralized online connectivity check (with opt-in of course). None of the bundled plugins will attempt to fetch data from the net when the connectivity check indicates that would fail anyhow. This should improve server startup times and various requests when running isolated.
|
||||
* [#2025](https://github.com/foosel/OctoPrint/issues/2025) - More verbose logging of asynchronous system commands (e.g. restart/shutdown).
|
||||
* Allow timelapse configuration through UI even when not connected to the printer (suggested in [#1918](https://github.com/foosel/OctoPrint/issues/1918))
|
||||
* Disable "Upload to SD" UI elements while printing (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914))
|
||||
* Update bundled SockJS to 1.1.2 incl. source maps
|
||||
* Set `X-Robots` HTTP header and remove `Server` header from all responses, also set `robots` meta tag in page.
|
||||
* Don't require to enter programmer mode for printer port autodetection when there's only one possible port candidate anyhow.
|
||||
* More sensible sorting of baudrates (additionally configured, then 115200, then 250000, then everything else).
|
||||
* Don't show "Unhandled communication error" on autodetection failure.
|
||||
* Make timeout after which to unload the webcam stream after navigating away from it configurable (as suggested in [#1937](https://github.com/foosel/OctoPrint/issues/1937))
|
||||
* Add `ToolChange` event and tool change GCODE scripts
|
||||
* Support parsing GCODE subcodes.
|
||||
* Add `octoprint.users.factory` hook, allowing plugins to extend/swap out the user manager OctoPrint uses.
|
||||
* Corewizard: Disable view model and client code if it's not actually required.
|
||||
* Corewizard: Disable injection of JS files into UI when it's not actually required.
|
||||
* GCODE analysis: Moved into its own subprocess. That should improve performance on multi core systems.
|
||||
* GCODE viewer: Ignore coordinates outside bed when zooming/centering on model. Those usually are nozzle priming routines.
|
||||
* JS Client Lib: Add centralized browser detection as `OctoPrint.coreui.browser`. Available properties: `chrome`, `firefox`, `safari`, `ie`, `edge`, `opera` as well as `mobile` and `desktop`, all of which are boolean values.
|
||||
* Plugin Manager plugin: Detect if a plugin requires a reconnect to the printer to become fully active/inactive.
|
||||
* Software Update plugin: Force exact version when updating OctoPrint and tracking releases.
|
||||
* Software Update plugin: "Devel RCs" release channel now also tracks maintenance RCs. That way people don't have to toggle between the two any more to get *all* RCs.
|
||||
* Software Update plugin: `bitbucket_commit` check type now supports API credentials (see also [#1993](https://github.com/foosel/OctoPrint/pull/1993)).
|
||||
* Wizard: Allow suppressing the "the settings got updated" dialog through subwizards, in case they need to update settings asynchronously as part of their workflow.
|
||||
* More resilience against expected folders being files.
|
||||
* More resilience against a wrong user manager class being configured.
|
||||
* Some code refactoring & cleanup.
|
||||
* Some HTML & CSS improvements.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* [#1916](https://github.com/foosel/OctoPrint/issues/1916) - Fix webcam not loading if first/initial tab is "Control"
|
||||
* [#1924](https://github.com/foosel/OctoPrint/issues/1924) - Filter out source map links from bundled JS webassets.
|
||||
* [#1943](https://github.com/foosel/OctoPrint/issues/1943) - Fix issue causing unnecessary creation of default printer profile on startup
|
||||
* [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Decouple writing of print log from everything else. Fixes delay in cancel processing.
|
||||
* [#1963](https://github.com/foosel/OctoPrint/issues/1963) & [#1974](https://github.com/foosel/OctoPrint/issues/1974) - Allow empty & custom size in print job events. Also fixes an issue with timelapses when printing from SD on printers that require the GPX plugin to work.
|
||||
* [#1996](https://github.com/foosel/OctoPrint/issues/1996) - Support all line ending variantes in the GCODE viewer. Solves an issue with GCODE generated for Prusa's multi material extruder since that uses only `\r` for some reason.
|
||||
* [#2007](https://github.com/foosel/OctoPrint/issues/2007) - Fix issue parsing temperature lines from the printer that contain negative values.
|
||||
* [#2012](https://github.com/foosel/OctoPrint/issues/2012) - Fix command line interface of Software Update plugin.
|
||||
* [#2017](https://github.com/foosel/OctoPrint/issues/2017) - Fix issue in GCODE viewer with files that contain a visit to the first layer twice (e.g. brim, then nose dive from higher z for actual model), causing all but the last layer segment to not be rendered.
|
||||
* Fix various popup buttons allowing multiple clicks (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914))
|
||||
* Software Update Plugin: Perform server restart asynchronously. Should reduce restart times on updates significantly.
|
||||
* Don't hex-escape `\t`, `\r` or `\n` in terminal output
|
||||
* Use client side default printer profile if the default profile could not be found on the server
|
||||
* Use both "to" and "from" coordinates of a given move for min/max model coordinate calculation in GCODE analysis. Otherwise wrong values could be calculated under certain circumstances.
|
||||
* Fix potential race condition in resend request handling.
|
||||
* Fix potential race condition in web socket handling.
|
||||
* Fix handling of tool offsets in GCODE analysis - diverted too far from firmware implementations, causing wrong calculations.
|
||||
* Fix `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved` events not being fired with the correct event name.
|
||||
* Fix potential division by zero in progress reporting if the timing was just right.
|
||||
* Fix sorting order for multiple tools in the "State" panel.
|
||||
* Fix file position vs. line ending handling in GCODE viewer. Could lead to slightly off file position calculation and hence possibly to the wrong move being plotted when synchronizing with print progress.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.3.4...1.3.5rc1))
|
||||
|
||||
## 1.3.4 (2017-06-01)
|
||||
|
||||
### Note for owners of Malyan M200/Monoprice Select Mini
|
||||
|
||||
+6
-5
@@ -7,6 +7,7 @@ thanks to everyone who contributed!
|
||||
## Patreon Patrons
|
||||
|
||||
* 3D Moniak
|
||||
* Aaron Lieberman
|
||||
* Aleph Objects, Inc.
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
@@ -14,24 +15,24 @@ thanks to everyone who contributed!
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brian E. Tyler
|
||||
* Chris Day
|
||||
* Christian Petropolis
|
||||
* COLLE+McVOY
|
||||
* CreativeTools
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* Doug Johnson
|
||||
* E3D BigBox
|
||||
* Ernesto Martinez
|
||||
* Exovite
|
||||
* F. Kunsmann
|
||||
* Farren Young II
|
||||
* Frank Sander
|
||||
* Gary Deen
|
||||
* Gary N McKinney
|
||||
* George Robles
|
||||
* günter weber
|
||||
* Ivan Krasin
|
||||
* James Seigel
|
||||
* Jamie R McGuigan
|
||||
* Jason Lawrence
|
||||
* Jeff Moe
|
||||
* Josh Daniels
|
||||
* Kaile Riser
|
||||
@@ -55,14 +56,14 @@ thanks to everyone who contributed!
|
||||
* Roger Strolz
|
||||
* Roy Cortes
|
||||
* Samer Najia
|
||||
* SD3D
|
||||
* SeeMeCNC
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Stephane Schittly
|
||||
* Sven Mueller
|
||||
* Symbiotic Devices
|
||||
* Thomas Hatley
|
||||
* Timeshell.ca
|
||||
* Trent Shumay
|
||||
|
||||
and 1098 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1117 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
@@ -198,6 +198,13 @@ Version checks
|
||||
* ``branch``: Branch of the Bitbucket repository to check, defaults to
|
||||
``master`` if not set.
|
||||
* ``current``: Current commit hash. Will be updated automatically.
|
||||
* ``api_user``: (mandatory only for private repositories) Bitbucket user name (not email address).
|
||||
Requires ``api_password`` to be set. Hint: This is used for the check only. For the actual
|
||||
download you might register your public SSH key as access key for the according repo and
|
||||
configure this as pip URL in ``config.yaml``: ``git+ssh://git@bitbucket.org/my_user/my_repo.git@{target_version}``
|
||||
* ``api_password``: (mandatory only for private repositories) App password. Requires
|
||||
``api_user`` to be set. **Important**: Never use your actual Bitbucket login password. Generate
|
||||
a new app password. App passwords are user specific on Bitbucket.
|
||||
|
||||
* ``git_commit``: Checks a local git repository for new commits on its
|
||||
configured remote. Additional config parameters:
|
||||
|
||||
@@ -909,6 +909,20 @@ Use the following settings to configure the server:
|
||||
# Command to shut down the system OctoPrint is running on, defaults to being unset
|
||||
systemShutdownCommand: sudo shutdown -h now
|
||||
|
||||
# Configuration of the regular online connectivity check
|
||||
onlineCheck:
|
||||
# whether the online check is enabled, defaults to false due to valid privacy concerns
|
||||
enabled: false
|
||||
|
||||
# interval in which to check for online connectivity (in seconds)
|
||||
interval: 300
|
||||
|
||||
# DNS host against which to check (default: 8.8.8.8 aka Google's DNS)
|
||||
host: 8.8.8.8
|
||||
|
||||
# DNS port against which to check (default: 53 - the default DNS port)
|
||||
port: 53
|
||||
|
||||
# Settings of when to display what disk space warning
|
||||
diskspace:
|
||||
|
||||
|
||||
@@ -110,6 +110,14 @@ ClientClosed
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that disconnected
|
||||
|
||||
ConnectivityChanged
|
||||
The server's internet connectivity changed
|
||||
|
||||
Payload:
|
||||
|
||||
* ``old``: Old connectivity value (true for online, false for offline)
|
||||
* ``new``: New connectivity value (true for online, false for offline)
|
||||
|
||||
Printer communication
|
||||
---------------------
|
||||
|
||||
|
||||
@@ -87,6 +87,9 @@ There are a few additional template variables available for the following specif
|
||||
|
||||
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. See
|
||||
``last_position`` above for the structure to expect here.
|
||||
|
||||
**Please note:** This will not be available if you disable
|
||||
"Log position on pause" under Settings > Serial > Advanced options!
|
||||
* ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above
|
||||
for the structure to expect here.
|
||||
|
||||
@@ -94,6 +97,9 @@ There are a few additional template variables available for the following specif
|
||||
|
||||
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
|
||||
See ``last_position`` above for the structure to expect here.
|
||||
|
||||
**Please note:** This will not be available if you disable
|
||||
"Log position on cancel" under Settings > Serial > Advanced options!
|
||||
* ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
|
||||
for the structure to expect here.
|
||||
|
||||
|
||||
@@ -14,4 +14,5 @@ Internal Modules
|
||||
server.rst
|
||||
settings.rst
|
||||
slicing.rst
|
||||
users.rst
|
||||
util.rst
|
||||
@@ -0,0 +1,9 @@
|
||||
.. _sec-modules-users:
|
||||
|
||||
octoprint.users
|
||||
---------------
|
||||
|
||||
.. automodule:: octoprint.users
|
||||
:members:
|
||||
|
||||
|
||||
+49
-9
@@ -389,7 +389,7 @@ This describes actually four hooks:
|
||||
* ``octoprint.comm.protocol.gcode.sending``
|
||||
* ``octoprint.comm.protocol.gcode.sent``
|
||||
|
||||
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs)
|
||||
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, *args, **kwargs)
|
||||
|
||||
Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases
|
||||
are the following:
|
||||
@@ -426,7 +426,7 @@ This describes actually four hooks:
|
||||
|
||||
* ``None``: Don't change anything. Note that Python functions will also automatically return ``None`` if
|
||||
an empty ``return`` statement is used or just nothing is returned explicitly from the handler. Hence, the following
|
||||
examples are all falling into this category:
|
||||
examples are all falling into this category and equivalent:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -451,21 +451,24 @@ This describes actually four hooks:
|
||||
should use this option.
|
||||
* A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``.
|
||||
Handlers which wish to rewrite both the command and the command type should use this option.
|
||||
* A list of any of the above to allow for expanding one command into
|
||||
* **"queuing" phase only**: A list of any of the above to allow for expanding one command into
|
||||
many. The following example shows how any queued command could be turned into a sequence of a temperature query,
|
||||
line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example
|
||||
does not make a lot of sense to be quite honest):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
|
||||
if gcode or not cmd.startswith("@foo"):
|
||||
return
|
||||
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
|
||||
if gcode or not cmd.startswith("@foo"):
|
||||
return
|
||||
|
||||
return [("M105", "temperature_poll"),
|
||||
("M110",),
|
||||
"M117 echo foo: {}".format(cmd)]
|
||||
return [("M105", "temperature_poll"), # 2-tuple, command & command type
|
||||
("M110",), # 1-tuple, just the command
|
||||
"M117 echo foo: {}".format(cmd)] # string, just the command
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.comm.protocol.gcode.queuing": rewrite_foo
|
||||
}
|
||||
|
||||
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type``
|
||||
to one already in the queue will give an error.
|
||||
@@ -488,6 +491,8 @@ This describes actually four hooks:
|
||||
:param str cmd_type: Type of command, e.g. ``temperature_poll`` for temperature polling or ``sd_status_poll`` for SD
|
||||
printing status polling.
|
||||
:param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed
|
||||
:param str subcode: Parsed subcode of the GCODE command, e.g. ``1`` for ``M80.1``. Will be None if no subcode was provided
|
||||
or no command could be parsed.
|
||||
:return: None, 1-tuple, 2-tuple or string, see the description above for details.
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-gcode-received:
|
||||
@@ -941,3 +946,38 @@ octoprint.ui.web.templatetypes
|
||||
:param dict template_sorting: read-only dictionary of currently configured template sorting specifications
|
||||
:return: a list of 3-tuples (template type, rule, sorting spec)
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-users-factory:
|
||||
|
||||
octoprint.users.factory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
|
||||
|
||||
Return a :class:`~octoprint.users.UserManager` instance to use as global user manager object. This will
|
||||
be called only once during initial server startup.
|
||||
|
||||
The provided ``components`` is a dictionary containing the already initialized system components:
|
||||
|
||||
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
|
||||
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
|
||||
* ``event_bus``: The :class:`~octoprint.events.EventManager`
|
||||
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
|
||||
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
|
||||
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
|
||||
* ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager`
|
||||
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
|
||||
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
|
||||
If no of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
|
||||
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
|
||||
:class:`~octoprint.users.FilebasedUserManager` will be instantiated, linked to the default user storage
|
||||
file ``~/.octoprint/users.yaml``.
|
||||
|
||||
:param dict components: System components to use for user manager instance initialization
|
||||
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
|
||||
:return: The ``userManager`` instance to use globally.
|
||||
:rtype: UserManager subclass or None
|
||||
|
||||
@@ -45,6 +45,8 @@ An overview of these properties follows.
|
||||
OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`.
|
||||
``self._user_manager``
|
||||
OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`.
|
||||
``self._connectivity_checker``
|
||||
OctoPrint's connectivity checker, an instance of :class:`octoprint.util.ConnectivityChecker`.
|
||||
|
||||
.. seealso::
|
||||
|
||||
|
||||
@@ -49,7 +49,8 @@ INSTALL_REQUIRES = [
|
||||
"scandir>=1.3,<1.4",
|
||||
"websocket-client>=0.40,<0.41",
|
||||
"python-dateutil>=2.6,<2.7",
|
||||
"wrapt>=1.10.10,<1.11"
|
||||
"wrapt>=1.10.10,<1.11",
|
||||
"futures>=3.1.1,<3.2"
|
||||
]
|
||||
|
||||
if sys.platform == "darwin":
|
||||
|
||||
+47
-24
@@ -9,7 +9,7 @@ import json
|
||||
|
||||
import octoprint_client
|
||||
|
||||
from octoprint.cli import get_ctx_obj_option
|
||||
from octoprint.cli import get_ctx_obj_option, bulk_options
|
||||
from octoprint import init_settings, FatalStartupError
|
||||
|
||||
|
||||
@@ -23,43 +23,66 @@ class JsonStringParamType(click.ParamType):
|
||||
self.fail("%s is not a valid json string" % value, param, ctx)
|
||||
|
||||
|
||||
def create_client(settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None):
|
||||
assert(host is not None or settings is not None)
|
||||
assert(port is not None or settings is not None)
|
||||
assert(apikey is not None or settings is not None)
|
||||
|
||||
if not host:
|
||||
host = settings.get(["server", "host"])
|
||||
host = host if host != "0.0.0.0" else "127.0.0.1"
|
||||
if not port:
|
||||
port = settings.getInt(["server", "port"])
|
||||
|
||||
if not apikey:
|
||||
apikey = settings.get(["api", "key"])
|
||||
|
||||
baseurl = octoprint_client.build_base_url(https=https,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
host=host,
|
||||
port=port,
|
||||
prefix=prefix)
|
||||
|
||||
return octoprint_client.Client(baseurl, apikey)
|
||||
|
||||
|
||||
client_options = bulk_options([
|
||||
click.option("--apikey", "-a", type=click.STRING),
|
||||
click.option("--host", "-h", type=click.STRING),
|
||||
click.option("--port", "-p", type=click.INT),
|
||||
click.option("--httpuser", type=click.STRING),
|
||||
click.option("--httppass", type=click.STRING),
|
||||
click.option("--https", is_flag=True),
|
||||
click.option("--prefix", type=click.STRING)
|
||||
])
|
||||
"""Common options to configure an API client."""
|
||||
|
||||
|
||||
@click.group()
|
||||
def client_commands():
|
||||
pass
|
||||
|
||||
|
||||
@client_commands.group("client", context_settings=dict(ignore_unknown_options=True))
|
||||
@click.option("--apikey", "-a", type=click.STRING)
|
||||
@click.option("--host", "-h", type=click.STRING)
|
||||
@click.option("--port", "-p", type=click.INT)
|
||||
@click.option("--httpuser", type=click.STRING)
|
||||
@click.option("--httppass", type=click.STRING)
|
||||
@click.option("--https", is_flag=True)
|
||||
@click.option("--prefix", type=click.STRING)
|
||||
@client_options
|
||||
@click.pass_context
|
||||
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
|
||||
"""Basic API client."""
|
||||
try:
|
||||
settings = None
|
||||
if not host or not port or not apikey:
|
||||
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
||||
|
||||
if not host:
|
||||
host = settings.get(["server", "host"])
|
||||
host = host if host != "0.0.0.0" else "127.0.0.1"
|
||||
if not port:
|
||||
port = settings.getInt(["server", "port"])
|
||||
ctx.obj.client = create_client(settings=settings,
|
||||
apikey=apikey,
|
||||
host=host,
|
||||
port=port,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
https=https,
|
||||
prefix=prefix)
|
||||
|
||||
if not apikey:
|
||||
apikey = settings.get(["api", "key"])
|
||||
|
||||
baseurl = octoprint_client.build_base_url(https=https,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
host=host,
|
||||
port=port,
|
||||
prefix=prefix)
|
||||
|
||||
ctx.obj.client = octoprint_client.Client(baseurl, apikey)
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error initializing the client.", err=True)
|
||||
|
||||
@@ -60,6 +60,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
# fetch registered hooks
|
||||
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARN)
|
||||
|
||||
self._initialized = True
|
||||
|
||||
def list_commands(self, ctx):
|
||||
@@ -88,14 +90,14 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
continue
|
||||
result[name + self.sep + command.name] = command
|
||||
except:
|
||||
self._logger.exception("Error while retrieving cli commants for plugin {}".format(name))
|
||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name))
|
||||
|
||||
return result
|
||||
|
||||
@click.group()
|
||||
@pass_octoprint_ctx
|
||||
def plugin_commands(obj):
|
||||
logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN)
|
||||
pass
|
||||
|
||||
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
|
||||
def plugins():
|
||||
|
||||
@@ -27,9 +27,10 @@ def all_events():
|
||||
|
||||
|
||||
class Events(object):
|
||||
# application startup
|
||||
# server
|
||||
STARTUP = "Startup"
|
||||
SHUTDOWN = "Shutdown"
|
||||
CONNECTIVITY_CHANGED = "ConnectivityChanged"
|
||||
|
||||
# connect/disconnect to printer
|
||||
CONNECTING = "Connecting"
|
||||
@@ -53,10 +54,10 @@ class Events(object):
|
||||
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
|
||||
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
|
||||
|
||||
FILE_ADDED = "FileAdded",
|
||||
FILE_REMOVED = "FileRemoved",
|
||||
FOLDER_ADDED = "FolderAdded",
|
||||
FOLDER_REMOVED = "FolderRemoved",
|
||||
FILE_ADDED = "FileAdded"
|
||||
FILE_REMOVED = "FileRemoved"
|
||||
FOLDER_ADDED = "FolderAdded"
|
||||
FOLDER_REMOVED = "FolderRemoved"
|
||||
|
||||
# SD Upload
|
||||
TRANSFER_STARTED = "TransferStarted"
|
||||
|
||||
@@ -180,9 +180,12 @@ class FileManager(object):
|
||||
import octoprint.settings
|
||||
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
|
||||
|
||||
def initialize(self):
|
||||
def initialize(self, process_backlog=False):
|
||||
self.reload_plugins()
|
||||
if process_backlog:
|
||||
self.process_backlog()
|
||||
|
||||
def process_backlog(self):
|
||||
def worker():
|
||||
self._logger.info("Adding backlog items from all storage types to analysis queue...".format(**locals()))
|
||||
for storage_type, storage_manager in self._storage_managers.items():
|
||||
@@ -253,6 +256,26 @@ class FileManager(object):
|
||||
def default_slicer(self):
|
||||
return self._slicing_manager.default_slicer
|
||||
|
||||
def analyse(self, destination, path, printer_profile_id=None):
|
||||
if not self.file_exists(destination, path):
|
||||
return
|
||||
|
||||
if printer_profile_id is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
else:
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
self._analysis_queue.dequeue(queue_entry)
|
||||
|
||||
queue_entry = self._analysis_queue_entry(destination, path, printer_profile=printer_profile)
|
||||
if queue_entry:
|
||||
return self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
|
||||
return False
|
||||
|
||||
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
|
||||
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
|
||||
absolute_source_path = self.path_on_disk(source_location, source_path)
|
||||
|
||||
@@ -135,3 +135,16 @@ def get_divider_line(c, message=None, length=78, indent=3):
|
||||
return c * indent + " " + message + " " + c * (length - indent - 2 - len(message))
|
||||
else:
|
||||
return c * indent + " " + message
|
||||
|
||||
|
||||
def prefix_multilines(text, prefix=": "):
|
||||
lines = text.splitlines()
|
||||
if not lines:
|
||||
return ""
|
||||
|
||||
if len(lines) == 1:
|
||||
return lines[0]
|
||||
|
||||
return lines[0] + "\n" + "\n".join(map(lambda line: prefix + line,
|
||||
lines[1:]))
|
||||
|
||||
@@ -45,8 +45,7 @@ def _validate_plugin(phase, plugin_info):
|
||||
return True
|
||||
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
|
||||
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None,
|
||||
plugin_checked_module_dependencies=None):
|
||||
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
|
||||
"""
|
||||
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
|
||||
singleton.
|
||||
@@ -72,8 +71,6 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will
|
||||
not be enabled since they might depend on functionality that is no longer available.
|
||||
plugin_validators (list): A list of additional plugin validators through which to process each plugin.
|
||||
plugin_checked_module_dependencies (dict): A dictionary of package name-version-pairs for which to enable
|
||||
dependency checking during plugin loading.
|
||||
|
||||
Returns:
|
||||
PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin
|
||||
@@ -117,9 +114,6 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
plugin_validators = [_validate_plugin]
|
||||
else:
|
||||
plugin_validators.append(_validate_plugin)
|
||||
if plugin_checked_module_dependencies is None:
|
||||
from octoprint import __version__ as octoprint_version
|
||||
plugin_checked_module_dependencies = dict(octoprint=octoprint_version)
|
||||
|
||||
_instance = PluginManager(plugin_folders,
|
||||
plugin_types,
|
||||
@@ -128,8 +122,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
plugin_disabled_list=plugin_disabled_list,
|
||||
plugin_restart_needing_hooks=plugin_restart_needing_hooks,
|
||||
plugin_obsolete_hooks=plugin_obsolete_hooks,
|
||||
plugin_validators=plugin_validators,
|
||||
plugin_checked_module_dependencies=plugin_checked_module_dependencies)
|
||||
plugin_validators=plugin_validators)
|
||||
else:
|
||||
raise ValueError("Plugin Manager not initialized yet")
|
||||
return _instance
|
||||
@@ -184,7 +177,7 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
|
||||
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
|
||||
|
||||
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None):
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
|
||||
"""
|
||||
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
|
||||
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
|
||||
@@ -220,6 +213,8 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
|
||||
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
|
||||
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
|
||||
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
|
||||
is determined be presence of injected ``_identifier`` property.
|
||||
|
||||
"""
|
||||
|
||||
@@ -232,6 +227,9 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
|
||||
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
|
||||
for plugin in plugins:
|
||||
if initialized and not hasattr(plugin, "_identifier"):
|
||||
continue
|
||||
|
||||
if hasattr(plugin, method):
|
||||
try:
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
|
||||
@@ -41,8 +41,6 @@ try:
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
from octoprint.util.version import version_matches_spec
|
||||
|
||||
EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version")
|
||||
FolderOrigin = namedtuple("FolderOrigin", "type, folder")
|
||||
|
||||
@@ -466,7 +464,7 @@ class PluginManager(object):
|
||||
|
||||
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None,
|
||||
plugin_disabled_list=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None,
|
||||
plugin_validators=None, plugin_checked_module_dependencies=None):
|
||||
plugin_validators=None):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
if logging_prefix is None:
|
||||
@@ -487,7 +485,6 @@ class PluginManager(object):
|
||||
self.plugin_restart_needing_hooks = plugin_restart_needing_hooks
|
||||
self.plugin_obsolete_hooks = plugin_obsolete_hooks
|
||||
self.plugin_validators = plugin_validators
|
||||
self.plugin_dependency_checks = plugin_checked_module_dependencies
|
||||
self.logging_prefix = logging_prefix
|
||||
|
||||
self.enabled_plugins = dict()
|
||||
@@ -622,20 +619,6 @@ class PluginManager(object):
|
||||
module_name = entry_point.module_name
|
||||
version = entry_point.dist.version
|
||||
|
||||
if self.plugin_dependency_checks:
|
||||
requires = entry_point.dist.requires()
|
||||
missing_requirements = []
|
||||
for require in requires:
|
||||
if require.key in self.plugin_dependency_checks:
|
||||
available_version = self.plugin_dependency_checks[require.key]
|
||||
spec = str(require.specifier)
|
||||
if not version_matches_spec(available_version, spec, package=require.key, base=True):
|
||||
missing_requirements.append("{}{}".format(require.key, spec))
|
||||
|
||||
if missing_requirements:
|
||||
self.logger.warn("Plugin \"{}\" is missing requirements, skipping it: {}".format(key, ", ".join(missing_requirements)))
|
||||
continue
|
||||
|
||||
if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
# plugin is already defined or marked as uninstalled, ignore it
|
||||
continue
|
||||
@@ -678,8 +661,7 @@ class PluginManager(object):
|
||||
|
||||
return result
|
||||
|
||||
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None,
|
||||
author=None, url=None, license=None):
|
||||
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None):
|
||||
# TODO error handling
|
||||
try:
|
||||
if folder:
|
||||
|
||||
@@ -28,7 +28,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.EventHandlerPlugin):
|
||||
|
||||
def __init__(self):
|
||||
self._cached_channel_configs = None
|
||||
@@ -210,6 +211,14 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
from octoprint.events import Events
|
||||
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
|
||||
return
|
||||
self._fetch_all_channels_async()
|
||||
|
||||
# Internal Tools
|
||||
|
||||
def _mark_read_until(self, channel, until):
|
||||
@@ -266,6 +275,11 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
safe_key = self._slugify(key)
|
||||
return self._get_channel_configs(force=force).get(safe_key)
|
||||
|
||||
def _fetch_all_channels_async(self, force=False):
|
||||
thread = threading.Thread(target=self._fetch_all_channels, kwargs=dict(force=force))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def _fetch_all_channels(self, force=False):
|
||||
"""Fetch all channel feeds from cache or network."""
|
||||
|
||||
@@ -298,7 +312,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
if data is None:
|
||||
# cache not allowed or empty, fetch from network
|
||||
data = self._get_channel_data_from_network(key, config)
|
||||
if self._connectivity_checker.online:
|
||||
data = self._get_channel_data_from_network(key, config)
|
||||
else:
|
||||
self._logger.info("Looks like we are offline, can't fetch announcements for channel {} from network".format(key))
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
var icon = data.enabled ? "fa fa-circle" : "fa fa-circle-o";
|
||||
var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off";
|
||||
var disabled = (self.enableToggle(data)) ? "" : " disabled";
|
||||
|
||||
return icon + disabled;
|
||||
@@ -317,7 +317,13 @@ $(function() {
|
||||
self.announcementDialog = $("#plugin_announcements_dialog");
|
||||
self.announcementDialogContent = $("#plugin_announcements_dialog_content");
|
||||
self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs");
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
if (!payload || !payload.new) return;
|
||||
self.retrieveData();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
|
||||
@@ -25,6 +25,13 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
names = self._get_subwizard_attrs("_get_", "_wizard_name")
|
||||
additional = self._get_subwizard_attrs("_get_", "_additional_wizard_template_data")
|
||||
|
||||
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
|
||||
firstrun = self._settings.global_get(["server", "firstRun"])
|
||||
|
||||
if not firstrun:
|
||||
required = dict((key, value) for key, value in required.items()
|
||||
if not firstrunonly.get(key, lambda: False)())
|
||||
|
||||
result = list()
|
||||
for key, method in required.items():
|
||||
if not method():
|
||||
@@ -59,8 +66,16 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~~ WizardPlugin API
|
||||
|
||||
def is_wizard_required(self):
|
||||
methods = self._get_subwizard_attrs("_is_", "_wizard_required")
|
||||
return self._settings.global_get(["server", "firstRun"]) and any(map(lambda m: m(), methods.values()))
|
||||
required = self._get_subwizard_attrs("_is_", "_wizard_required")
|
||||
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
|
||||
firstrun = self._settings.global_get(["server", "firstRun"])
|
||||
|
||||
if not firstrun:
|
||||
required = dict((key, value) for key, value in required.items()
|
||||
if not firstrunonly.get(key, lambda: False)())
|
||||
any_required = any(map(lambda m: m(), required.values()))
|
||||
|
||||
return any_required
|
||||
|
||||
def get_wizard_details(self):
|
||||
result = dict()
|
||||
@@ -71,8 +86,14 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
return result
|
||||
|
||||
def get_wizard_version(self):
|
||||
return 1
|
||||
|
||||
#~~ ACL subwizard
|
||||
|
||||
def _is_acl_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_acl_wizard_required(self):
|
||||
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
|
||||
|
||||
@@ -114,6 +135,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
#~~ Webcam subwizard
|
||||
|
||||
def _is_webcam_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_webcam_wizard_required(self):
|
||||
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
|
||||
webcam_stream_url = self._settings.global_get(["webcam", "stream"])
|
||||
@@ -129,6 +153,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
#~~ Server commands subwizard
|
||||
|
||||
def _is_servercommands_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_servercommands_wizard_required(self):
|
||||
system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"])
|
||||
system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
@@ -142,8 +169,28 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
def _get_servercommands_wizard_name(self):
|
||||
return gettext("Server Commands")
|
||||
|
||||
#~~ Online check subwizard
|
||||
|
||||
def _is_onlinecheck_wizard_firstrunonly(self):
|
||||
return False
|
||||
|
||||
def _is_onlinecheck_wizard_required(self):
|
||||
return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None
|
||||
|
||||
def _get_onlinecheck_wizard_details(self):
|
||||
return dict(required=self._is_onlinecheck_wizard_required())
|
||||
|
||||
def _get_onlinecheck_wizard_name(self):
|
||||
return gettext("Online connectivity check")
|
||||
|
||||
def _get_onlinecheck_additional_wizard_template_data(self):
|
||||
return dict(mandatory=self._is_onlinecheck_wizard_required())
|
||||
|
||||
#~~ Printer profile subwizard
|
||||
|
||||
def _is_printerprofile_wizard_firstrunonly(self):
|
||||
return True
|
||||
|
||||
def _is_printerprofile_wizard_required(self):
|
||||
return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
|
||||
|
||||
|
||||
@@ -125,6 +125,88 @@ $(function() {
|
||||
self.settingsViewModel = parameters[0];
|
||||
}
|
||||
|
||||
function CoreWizardOnlineCheckViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.settingsViewModel = parameters[0];
|
||||
|
||||
self.setup = ko.observable(false);
|
||||
|
||||
self.decision = ko.observable();
|
||||
self.required = false;
|
||||
self.active = false;
|
||||
|
||||
self.enableOnlineCheck = function() {
|
||||
self.settingsViewModel.server_onlineCheck_enabled(true);
|
||||
self.decision(true);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.disableOnlineCheck = function() {
|
||||
self.settingsViewModel.server_onlineCheck_enabled(false);
|
||||
self.decision(false);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") || self.setup()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onBeforeWizardFinish = function() {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (self.setup()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
self._showDecisionNeededDialog();
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardPreventSettingsRefreshDialog = function() {
|
||||
return self.active;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required;
|
||||
};
|
||||
|
||||
self._showDecisionNeededDialog = function() {
|
||||
showMessageDialog({
|
||||
title: gettext("Please set up the online connectivity check"),
|
||||
message: gettext("You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing.")
|
||||
});
|
||||
};
|
||||
|
||||
self._sendData = function() {
|
||||
var data = {
|
||||
server: {
|
||||
onlineCheck: {
|
||||
enabled: self.settingsViewModel.server_onlineCheck_enabled(),
|
||||
interval: self.settingsViewModel.server_onlineCheck_interval(),
|
||||
host: self.settingsViewModel.server_onlineCheck_host(),
|
||||
port: self.settingsViewModel.server_onlineCheck_port()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.active = true;
|
||||
self.settingsViewModel.saveData(data)
|
||||
.done(function() {
|
||||
self.setup(true);
|
||||
self.active = false;
|
||||
});
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
function CoreWizardPrinterProfileViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -172,6 +254,10 @@ $(function() {
|
||||
CoreWizardServerCommandsViewModel,
|
||||
["settingsViewModel"],
|
||||
"#wizard_plugin_corewizard_servercommands"
|
||||
], [
|
||||
CoreWizardOnlineCheckViewModel,
|
||||
["settingsViewModel"],
|
||||
"#wizard_plugin_corewizard_onlinecheck"
|
||||
], [
|
||||
CoreWizardPrinterProfileViewModel,
|
||||
["printerProfilesViewModel"],
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<h3>{{ _('Configure the connectivity check') }}</h3>
|
||||
|
||||
{% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %}
|
||||
|
||||
<p>{% trans %}
|
||||
If it is disabled OctoPrint will always assume to have a working connection to the internet.
|
||||
If that should not actually be the case, server startups, update checks and the like might take longer.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<p>{% trans %}
|
||||
OctoPrint comes preconfigured to perform the connectivity check every 15 minutes. You may change the value here.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<form class="form-horizontal" data-bind="with: settingsViewModel, enable: !setup(), css {disabled: setup()}">
|
||||
{% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
|
||||
</form>
|
||||
|
||||
<p>{% trans %}
|
||||
OctoPrint comes preconfigured to utilize Google's DNS server <code>8.8.8.8</code>, port 53 for the connectivity check (if
|
||||
it's enabled). If you have concerns about using that, define the IP and port of a different online server that you
|
||||
trust and that has a high availability.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<form class="form-horizontal" data-bind="with: settingsViewModel, enable: !setup(), css {disabled: setup()}">
|
||||
{% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %}
|
||||
</form>
|
||||
|
||||
<p>{% trans %}
|
||||
Finally, please decide on whether to enable or disable the connectivity check. You may change the configuration at
|
||||
any time to a later date through Settings > Server right from within OctoPrint.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<div class="row-fluid">
|
||||
<a href="#" class="btn span6" data-bind="click: function() { if(!setup()){disableOnlineCheck()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Connectivity Check') }}</a>
|
||||
<a href="#" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enableOnlineCheck()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Enable Connectivity Check') }}</a>
|
||||
</div>
|
||||
|
||||
<div class="onlinecheck_decision" style="display: none" data-bind="visible: setup()">
|
||||
<div class="text-center" style="display: none" data-bind="visible: decision()">{% trans %}
|
||||
Connectivity check is <strong class="text-success">enabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
<div class="text-center" style="display: none" data-bind="visible: !decision()">{% trans %}
|
||||
Connectivity check is <strong class="text-danger">disabled</strong>.
|
||||
{% endtrans %}</div>
|
||||
</div>
|
||||
@@ -14,7 +14,6 @@ from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import admin_permission, VERSION
|
||||
from octoprint.util.pip import LocalPipCaller, UnknownPip
|
||||
from octoprint.util.version import parse_version, version_matches_any_spec
|
||||
|
||||
from flask import jsonify, make_response
|
||||
from flask.ext.babel import gettext
|
||||
@@ -37,7 +36,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.BlueprintPlugin):
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.EventHandlerPlugin):
|
||||
|
||||
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
|
||||
|
||||
@@ -101,13 +101,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._console_logger.propagate = False
|
||||
|
||||
# decouple repository fetching from server startup
|
||||
def fetch_data():
|
||||
self._repository_available = self._fetch_repository_from_disk()
|
||||
self._notices_available = self._fetch_notices_from_disk()
|
||||
|
||||
thread = threading.Thread(target=fetch_data)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
self._fetch_all_data(async=True)
|
||||
|
||||
##~~ SettingsPlugin
|
||||
|
||||
@@ -198,6 +192,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e)))
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
from octoprint.events import Events
|
||||
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
|
||||
return
|
||||
self._fetch_all_data(async=True)
|
||||
|
||||
##~~ SimpleApiPlugin
|
||||
|
||||
def get_api_commands(self):
|
||||
@@ -240,7 +242,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
additional_args=self._settings.get(["pip_args"]),
|
||||
python=sys.executable
|
||||
),
|
||||
safe_mode=safe_mode)
|
||||
safe_mode=safe_mode,
|
||||
online=self._connectivity_checker.online)
|
||||
|
||||
def etag():
|
||||
import hashlib
|
||||
@@ -251,6 +254,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
hash.update(str(self._notices_available))
|
||||
hash.update(repr(self._notices))
|
||||
hash.update(repr(safe_mode))
|
||||
hash.update(repr(self._connectivity_checker.online))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
@@ -680,6 +684,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable:
|
||||
self._pending_disable.add(plugin.key)
|
||||
|
||||
def _fetch_all_data(self, async=False):
|
||||
def run():
|
||||
self._repository_available = self._fetch_repository_from_disk()
|
||||
self._notices_available = self._fetch_notices_from_disk()
|
||||
|
||||
if async:
|
||||
thread = threading.Thread(target=run)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
else:
|
||||
run()
|
||||
|
||||
def _fetch_repository_from_disk(self):
|
||||
repo_data = None
|
||||
if os.path.isfile(self._repository_cache_path):
|
||||
@@ -697,6 +713,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return self._refresh_repository(repo_data=repo_data)
|
||||
|
||||
def _fetch_repository_from_url(self):
|
||||
if not self._connectivity_checker.online:
|
||||
self._logger.info("Looks like we are offline, can't fetch repository from network")
|
||||
return None
|
||||
|
||||
repository_url = self._settings.get(["repository"])
|
||||
try:
|
||||
r = requests.get(repository_url, timeout=30)
|
||||
@@ -724,7 +744,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return False
|
||||
|
||||
current_os = self._get_os()
|
||||
parsed_octoprint_version = self._get_octoprint_version()
|
||||
octoprint_version = self._get_octoprint_version(base=True)
|
||||
|
||||
def map_repository_entry(entry):
|
||||
result = copy.deepcopy(entry)
|
||||
@@ -739,7 +759,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
if "compatibility" in entry:
|
||||
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]):
|
||||
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(parsed_octoprint_version, entry["compatibility"]["octoprint"])
|
||||
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(octoprint_version, entry["compatibility"]["octoprint"])
|
||||
|
||||
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
|
||||
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
|
||||
@@ -759,13 +779,17 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
import json
|
||||
with open(self._notices_cache_path) as f:
|
||||
notice_data = json.load(f)
|
||||
self._logger.info("Loaded notices from disk, was still valid")
|
||||
self._logger.info("Loaded notice data from disk, was still valid")
|
||||
except:
|
||||
self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path))
|
||||
|
||||
return self._refresh_notices(notice_data=notice_data)
|
||||
|
||||
def _fetch_notices_from_url(self):
|
||||
if not self._connectivity_checker.online:
|
||||
self._logger.info("Looks like we are offline, can't fetch notices from network")
|
||||
return None
|
||||
|
||||
notices_url = self._settings.get(["notices"])
|
||||
try:
|
||||
r = requests.get(notices_url, timeout=30)
|
||||
@@ -818,15 +842,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
|
||||
"""
|
||||
|
||||
spec_matcher = ("<", "<=", "!=", "==", ">=", ">", "~=", "===")
|
||||
specs = map(lambda x: x if any(x.startswith(c) for c in spec_matcher) else ">={}".format(x),
|
||||
compatibility_entries)
|
||||
for octo_compat in compatibility_entries:
|
||||
try:
|
||||
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
|
||||
octo_compat = ">={}".format(octo_compat)
|
||||
|
||||
try:
|
||||
return version_matches_any_spec(octoprint_version, specs, package="OctoPrint", base=True)
|
||||
except:
|
||||
self._logger.exception("Something is wrong with these compatibility specs: {!r}".format(specs))
|
||||
return False
|
||||
s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat))
|
||||
if octoprint_version in s:
|
||||
break
|
||||
except:
|
||||
self._logger.exception("Something is wrong with this compatibility string for OctoPrint: {}".format(octo_compat))
|
||||
else:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _is_os_compatible(current_os, compatibility_entries):
|
||||
@@ -860,14 +889,37 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
else:
|
||||
return "unmapped"
|
||||
|
||||
@staticmethod
|
||||
def _get_octoprint_version_string():
|
||||
from octoprint import __version__ as octoprint_version
|
||||
return octoprint_version
|
||||
def _get_octoprint_version_string(self):
|
||||
return VERSION
|
||||
|
||||
@staticmethod
|
||||
def _get_octoprint_version(base=False):
|
||||
return parse_version(PluginManagerPlugin._get_octoprint_version_string(), base=base)
|
||||
def _get_octoprint_version(self, base=False):
|
||||
octoprint_version_string = self._get_octoprint_version_string()
|
||||
|
||||
if "-" in octoprint_version_string:
|
||||
octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")]
|
||||
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
|
||||
|
||||
# A leading v is common in github release tags and old setuptools doesn't remove it. While OctoPrint's
|
||||
# versions should never contains such a prefix, we'll make sure to have stuff behave the same
|
||||
# regardless of setuptools version anyhow.
|
||||
if octoprint_version and isinstance(octoprint_version, tuple) and octoprint_version[0].lower() == "*v":
|
||||
octoprint_version = octoprint_version[1:]
|
||||
|
||||
if base:
|
||||
if isinstance(octoprint_version, tuple):
|
||||
# old setuptools
|
||||
base_version = []
|
||||
for part in octoprint_version:
|
||||
if part.startswith("*"):
|
||||
break
|
||||
base_version.append(part)
|
||||
base_version.append("*final")
|
||||
octoprint_version = tuple(base_version)
|
||||
else:
|
||||
# new setuptools
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
|
||||
return octoprint_version
|
||||
|
||||
@property
|
||||
def _reconnect_hooks(self):
|
||||
|
||||
@@ -174,6 +174,7 @@ $(function() {
|
||||
self.pipPython = ko.observable();
|
||||
|
||||
self.safeMode = ko.observable();
|
||||
self.online = ko.observable();
|
||||
|
||||
self.pipUseUserString = ko.pureComputed(function() {
|
||||
return self.pipUseUser() ? "yes" : "no";
|
||||
@@ -234,7 +235,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.enableRepoInstall = function(data) {
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data);
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && self.isCompatible(data);
|
||||
};
|
||||
|
||||
self.invalidUrl = ko.pureComputed(function() {
|
||||
@@ -244,7 +245,7 @@ $(function() {
|
||||
|
||||
self.enableUrlInstall = ko.pureComputed(function() {
|
||||
var url = self.installUrl();
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
});
|
||||
|
||||
self.invalidArchive = ko.pureComputed(function() {
|
||||
@@ -321,6 +322,7 @@ $(function() {
|
||||
self._fromPipResponse(data.pip, options);
|
||||
|
||||
self.safeMode(data.safe_mode || false);
|
||||
self.online(data.online !== undefined ? data.online : true);
|
||||
};
|
||||
|
||||
self._fromPluginsResponse = function(data, options) {
|
||||
@@ -814,7 +816,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-circle-o" : "fa fa-circle";
|
||||
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on";
|
||||
var disabled = (self.enableToggle(data)) ? "" : " disabled";
|
||||
|
||||
return icon + disabled;
|
||||
@@ -1020,6 +1022,10 @@ $(function() {
|
||||
self._closeAllNotifications();
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
self.requestData({eval_notices: true});
|
||||
};
|
||||
|
||||
self._closeAllNotifications = function() {
|
||||
if (self.notifications) {
|
||||
_.each(self.notifications, function(notification) {
|
||||
|
||||
@@ -20,6 +20,13 @@
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro pluginmanager_offline() %}
|
||||
<div class="alert" data-bind="visible: !online()">{% trans %}
|
||||
It looks like OctoPrint has currently no connection to the internet. Due to that it's not possible
|
||||
to install new plugins from the plugin repository or archive URLs.
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
@@ -124,6 +131,7 @@
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
{{ pluginmanager_offline() }}
|
||||
<h4 style="position: relative">
|
||||
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
|
||||
<div class="dropdown pull-right">
|
||||
|
||||
@@ -15,6 +15,9 @@ import time
|
||||
import logging
|
||||
import logging.handlers
|
||||
import hashlib
|
||||
import traceback
|
||||
|
||||
from concurrent import futures
|
||||
|
||||
from . import version_checks, updaters, exceptions, util, cli
|
||||
|
||||
@@ -34,7 +37,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.WizardPlugin):
|
||||
octoprint.plugin.WizardPlugin,
|
||||
octoprint.plugin.EventHandlerPlugin):
|
||||
|
||||
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
|
||||
|
||||
@@ -44,7 +48,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._configured_checks = None
|
||||
self._refresh_configured_checks = False
|
||||
|
||||
self._get_versions_mutex = threading.Lock()
|
||||
self._get_versions_mutex = threading.RLock()
|
||||
self._get_versions_data = None
|
||||
self._get_versions_data_ready = threading.Event()
|
||||
|
||||
self._version_cache = dict()
|
||||
self._version_cache_ttl = 0
|
||||
@@ -467,15 +473,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
def view():
|
||||
try:
|
||||
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
|
||||
|
||||
# we don't want to transfer python_checker or python_updater values through json - replace with True
|
||||
for key, data in information.items():
|
||||
if "check" in data:
|
||||
if "python_checker" in data["check"]:
|
||||
data["check"]["python_checker"] = True
|
||||
if "python_updater" in data["check"]:
|
||||
data["check"]["python_updater"] = True
|
||||
|
||||
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
|
||||
information=information,
|
||||
timestamp=self._version_cache_timestamp))
|
||||
@@ -502,9 +499,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash.update(repr(data["information"]))
|
||||
hash.update(str(data["available"]))
|
||||
hash.update(str(data["possible"]))
|
||||
hash.update(str(data.get("online", None)))
|
||||
|
||||
hash.update(",".join(targets))
|
||||
hash.update(str(self._version_cache_timestamp))
|
||||
hash.update(str(self._connectivity_checker.online))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
@@ -566,6 +565,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
checkout_folder = self._get_octoprint_checkout_folder(checks=checks)
|
||||
return check and "update_script" in check and not checkout_folder
|
||||
|
||||
##~~ EventHandlerPlugin API
|
||||
|
||||
def on_event(self, event, payload):
|
||||
from octoprint.events import Events
|
||||
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
|
||||
return
|
||||
|
||||
thread = threading.Thread(target=self.get_current_versions)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
#~~ Updater
|
||||
|
||||
def get_current_versions(self, check_targets=None, force=False):
|
||||
@@ -585,53 +595,91 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
information = dict()
|
||||
|
||||
# we don't want to do the same work twice, so let's use a lock
|
||||
with self._get_versions_mutex:
|
||||
for target, check in checks.items():
|
||||
if not target in check_targets:
|
||||
continue
|
||||
if self._get_versions_mutex.acquire(False):
|
||||
self._get_versions_data_ready.clear()
|
||||
try:
|
||||
futures_to_result = dict()
|
||||
online = self._connectivity_checker.check_immediately()
|
||||
self._logger.debug("Looks like we are {}".format("online" if online else "offline"))
|
||||
|
||||
if not check:
|
||||
continue
|
||||
with futures.ThreadPoolExecutor(max_workers=5) as executor:
|
||||
for target, check in checks.items():
|
||||
if not target in check_targets:
|
||||
continue
|
||||
|
||||
try:
|
||||
populated_check = self._populated_check(target, check)
|
||||
target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force)
|
||||
if target_information is None:
|
||||
target_information = dict()
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", "<n/a>")))
|
||||
continue
|
||||
if not check:
|
||||
continue
|
||||
|
||||
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), target_information)
|
||||
try:
|
||||
populated_check = self._populated_check(target, check)
|
||||
future = executor.submit(self._get_current_version, target, populated_check, force=force)
|
||||
futures_to_result[future] = (target, populated_check)
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown update check type for target {}: {}".format(target,
|
||||
check.get("type",
|
||||
"<n/a>")))
|
||||
continue
|
||||
except:
|
||||
self._logger.exception("Could not check {} for updates".format(target))
|
||||
continue
|
||||
|
||||
update_available = update_available or target_update_available
|
||||
update_possible = update_possible or (target_update_possible and target_update_available)
|
||||
for future in futures.as_completed(futures_to_result):
|
||||
|
||||
local_name = target_information["local"]["name"]
|
||||
local_value = target_information["local"]["value"]
|
||||
target, populated_check = futures_to_result[future]
|
||||
if future.exception() is not None:
|
||||
self._logger.error("Could not check {} for updates, error: {!r}".format(target,
|
||||
future.exception()))
|
||||
continue
|
||||
|
||||
release_notes = None
|
||||
if target_information and target_information["remote"] and target_information["remote"]["value"]:
|
||||
if "release_notes" in populated_check and populated_check["release_notes"]:
|
||||
release_notes = populated_check["release_notes"]
|
||||
elif "release_notes" in target_information["remote"]:
|
||||
release_notes = target_information["remote"]["release_notes"]
|
||||
target_information, target_update_available, target_update_possible, target_online, target_error = future.result()
|
||||
|
||||
if release_notes:
|
||||
release_notes = release_notes.format(octoprint_version=VERSION,
|
||||
target_name=target_information["remote"]["name"],
|
||||
target_version=target_information["remote"]["value"])
|
||||
target_information = dict_merge(dict(local=dict(name="?", value="?"),
|
||||
remote=dict(name="?", value="?",
|
||||
release_notes=None),
|
||||
needs_online=True), target_information)
|
||||
|
||||
information[target] = dict(updateAvailable=target_update_available,
|
||||
updatePossible=target_update_possible,
|
||||
information=target_information,
|
||||
displayName=populated_check["displayName"],
|
||||
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION, local_name=local_name, local_value=local_value),
|
||||
check=populated_check,
|
||||
releaseNotes=release_notes)
|
||||
update_available = update_available or target_update_available
|
||||
update_possible = update_possible or (target_update_possible and target_update_available)
|
||||
|
||||
local_name = target_information["local"]["name"]
|
||||
local_value = target_information["local"]["value"]
|
||||
|
||||
release_notes = None
|
||||
if target_information and target_information["remote"] and target_information["remote"][
|
||||
"value"]:
|
||||
if "release_notes" in populated_check and populated_check["release_notes"]:
|
||||
release_notes = populated_check["release_notes"]
|
||||
elif "release_notes" in target_information["remote"]:
|
||||
release_notes = target_information["remote"]["release_notes"]
|
||||
|
||||
if release_notes:
|
||||
release_notes = release_notes.format(octoprint_version=VERSION,
|
||||
target_name=target_information["remote"]["name"],
|
||||
target_version=target_information["remote"]["value"])
|
||||
|
||||
information[target] = dict(updateAvailable=target_update_available,
|
||||
updatePossible=target_update_possible,
|
||||
information=target_information,
|
||||
displayName=populated_check["displayName"],
|
||||
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION,
|
||||
local_name=local_name,
|
||||
local_value=local_value),
|
||||
releaseNotes=release_notes,
|
||||
online=target_online,
|
||||
error=target_error)
|
||||
|
||||
if self._version_cache_dirty:
|
||||
self._save_version_cache()
|
||||
|
||||
self._get_versions_data = information, update_available, update_possible
|
||||
self._get_versions_data_ready.set()
|
||||
finally:
|
||||
self._get_versions_mutex.release()
|
||||
|
||||
else: # something's already in progress, let's wait for it to complete and use its result
|
||||
self._get_versions_data_ready.wait()
|
||||
information, update_available, update_possible = self._get_versions_data
|
||||
|
||||
if self._version_cache_dirty:
|
||||
self._save_version_cache()
|
||||
return information, update_available, update_possible
|
||||
|
||||
def _get_check_hash(self, check):
|
||||
@@ -650,36 +698,50 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash.update(dict_to_sorted_repr(check))
|
||||
return hash.hexdigest()
|
||||
|
||||
def _get_current_version(self, target, check, force=False):
|
||||
def _get_current_version(self, target, check, force=False, online=None):
|
||||
"""
|
||||
Determines the current version information for one target based on its check configuration.
|
||||
"""
|
||||
|
||||
current_hash = self._get_check_hash(check)
|
||||
if online is None:
|
||||
online = self._connectivity_checker.online
|
||||
if target in self._version_cache and not force:
|
||||
data = self._version_cache[target]
|
||||
if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]:
|
||||
if data["hash"] == current_hash \
|
||||
and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"] \
|
||||
and data.get("online", None) == online:
|
||||
# we also check that timestamp < now to not get confused too much by clock changes
|
||||
return data["information"], data["available"], data["possible"]
|
||||
return data["information"], data["available"], data["possible"], data["online"], data.get("error", None)
|
||||
|
||||
information = dict()
|
||||
update_available = False
|
||||
error = None
|
||||
|
||||
try:
|
||||
version_checker = self._get_version_checker(target, check)
|
||||
information, is_current = version_checker.get_latest(target, check)
|
||||
information, is_current = version_checker.get_latest(target, check, online=online)
|
||||
if information is not None and not is_current:
|
||||
update_available = True
|
||||
except exceptions.CannotCheckOffline:
|
||||
update_possible = False
|
||||
information["needs_online"] = True
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown check type %s for %s" % (check["type"], target))
|
||||
update_possible = False
|
||||
error = "unknown_check"
|
||||
except exceptions.NetworkError:
|
||||
self._logger.warn("Could not check %s for updates due to a network error" % target)
|
||||
update_possible = False
|
||||
error = "network"
|
||||
except:
|
||||
self._logger.exception("Could not check %s for updates" % target)
|
||||
update_possible = False
|
||||
error = "unknown"
|
||||
else:
|
||||
try:
|
||||
updater = self._get_updater(target, check)
|
||||
update_possible = updater.can_perform_update(target, check)
|
||||
update_possible = updater.can_perform_update(target, check, online=online)
|
||||
except:
|
||||
update_possible = False
|
||||
|
||||
@@ -687,9 +749,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash=current_hash,
|
||||
information=information,
|
||||
available=update_available,
|
||||
possible=update_possible)
|
||||
possible=update_possible,
|
||||
online=online,
|
||||
error=error)
|
||||
self._version_cache_dirty = True
|
||||
return information, update_available, update_possible
|
||||
return information, update_available, update_possible, online, error
|
||||
|
||||
def perform_updates(self, check_targets=None, force=False):
|
||||
"""
|
||||
@@ -801,7 +865,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._send_client_message("success", dict(results=target_results))
|
||||
|
||||
def _perform_update(self, target, check, force):
|
||||
information, update_available, update_possible = self._get_current_version(target, check)
|
||||
online = self._connectivity_checker.online
|
||||
|
||||
information, update_available, update_possible, _, _ = self._get_current_version(target, check, online=online)
|
||||
|
||||
if not update_available and not force:
|
||||
return False, None
|
||||
@@ -824,7 +890,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if updater is None:
|
||||
raise exceptions.UnknownUpdateType()
|
||||
|
||||
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log)
|
||||
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log, online=online)
|
||||
target_result = ("success", update_result)
|
||||
self._logger.info("Update of %s to %s successful!" % (target, target_version))
|
||||
|
||||
@@ -833,6 +899,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="Unknown update type"))
|
||||
return False, None
|
||||
|
||||
except exceptions.CannotUpdateOffline:
|
||||
self._logger.warn("Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" % target)
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="No internet connection"))
|
||||
|
||||
except Exception as e:
|
||||
self._logger.exception("Update of %s can not be performed" % target)
|
||||
if not "ignorable" in populated_check or not populated_check["ignorable"]:
|
||||
|
||||
@@ -9,12 +9,14 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
import click
|
||||
import sys
|
||||
import requests.exceptions
|
||||
import octoprint_client as client
|
||||
from octoprint.cli.client import create_client, client_options
|
||||
|
||||
@click.command("check")
|
||||
@click.option("--force", is_flag=True, help="Ignore the cache for the update check")
|
||||
@click.option("--only-new", is_flag=True, help="Only show entries with updates available")
|
||||
@client_options
|
||||
@click.argument("targets", nargs=-1)
|
||||
def check_command(force, targets):
|
||||
def check_command(force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets):
|
||||
"""
|
||||
Check for updates.
|
||||
|
||||
@@ -37,7 +39,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
if targets:
|
||||
params["check"] = ",".join(targets)
|
||||
|
||||
client.init_client(cli_group.settings)
|
||||
client = create_client(settings=cli_group.settings,
|
||||
apikey=apikey,
|
||||
host=host,
|
||||
port=port,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
https=https,
|
||||
prefix=prefix)
|
||||
|
||||
r = client.get("plugin/softwareupdate/check", params=params)
|
||||
try:
|
||||
r.raise_for_status()
|
||||
@@ -58,10 +68,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
status_text = "Update available"
|
||||
else:
|
||||
status_text = "Update available (manual)"
|
||||
line = "{}\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
|
||||
info["information"]["local"]["name"],
|
||||
info["information"]["remote"]["name"],
|
||||
status_text)
|
||||
|
||||
elif only_new:
|
||||
continue
|
||||
|
||||
line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
|
||||
key,
|
||||
info["information"]["local"]["name"],
|
||||
info["information"]["remote"]["name"],
|
||||
status_text)
|
||||
if key == "octoprint":
|
||||
octoprint_line = line
|
||||
else:
|
||||
@@ -83,8 +98,9 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
|
||||
@click.command("update")
|
||||
@click.option("--force", is_flag=True, help="Update even if already up to date")
|
||||
@client_options
|
||||
@click.argument("targets", nargs=-1)
|
||||
def update_command(force, targets):
|
||||
def update_command(force, apikey, host, port, httpuser, httppass, https, prefix, targets):
|
||||
"""
|
||||
Apply updates.
|
||||
|
||||
@@ -108,7 +124,13 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
if targets:
|
||||
data["check"] = targets
|
||||
|
||||
client.init_client(cli_group.settings)
|
||||
client = create_client(apikey=apikey,
|
||||
host=host,
|
||||
port=port,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
https=https,
|
||||
prefix=prefix)
|
||||
|
||||
flags = dict(
|
||||
waiting_for_restart=False,
|
||||
|
||||
@@ -18,6 +18,20 @@ class UnknownUpdateType(Exception):
|
||||
class UnknownCheckType(Exception):
|
||||
pass
|
||||
|
||||
class NetworkError(Exception):
|
||||
def __init__(self, message=None, cause=None):
|
||||
Exception.__init__(self)
|
||||
self.message = message
|
||||
self.cause = cause
|
||||
|
||||
def __str__(self):
|
||||
if self.message is not None:
|
||||
return self.message
|
||||
elif self.cause is not None:
|
||||
return "NetworkError caused by {}".format(self.cause)
|
||||
else:
|
||||
return "NetworkError"
|
||||
|
||||
class UpdateError(Exception):
|
||||
def __init__(self, message, data):
|
||||
self.message = message
|
||||
@@ -35,3 +49,8 @@ class RestartFailed(Exception):
|
||||
class ConfigurationInvalid(Exception):
|
||||
pass
|
||||
|
||||
class CannotCheckOffline(Exception):
|
||||
pass
|
||||
|
||||
class CannotUpdateOffline(Exception):
|
||||
pass
|
||||
@@ -1 +1 @@
|
||||
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
@@ -417,6 +417,42 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.iconTitleForEntry = function(data) {
|
||||
if (data.updatePossible) {
|
||||
return "";
|
||||
} else if (!data.online && data.information && data.information.needs_online) {
|
||||
return gettext("No internet connection");
|
||||
} else if (data.error) {
|
||||
return self.errorTextForEntry(data);
|
||||
} else {
|
||||
return gettext("Update not possible");
|
||||
}
|
||||
};
|
||||
|
||||
self.errorTextForEntry = function(data) {
|
||||
if (!data.error) {
|
||||
return "";
|
||||
}
|
||||
|
||||
switch (data.error) {
|
||||
case "unknown_check": {
|
||||
return gettext("Unknown update check, configuration ok?");
|
||||
}
|
||||
case "needs_online": {
|
||||
return gettext("Cannot check for update, need online connection");
|
||||
}
|
||||
case "network": {
|
||||
return gettext("Network error while checking for update");
|
||||
}
|
||||
case "unknown": {
|
||||
return gettext("Unknown error while checking for update, please check the logs");
|
||||
}
|
||||
default: {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self._markNotificationAsSeen = function(data) {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
@@ -607,6 +643,11 @@ $(function() {
|
||||
return true;
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
if (!payload || !payload.new) return;
|
||||
self.performCheck();
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
if (self.waitingForRestart) {
|
||||
self.waitingForRestart = false;
|
||||
|
||||
@@ -2,6 +2,12 @@ td.settings_plugin_softwareupdate_column_update {
|
||||
width: 16px;
|
||||
}
|
||||
|
||||
td.settings_plugin_softwareupdate_column_information {
|
||||
.line {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
#settings_plugin_softwareupdate_workingdialog_output {
|
||||
font-size: 0.8em;
|
||||
|
||||
|
||||
@@ -29,11 +29,12 @@
|
||||
<span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" title="{{ _('Update available') }}"></i></span>
|
||||
</td>
|
||||
<td class="settings_plugin_softwareupdate_column_information">
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
|
||||
<small class="muted">
|
||||
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
|
||||
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span><br>
|
||||
<span data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
|
||||
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
|
||||
<span class="line">{{ _('Available:') }} <span data-bind="text: information.remote.name"></span></span>
|
||||
<span class="line" data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
|
||||
<span class="line text-error" data-bind="visible: error, text: $root.errorTextForEntry($data)"></span>
|
||||
</small>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -18,9 +18,9 @@ console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pi
|
||||
_pip_callers = dict()
|
||||
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
def can_perform_update(target, check):
|
||||
def can_perform_update(target, check, online=True):
|
||||
pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None)
|
||||
return "pip" in check and pip_caller is not None and pip_caller.available
|
||||
return "pip" in check and pip_caller is not None and pip_caller.available and (online or check.get("offline", False))
|
||||
|
||||
def _get_pip_caller(command=None):
|
||||
key = command
|
||||
@@ -35,11 +35,14 @@ def _get_pip_caller(command=None):
|
||||
|
||||
return _pip_callers[key]
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None):
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
pip_command = None
|
||||
if "pip_command" in check:
|
||||
pip_command = check["pip_command"]
|
||||
|
||||
if not online and not check.get("offline", False):
|
||||
raise exceptions.CannotUpdateOffline()
|
||||
|
||||
pip_caller = _get_pip_caller(command=pip_command)
|
||||
if pip_caller is None:
|
||||
raise exceptions.UpdateError("Can't run pip", None)
|
||||
|
||||
@@ -6,9 +6,24 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
def can_perform_update(target, check):
|
||||
return "python_updater" in check and check["python_updater"] is not None and hasattr(check["python_updater"], "perform_update")
|
||||
def can_perform_update(target, check, online=True):
|
||||
return "python_updater" in check and check["python_updater"] is not None and hasattr(check["python_updater"], "perform_update") and (online or check.get("offline", False))
|
||||
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None):
|
||||
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb)
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
from ..exceptions import CannotUpdateOffline
|
||||
|
||||
if not online and not check("offline", False):
|
||||
raise CannotUpdateOffline()
|
||||
|
||||
try:
|
||||
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb, online=online)
|
||||
except:
|
||||
import inspect
|
||||
args, _, _, _ = inspect.getargspec(check["python_updater"].perform_update)
|
||||
if "online" not in args:
|
||||
# old python_updater footprint, simply leave out the online parameter
|
||||
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb)
|
||||
|
||||
# some other error, raise again
|
||||
raise
|
||||
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import sys
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid, UpdateError
|
||||
from ..exceptions import ConfigurationInvalid, UpdateError, CannotUpdateOffline
|
||||
|
||||
from octoprint.util.commandline import CommandlineCaller, CommandlineError
|
||||
|
||||
@@ -36,7 +36,7 @@ def _get_caller(log_cb=None):
|
||||
return caller
|
||||
|
||||
|
||||
def can_perform_update(target, check):
|
||||
def can_perform_update(target, check, online=True):
|
||||
import os
|
||||
script_configured = bool("update_script" in check and check["update_script"])
|
||||
|
||||
@@ -47,12 +47,15 @@ def can_perform_update(target, check):
|
||||
folder = check["checkout_folder"]
|
||||
folder_configured = bool(folder and os.path.isdir(folder))
|
||||
|
||||
return script_configured and folder_configured
|
||||
return script_configured and folder_configured and (online or check.get("offline", False))
|
||||
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None):
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.update_script")
|
||||
|
||||
if not online and not check("offline", False):
|
||||
raise CannotUpdateOffline()
|
||||
|
||||
if not can_perform_update(target, check):
|
||||
raise ConfigurationInvalid("checkout_folder and update_folder are missing for update target %s, one is needed" % target)
|
||||
|
||||
|
||||
@@ -6,15 +6,26 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
|
||||
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
import base64
|
||||
|
||||
BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit")
|
||||
|
||||
def _get_latest_commit(user, repo, branch):
|
||||
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch))
|
||||
|
||||
def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
|
||||
from ..exceptions import NetworkError
|
||||
|
||||
url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch)
|
||||
headers = {}
|
||||
if api_user is not None and api_password is not None:
|
||||
auth_value = base64.b64encode(b"{user}:{pw}".format(user=api_user, pw=api_password))
|
||||
headers["authorization"] = "Basic {}".format(auth_value)
|
||||
|
||||
try:
|
||||
r = requests.get(url, headers=headers, timeout=(3.05, 30))
|
||||
except requests.ConnectionError as exc:
|
||||
raise NetworkError(cause=exc)
|
||||
|
||||
if not r.status_code == requests.codes.ok:
|
||||
return None
|
||||
@@ -26,24 +37,33 @@ def _get_latest_commit(user, repo, branch):
|
||||
return reference["hash"]
|
||||
|
||||
|
||||
def get_latest(target, check):
|
||||
def get_latest(target, check, online=True):
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
if "user" not in check or "repo" not in check:
|
||||
raise ConfigurationInvalid("Update configuration for %s of type bitbucket_commit needs all of user and repo" % target)
|
||||
|
||||
branch = "master"
|
||||
if "branch" in check:
|
||||
if "branch" in check and check["branch"] is not None:
|
||||
branch = check["branch"]
|
||||
|
||||
current = None
|
||||
if "current" in check:
|
||||
current = check["current"]
|
||||
api_user = check.get("api_user")
|
||||
api_password = check.get("api_password")
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
|
||||
current = check.get("current")
|
||||
|
||||
information = dict(
|
||||
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
|
||||
remote=dict(name="Commit {commit}".format(commit=remote_commit if remote_commit is not None else "unknown"), value=remote_commit)
|
||||
remote=dict(name="?", value="?"),
|
||||
needs_online=not check.get("offline", False)
|
||||
)
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch, api_user, api_password)
|
||||
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
|
||||
|
||||
information["remote"] = dict(name=remote_name, value=remote_commit)
|
||||
is_current = (current is not None and current == remote_commit) or remote_commit is None
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
|
||||
|
||||
@@ -8,14 +8,17 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
from ..exceptions import ConfigurationInvalid, CannotCheckOffline
|
||||
from ..util import execute
|
||||
|
||||
def get_latest(target, check):
|
||||
def get_latest(target, check, online=True):
|
||||
command = check.get("command")
|
||||
if command is None:
|
||||
raise ConfigurationInvalid("Update configuration for {} of type commandline needs command set and not None".format(target))
|
||||
|
||||
if not online and not check.get("offline", False):
|
||||
raise CannotCheckOffline("{} isn't marked as 'offline' capable, but we are apparently offline right now".format(target))
|
||||
|
||||
returncode, stdout, stderr = execute(command, evaluate_returncode=False)
|
||||
|
||||
# We expect command line check commands to
|
||||
|
||||
@@ -47,38 +47,40 @@ def _git(args, cwd, hide_stderr=False):
|
||||
return p.returncode, stdout
|
||||
|
||||
|
||||
def get_latest(target, check):
|
||||
def get_latest(target, check, online=True):
|
||||
checkout_folder = check.get("checkout_folder")
|
||||
if checkout_folder is None:
|
||||
raise ConfigurationInvalid("Update configuration for {} of type git_commit needs checkout_folder set and not None".format(target))
|
||||
|
||||
returncode, _ = _git(["fetch"], checkout_folder)
|
||||
if returncode != 0:
|
||||
return None, True
|
||||
|
||||
returncode, local_commit = _git(["rev-parse", "@{0}"], checkout_folder)
|
||||
if returncode != 0:
|
||||
return None, True
|
||||
|
||||
information = dict(
|
||||
local=dict(name="Commit %s" % local_commit, value=local_commit),
|
||||
remote=dict(name="?", value="?"),
|
||||
needs_online=not check.get("offline", False)
|
||||
)
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
returncode, _ = _git(["fetch"], checkout_folder)
|
||||
if returncode != 0:
|
||||
return information, True
|
||||
|
||||
returncode, remote_commit = _git(["rev-parse", "@{u}"], checkout_folder)
|
||||
if returncode != 0:
|
||||
return None, True
|
||||
return information, True
|
||||
|
||||
returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
|
||||
if returncode != 0:
|
||||
return None, True
|
||||
return information, True
|
||||
|
||||
if local_commit == remote_commit or remote_commit == base:
|
||||
information = dict(
|
||||
local=dict(name="Commit %s" % local_commit, value=local_commit),
|
||||
remote=dict(name="Commit %s" % local_commit, value=local_commit)
|
||||
)
|
||||
information["remote"] = dict(name="Commit %s" % local_commit, value=local_commit)
|
||||
is_current = True
|
||||
else:
|
||||
information = dict(
|
||||
local=dict(name="Commit %s" % local_commit, value=local_commit),
|
||||
remote=dict(name="Commit %s" % remote_commit, value=remote_commit)
|
||||
)
|
||||
information["remote"] = dict(name="Commit %s" % remote_commit, value=remote_commit)
|
||||
is_current = local_commit == remote_commit
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.git_commit")
|
||||
|
||||
@@ -8,14 +8,17 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{branch}"
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit")
|
||||
|
||||
def _get_latest_commit(user, repo, branch):
|
||||
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=30)
|
||||
from ..exceptions import NetworkError
|
||||
|
||||
try:
|
||||
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=(3.05, 30))
|
||||
except requests.ConnectionError as exc:
|
||||
raise NetworkError(cause=exc)
|
||||
|
||||
from . import log_github_ratelimit
|
||||
log_github_ratelimit(logger, r)
|
||||
@@ -30,7 +33,9 @@ def _get_latest_commit(user, repo, branch):
|
||||
return reference["object"]["sha"]
|
||||
|
||||
|
||||
def get_latest(target, check):
|
||||
def get_latest(target, check, online=True):
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
user = check.get("user")
|
||||
repo = check.get("repo")
|
||||
|
||||
@@ -41,16 +46,18 @@ def get_latest(target, check):
|
||||
if "branch" in check and check["branch"] is not None:
|
||||
branch = check["branch"]
|
||||
|
||||
current = None
|
||||
if "current" in check:
|
||||
current = check["current"]
|
||||
current = check.get("current")
|
||||
|
||||
information = dict(local=dict(name="Commit {commit}".format(commit=current if current is not None else "?"), value=current),
|
||||
remote=dict(name="?", value="?"),
|
||||
needs_online=not check.get("offline", False))
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
|
||||
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
|
||||
|
||||
information = dict(
|
||||
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
|
||||
remote=dict(name="Commit {commit}".format(commit=remote_commit if remote_commit is not None else "unknown"), value=remote_commit)
|
||||
)
|
||||
information["remote"] = dict(name=remote_name, value=remote_commit)
|
||||
is_current = (current is not None and current == remote_commit) or remote_commit is None
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
|
||||
|
||||
@@ -8,8 +8,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from octoprint.util.version import parse_version
|
||||
|
||||
RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release")
|
||||
@@ -98,8 +96,14 @@ def _get_latest_release(user, repo, compare_type,
|
||||
include_prerelease=False,
|
||||
commitish=None,
|
||||
force_base=True):
|
||||
from ..exceptions import NetworkError
|
||||
|
||||
nothing = None, None, None
|
||||
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=30)
|
||||
|
||||
try:
|
||||
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30))
|
||||
except requests.ConnectionError as exc:
|
||||
raise NetworkError(cause=exc)
|
||||
|
||||
from . import log_github_ratelimit
|
||||
log_github_ratelimit(logger, r)
|
||||
@@ -141,8 +145,44 @@ def _get_sanitized_version(version_string):
|
||||
return version_string
|
||||
|
||||
|
||||
def _get_base_from_version_tuple(version_tuple):
|
||||
"""
|
||||
Reduces version tuple to base version.
|
||||
|
||||
Tests:
|
||||
|
||||
>>> _get_base_from_version_tuple(("1", "2", "15"))
|
||||
('1', '2', '15')
|
||||
>>> _get_base_from_version_tuple(("1", "2", "15", "*", "dev12"))
|
||||
('1', '2', '15')
|
||||
"""
|
||||
|
||||
base_version = []
|
||||
for part in version_tuple:
|
||||
if part.startswith("*"):
|
||||
break
|
||||
base_version.append(part)
|
||||
return tuple(base_version)
|
||||
|
||||
|
||||
def _get_comparable_version_pkg_resources(version_string, force_base=True):
|
||||
return parse_version(version_string, base=force_base)
|
||||
import pkg_resources
|
||||
|
||||
version = pkg_resources.parse_version(version_string)
|
||||
|
||||
# A leading v is common in github release tags and old setuptools doesn't remove it.
|
||||
if version and isinstance(version, tuple) and version[0].lower() == "*v":
|
||||
version = version[1:]
|
||||
|
||||
if force_base:
|
||||
if isinstance(version, tuple):
|
||||
# old setuptools
|
||||
version = _get_base_from_version_tuple(version)
|
||||
else:
|
||||
# new setuptools
|
||||
version = pkg_resources.parse_version(version.base_version)
|
||||
|
||||
return version
|
||||
|
||||
|
||||
def _get_comparable_version_semantic(version_string, force_base=True):
|
||||
@@ -224,7 +264,7 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
|
||||
return True
|
||||
|
||||
|
||||
def get_latest(target, check, custom_compare=None):
|
||||
def get_latest(target, check, custom_compare=None, online=True):
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
user = check.get("user", None)
|
||||
@@ -233,6 +273,14 @@ def get_latest(target, check, custom_compare=None):
|
||||
if user is None or repo is None or current is None:
|
||||
raise ConfigurationInvalid("Update configuration for {} of type github_release needs all of user, repo and current set and not None".format(target))
|
||||
|
||||
information =dict(
|
||||
local=dict(name=current, value=current),
|
||||
remote=dict(name="?", value="?", release_notes=None),
|
||||
needs_online=not check.get("offline", False)
|
||||
)
|
||||
if not online and information["needs_online"]:
|
||||
return information, True
|
||||
|
||||
include_prerelease = check.get("prerelease", False)
|
||||
prerelease_channel = check.get("prerelease_channel", None)
|
||||
|
||||
@@ -256,10 +304,13 @@ def get_latest(target, check, custom_compare=None):
|
||||
commitish=commitish,
|
||||
force_base=force_base)
|
||||
|
||||
information =dict(
|
||||
local=dict(name=current, value=current),
|
||||
remote=dict(name=remote_name, value=remote_tag, release_notes=release_notes)
|
||||
)
|
||||
if remote_name is None:
|
||||
if remote_tag is not None:
|
||||
remote_name = remote_tag
|
||||
else:
|
||||
remote_name = "-"
|
||||
|
||||
information["remote"] = dict(name=remote_name, value=remote_tag, release_notes=release_notes)
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
|
||||
|
||||
|
||||
@@ -5,11 +5,24 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
from ..exceptions import ConfigurationInvalid, CannotCheckOffline
|
||||
|
||||
def get_latest(target, check, full_data=False):
|
||||
def get_latest(target, check, full_data=False, online=True):
|
||||
python_checker = check.get("python_checker")
|
||||
if python_checker is None or not hasattr(python_checker, "get_latest"):
|
||||
raise ConfigurationInvalid("Update configuration for {} of type python_checker needs python_checker defined and have an attribute \"get_latest\"".format(target))
|
||||
|
||||
return check["python_checker"].get_latest(target, check, full_data=full_data)
|
||||
if not online and not check.get("offline", False):
|
||||
raise CannotCheckOffline("{} isn't marked as 'offline' capable, but we are apparently offline right now".format(target))
|
||||
|
||||
try:
|
||||
return check["python_checker"].get_latest(target, check, full_data=full_data, online=online)
|
||||
except:
|
||||
import inspect
|
||||
args, _, _, _ = inspect.getargspec(check["python_checker"].get_latest)
|
||||
if "online" not in args:
|
||||
# old python_checker footprint, simply leave out the online parameter
|
||||
return check["python_checker"].get_latest(target, check, full_data=full_data)
|
||||
|
||||
# some other error, raise again
|
||||
raise
|
||||
@@ -65,6 +65,9 @@ class VirtualPrinter(object):
|
||||
|
||||
self.currentExtruder = 0
|
||||
self.extruderCount = settings().getInt(["devel", "virtualPrinter", "numExtruders"])
|
||||
self.pinnedExtruders = settings().get(["devel", "virtualPrinter", "pinnedExtruders"])
|
||||
if self.pinnedExtruders is None:
|
||||
self.pinnedExtruders = dict()
|
||||
self.sharedNozzle = settings().getBoolean(["devel", "virtualPrinter", "sharedNozzle"])
|
||||
self.temperatureCount = (1 if self.sharedNozzle else self.extruderCount)
|
||||
|
||||
@@ -1001,6 +1004,10 @@ class VirtualPrinter(object):
|
||||
timeDiff = self.lastTempAt - time.time()
|
||||
self.lastTempAt = time.time()
|
||||
for i in range(len(self.temp)):
|
||||
if i in self.pinnedExtruders:
|
||||
self.temp[i] = self.pinnedExtruders[i]
|
||||
continue
|
||||
|
||||
if abs(self.temp[i] - self.targetTemp[i]) > delta:
|
||||
oldVal = self.temp[i]
|
||||
self.temp[i] += math.copysign(timeDiff * 10, self.targetTemp[i] - self.temp[i])
|
||||
|
||||
@@ -763,7 +763,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
(2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation
|
||||
"""
|
||||
|
||||
if progress is None or printTime is None or cleanedPrintTime is None:
|
||||
if progress is None or progress == 0 or printTime is None or cleanedPrintTime is None:
|
||||
return None, None
|
||||
|
||||
dumbTotalPrintTime = printTime / progress
|
||||
@@ -1000,7 +1000,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
with self._selectedFileMutex:
|
||||
if self._selectedFile is not None:
|
||||
if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_ERROR or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
def log_print():
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL,
|
||||
self._selectedFile["filename"],
|
||||
time.time(),
|
||||
self._comm.getPrintTime(),
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
|
||||
thread = threading.Thread(target=log_print)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
|
||||
elif state == comm.MachineCom.STATE_PRINTING:
|
||||
self._analysisQueue.pause() # do not analyse files while printing
|
||||
@@ -1091,12 +1101,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
context=dict(event=payload),
|
||||
must_be_set=False)
|
||||
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
True,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
def log_print():
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
True,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
|
||||
thread = threading.Thread(target=log_print)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
else:
|
||||
self._updateProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
@@ -1119,13 +1135,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
context=dict(event=payload),
|
||||
must_be_set=False)
|
||||
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
def finalize():
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
thread = threading.Thread(target=finalize)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def on_comm_print_job_paused(self):
|
||||
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None)
|
||||
|
||||
@@ -7,9 +7,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import uuid
|
||||
from sockjs.tornado import SockJSRouter
|
||||
from flask import Flask, g, request, session, Blueprint, Request, Response
|
||||
from flask.ext.login import LoginManager, current_user
|
||||
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
|
||||
from flask import Flask, g, request, session, Blueprint, Request, Response, current_app
|
||||
from flask.ext.login import LoginManager, current_user, session_protected, user_logged_out
|
||||
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, AnonymousIdentity
|
||||
from flask.ext.babel import Babel, gettext, ngettext
|
||||
from flask.ext.assets import Environment, Bundle
|
||||
from babel import Locale
|
||||
@@ -27,6 +27,11 @@ import atexit
|
||||
import signal
|
||||
import base64
|
||||
|
||||
try:
|
||||
import fcntl
|
||||
except ImportError:
|
||||
fcntl = None
|
||||
|
||||
SUCCESS = {}
|
||||
NO_CONTENT = ("", 204)
|
||||
NOT_MODIFIED = ("Not Modified", 304)
|
||||
@@ -49,6 +54,7 @@ pluginManager = None
|
||||
appSessionManager = None
|
||||
pluginLifecycleManager = None
|
||||
preemptiveCache = None
|
||||
connectivityChecker = None
|
||||
|
||||
principals = Principal(app)
|
||||
admin_permission = Permission(RoleNeed("admin"))
|
||||
@@ -96,6 +102,29 @@ def on_identity_loaded(sender, identity):
|
||||
if user.is_admin():
|
||||
identity.provides.add(RoleNeed("admin"))
|
||||
|
||||
|
||||
def _clear_identity(sender):
|
||||
# Remove session keys set by Flask-Principal
|
||||
for key in ('identity.id', 'identity.name', 'identity.auth_type'):
|
||||
if key in session:
|
||||
del session[key]
|
||||
|
||||
# switch to anonymous identity
|
||||
identity_changed.send(sender, identity=AnonymousIdentity())
|
||||
|
||||
|
||||
@session_protected.connect_via(app)
|
||||
def on_session_protected(sender):
|
||||
# session was protected, that means the user is no more and we need to clear our identity
|
||||
_clear_identity(sender)
|
||||
|
||||
|
||||
@user_logged_out.connect_via(app)
|
||||
def on_user_logged_out(sender, user=None):
|
||||
# user was logged out, clear identity
|
||||
_clear_identity(sender)
|
||||
|
||||
|
||||
def load_user(id):
|
||||
if id == "_api":
|
||||
return users.ApiUser()
|
||||
@@ -160,6 +189,7 @@ class Server(object):
|
||||
global appSessionManager
|
||||
global pluginLifecycleManager
|
||||
global preemptiveCache
|
||||
global connectivityChecker
|
||||
global debug
|
||||
global safe_mode
|
||||
|
||||
@@ -189,6 +219,17 @@ class Server(object):
|
||||
# start the intermediary server
|
||||
self._start_intermediary_server()
|
||||
|
||||
### IMPORTANT!
|
||||
###
|
||||
### Do not start any subprocesses until the intermediary server shuts down again or they WILL inherit the
|
||||
### open port and prevent us from firing up Tornado later. Thanks to close_fds not being available on Popen
|
||||
### on Windows if you also want to be able to redirect stdout/stderr/stdin and fnctl also not being available
|
||||
### we don't have a good way around this issue besides being careful not to spawn processes here.
|
||||
###
|
||||
### Which kinda sucks tbh.
|
||||
###
|
||||
### See also issue #2035
|
||||
|
||||
# then initialize the plugin manager
|
||||
pluginManager.reload_plugins(startup=True, initialize_implementations=False)
|
||||
|
||||
@@ -205,6 +246,40 @@ class Server(object):
|
||||
pluginLifecycleManager = LifecycleManager(pluginManager)
|
||||
preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml"))
|
||||
|
||||
# start regular check if we are connected to the internet
|
||||
connectivityEnabled = self._settings.getBoolean(["server", "onlineCheck", "enabled"])
|
||||
connectivityInterval = self._settings.getInt(["server", "onlineCheck", "interval"])
|
||||
connectivityHost = self._settings.get(["server", "onlineCheck", "host"])
|
||||
connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"])
|
||||
|
||||
def on_connectivity_change(old_value, new_value):
|
||||
eventManager.fire(events.Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value))
|
||||
|
||||
connectivityChecker = octoprint.util.ConnectivityChecker(connectivityInterval,
|
||||
connectivityHost,
|
||||
port=connectivityPort,
|
||||
enabled=connectivityEnabled,
|
||||
on_change=on_connectivity_change)
|
||||
|
||||
def on_settings_update(*args, **kwargs):
|
||||
# make sure our connectivity checker runs with the latest settings
|
||||
connectivityEnabled = self._settings.getBoolean(["server", "onlineCheck", "enabled"])
|
||||
connectivityInterval = self._settings.getInt(["server", "onlineCheck", "interval"])
|
||||
connectivityHost = self._settings.get(["server", "onlineCheck", "host"])
|
||||
connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"])
|
||||
|
||||
if connectivityChecker.enabled != connectivityEnabled \
|
||||
or connectivityChecker.interval != connectivityInterval \
|
||||
or connectivityChecker.host != connectivityHost \
|
||||
or connectivityChecker.port != connectivityPort:
|
||||
connectivityChecker.enabled = connectivityEnabled
|
||||
connectivityChecker.interval = connectivityInterval
|
||||
connectivityChecker.host = connectivityHost
|
||||
connectivityChecker.port = connectivityPort
|
||||
connectivityChecker.check_immediately()
|
||||
|
||||
eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update)
|
||||
|
||||
# setup access control
|
||||
userManagerName = self._settings.get(["accessControl", "userManager"])
|
||||
try:
|
||||
@@ -225,10 +300,33 @@ class Server(object):
|
||||
file_manager=fileManager,
|
||||
app_session_manager=appSessionManager,
|
||||
plugin_lifecycle_manager=pluginLifecycleManager,
|
||||
user_manager=userManager,
|
||||
preemptive_cache=preemptiveCache
|
||||
preemptive_cache=preemptiveCache,
|
||||
connectivity_checker=connectivityChecker
|
||||
)
|
||||
|
||||
# create user manager instance
|
||||
user_manager_factories = pluginManager.get_hooks("octoprint.users.factory")
|
||||
for name, factory in user_manager_factories.items():
|
||||
try:
|
||||
userManager = factory(components, self._settings)
|
||||
if userManager is not None:
|
||||
self._logger.debug("Created user manager instance from factory {}".format(name))
|
||||
break
|
||||
except:
|
||||
self._logger.exception("Error while creating user manager instance from factory {}".format(name))
|
||||
else:
|
||||
name = self._settings.get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = octoprint.util.get_class(name)
|
||||
userManager = clazz()
|
||||
except:
|
||||
self._logger.exception(
|
||||
"Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name))
|
||||
userManager = octoprint.users.FilebasedUserManager()
|
||||
finally:
|
||||
userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"])
|
||||
components.update(dict(user_manager=userManager))
|
||||
|
||||
# create printer instance
|
||||
printer_factories = pluginManager.get_hooks("octoprint.printer.factory")
|
||||
for name, factory in printer_factories.items():
|
||||
@@ -487,8 +585,13 @@ class Server(object):
|
||||
self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=self._settings.getInt(["server", "maxSize"]))
|
||||
self._server.listen(self._port, address=self._host)
|
||||
|
||||
### From now on it's ok to launch subprocesses again
|
||||
|
||||
eventManager.fire(events.Events.STARTUP)
|
||||
|
||||
# analysis backlog
|
||||
fileManager.process_backlog()
|
||||
|
||||
# auto connect
|
||||
if self._settings.getBoolean(["serial", "autoconnect"]):
|
||||
try:
|
||||
@@ -1274,21 +1377,37 @@ class Server(object):
|
||||
|
||||
rules = map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))
|
||||
|
||||
self._intermediary_server = BaseHTTPServer.HTTPServer((host, port), lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs))
|
||||
self._intermediary_server = BaseHTTPServer.HTTPServer((host, port),
|
||||
lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs),
|
||||
bind_and_activate=False)
|
||||
|
||||
# if possible, make sure our socket's port descriptor isn't handed over to subprocesses
|
||||
if fcntl is not None and hasattr(fcntl, "FD_CLOEXEC"):
|
||||
flags = fcntl.fcntl(self._intermediary_server.socket, fcntl.F_GETFD)
|
||||
flags |= fcntl.FD_CLOEXEC
|
||||
fcntl.fcntl(self._intermediary_server.socket, fcntl.F_SETFD, flags)
|
||||
|
||||
# then bind the server and have it serve our handler until stopped
|
||||
try:
|
||||
self._intermediary_server.server_bind()
|
||||
self._intermediary_server.server_activate()
|
||||
except:
|
||||
self._intermediary_server.server_close()
|
||||
raise
|
||||
|
||||
thread = threading.Thread(target=self._intermediary_server.serve_forever)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
self._logger.debug("Intermediary server started")
|
||||
self._logger.info("Intermediary server started")
|
||||
|
||||
def _stop_intermediary_server(self):
|
||||
if self._intermediary_server is None:
|
||||
return
|
||||
self._logger.debug("Shutting down intermediary server...")
|
||||
self._logger.info("Shutting down intermediary server...")
|
||||
self._intermediary_server.shutdown()
|
||||
self._intermediary_server.server_close()
|
||||
self._logger.debug("Intermediary server shut down")
|
||||
self._logger.info("Intermediary server shut down")
|
||||
|
||||
class LifecycleManager(object):
|
||||
def __init__(self, plugin_manager):
|
||||
|
||||
@@ -222,22 +222,21 @@ def login():
|
||||
@api.route("/logout", methods=["POST"])
|
||||
@restricted_access
|
||||
def logout():
|
||||
# Remove session keys set by Flask-Principal
|
||||
for key in ('identity.id', 'identity.name', 'identity.auth_type'):
|
||||
if key in session:
|
||||
del session[key]
|
||||
identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
|
||||
|
||||
# logout from user manager...
|
||||
_logout(current_user)
|
||||
|
||||
# ... and from flask login (and principal)
|
||||
logout_user()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
def _logout(user):
|
||||
if "usersession.id" in session:
|
||||
del session["usersession.id"]
|
||||
octoprint.server.userManager.logout_user(user)
|
||||
|
||||
|
||||
@api.route("/util/test", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
|
||||
@@ -464,6 +464,7 @@ def gcodeFileCommand(filename, target):
|
||||
valid_commands = {
|
||||
"select": [],
|
||||
"slice": [],
|
||||
"analyse": [],
|
||||
"copy": ["destination"],
|
||||
"move": ["destination"]
|
||||
}
|
||||
@@ -616,6 +617,17 @@ def gcodeFileCommand(filename, target):
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
|
||||
elif command == "analyse":
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
printer_profile = None
|
||||
if "printerProfile" in data and data["printerProfile"]:
|
||||
printer_profile = data["printerProfile"]
|
||||
|
||||
if not fileManager.analyse(target, filename, printer_profile_id=printer_profile):
|
||||
return make_response("No analysis possible for {} on {}".format(filename, target), 400)
|
||||
|
||||
elif command == "copy" or command == "move":
|
||||
# Copy and move are only possible on local storage
|
||||
if not target in [FileDestinations.LOCAL]:
|
||||
|
||||
@@ -154,6 +154,8 @@ def getSettings():
|
||||
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
|
||||
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
|
||||
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
|
||||
"logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]),
|
||||
"logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]),
|
||||
"supportResendsWithoutOk": s.getBoolean(["serial", "supportResendsWithoutOk"]),
|
||||
"maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]),
|
||||
"maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]),
|
||||
@@ -200,6 +202,12 @@ def getSettings():
|
||||
"diskspace": {
|
||||
"warning": s.getInt(["server", "diskspace", "warning"]),
|
||||
"critical": s.getInt(["server", "diskspace", "critical"])
|
||||
},
|
||||
"onlineCheck": {
|
||||
"enabled": s.getBoolean(["server", "onlineCheck", "enabled"]),
|
||||
"interval": int(s.getInt(["server", "onlineCheck", "interval"]) / 60),
|
||||
"host": s.get(["server", "onlineCheck", "host"]),
|
||||
"port": s.getInt(["server", "onlineCheck", "port"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -365,6 +373,8 @@ def _saveSettings(data):
|
||||
if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"])
|
||||
if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"])
|
||||
if "supportResendsWithoutOk" in data["serial"]: s.setBoolean(["serial", "supportResendsWithoutOk"], data["serial"]["supportResendsWithoutOk"])
|
||||
if "logPositionOnPause" in data["serial"]: s.setBoolean(["serial", "logPositionOnPause"], data["serial"]["logPositionOnPause"])
|
||||
if "logPositionOnCancel" in data["serial"]: s.setBoolean(["serial", "logPositionOnCancel"], data["serial"]["logPositionOnCancel"])
|
||||
if "maxTimeoutsIdle" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "idle"], data["serial"]["maxTimeoutsIdle"])
|
||||
if "maxTimeoutsPrinting" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "printing"], data["serial"]["maxTimeoutsPrinting"])
|
||||
if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"])
|
||||
@@ -415,6 +425,16 @@ def _saveSettings(data):
|
||||
if "diskspace" in data["server"]:
|
||||
if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"])
|
||||
if "critical" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"])
|
||||
if "onlineCheck" in data["server"]:
|
||||
if "enabled" in data["server"]["onlineCheck"]: s.setBoolean(["server", "onlineCheck", "enabled"], data["server"]["onlineCheck"]["enabled"])
|
||||
if "interval" in data["server"]["onlineCheck"]:
|
||||
try:
|
||||
interval = int(data["server"]["onlineCheck"]["interval"])
|
||||
s.setInt(["server", "onlineCheck", "interval"], interval*60)
|
||||
except ValueError:
|
||||
pass
|
||||
if "host" in data["server"]["onlineCheck"]: s.set(["server", "onlineCheck", "host"], data["server"]["onlineCheck"]["host"])
|
||||
if "port" in data["server"]["onlineCheck"]: s.setInt(["server", "onlineCheck", "port"], data["server"]["onlineCheck"]["port"])
|
||||
|
||||
if "plugins" in data:
|
||||
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
|
||||
|
||||
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
import collections
|
||||
import logging
|
||||
import sarge
|
||||
import threading
|
||||
|
||||
from flask import request, make_response, jsonify, url_for
|
||||
from flask.ext.babel import gettext
|
||||
@@ -16,6 +17,7 @@ from octoprint.settings import settings as s
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access, get_remote_address
|
||||
from octoprint.logging import prefix_multilines
|
||||
|
||||
|
||||
@api.route("/system", methods=["POST"])
|
||||
@@ -74,38 +76,59 @@ def executeSystemCommand(source, command):
|
||||
|
||||
do_async = command_spec.get("async", False)
|
||||
do_ignore = command_spec.get("ignore", False)
|
||||
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
|
||||
debug = command_spec.get("debug", False)
|
||||
|
||||
if logger.isEnabledFor(logging.DEBUG) or debug:
|
||||
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
|
||||
else:
|
||||
logger.info("Performing command for {}:{}".format(source, command))
|
||||
|
||||
try:
|
||||
if "before" in command_spec and callable(command_spec["before"]):
|
||||
command_spec["before"]()
|
||||
except Exception as e:
|
||||
if not do_ignore:
|
||||
error = "Command \"before\" failed: {}".format(str(e))
|
||||
error = "Command \"before\" for {}:{} failed: {}".format(source, command, str(e))
|
||||
logger.warn(error)
|
||||
return make_response(error, 500)
|
||||
|
||||
try:
|
||||
# we run this with shell=True since we have to trust whatever
|
||||
# our admin configured as command and since we want to allow
|
||||
# shell-alike handling here...
|
||||
p = sarge.run(command_spec["command"],
|
||||
stdout=sarge.Capture(),
|
||||
stderr=sarge.Capture(),
|
||||
shell=True,
|
||||
async=do_async)
|
||||
if not do_async:
|
||||
def execute():
|
||||
# we run this with shell=True since we have to trust whatever
|
||||
# our admin configured as command and since we want to allow
|
||||
# shell-alike handling here...
|
||||
p = sarge.run(command_spec["command"],
|
||||
stdout=sarge.Capture(),
|
||||
stderr=sarge.Capture(),
|
||||
shell=True)
|
||||
|
||||
if not do_ignore and p.returncode != 0:
|
||||
returncode = p.returncode
|
||||
stdout_text = p.stdout.text
|
||||
stderr_text = p.stderr.text
|
||||
|
||||
error = "Command failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(returncode, stdout_text, stderr_text)
|
||||
logger.warn(error)
|
||||
return make_response(error, 500)
|
||||
error = "Command for {}:{} failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(source, command,
|
||||
returncode,
|
||||
stdout_text,
|
||||
stderr_text)
|
||||
logger.warn(prefix_multilines(error, prefix="! "))
|
||||
if not do_async:
|
||||
raise CommandFailed(error)
|
||||
|
||||
if do_async:
|
||||
thread = threading.Thread(target=execute)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
else:
|
||||
try:
|
||||
execute()
|
||||
except CommandFailed as exc:
|
||||
return make_response(exc.error, 500)
|
||||
|
||||
except Exception as e:
|
||||
if not do_ignore:
|
||||
error = "Command failed: {}".format(str(e))
|
||||
error = "Command for {}:{} failed: {}".format(source, command, str(e))
|
||||
logger.warn(error)
|
||||
return make_response(error, 500)
|
||||
|
||||
@@ -164,7 +187,10 @@ def _get_core_command_specs():
|
||||
for action, spec in commands.items():
|
||||
if not spec["command"]:
|
||||
continue
|
||||
spec.update(dict(action=action, source="core", async=True, ignore=True))
|
||||
spec.update(dict(action=action,
|
||||
source="core",
|
||||
async=True,
|
||||
debug=True))
|
||||
available_commands[action] = spec
|
||||
return available_commands
|
||||
|
||||
@@ -202,3 +228,7 @@ def _get_custom_command_spec(action):
|
||||
|
||||
return available_actions[action]
|
||||
|
||||
|
||||
class CommandFailed(Exception):
|
||||
def __init__(self, error):
|
||||
self.error = error
|
||||
@@ -21,6 +21,7 @@ from octoprint.server import app, userManager, pluginManager, gettext, \
|
||||
NOT_MODIFIED
|
||||
from octoprint.settings import settings
|
||||
from octoprint.filemanager import get_all_extensions
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
import re
|
||||
import base64
|
||||
@@ -466,7 +467,7 @@ def _process_templates():
|
||||
tab=dict(add="append", key="name"),
|
||||
settings=dict(add="custom_append", key="name", custom_add_entries=lambda missing: dict(section_plugins=(gettext("Plugins"), None)), custom_add_order=lambda missing: ["section_plugins"] + missing),
|
||||
usersettings=dict(add="append", key="name"),
|
||||
wizard=dict(add="append", key="name", key_extractor=lambda d, k: "0:{}".format(d[0]) if "mandatory" in d[1] and d[1]["mandatory"] else "1:{}".format(d[0])),
|
||||
wizard=dict(add="append", key="name", key_extractor=lambda d, k: u"0:{}".format(to_unicode(d[0])) if "mandatory" in d[1] and d[1]["mandatory"] else u"1:{}".format(to_unicode(d[0]))),
|
||||
about=dict(add="append", key="name"),
|
||||
generic=dict(add="append", key=None)
|
||||
)
|
||||
|
||||
@@ -112,6 +112,8 @@ default_settings = {
|
||||
"ignoreErrorsFromFirmware": False,
|
||||
"logResends": True,
|
||||
"supportResendsWithoutOk": False,
|
||||
"logPositionOnPause": True,
|
||||
"logPositionOnCancel": True,
|
||||
|
||||
# command specific flags
|
||||
"triggerOkForM29": True
|
||||
@@ -146,6 +148,12 @@ default_settings = {
|
||||
"systemRestartCommand": None,
|
||||
"serverRestartCommand": None
|
||||
},
|
||||
"onlineCheck": {
|
||||
"enabled": None,
|
||||
"interval": 15 * 60, # 15 min
|
||||
"host": "8.8.8.8",
|
||||
"port": 53
|
||||
},
|
||||
"diskspace": {
|
||||
"warning": 500 * 1024 * 1024, # 500 MB
|
||||
"critical": 200 * 1024 * 1024, # 200 MB
|
||||
@@ -342,6 +350,7 @@ default_settings = {
|
||||
"okAfterResend": False,
|
||||
"forceChecksum": False,
|
||||
"numExtruders": 1,
|
||||
"pinnedExtruders": None,
|
||||
"includeCurrentToolInTemps": True,
|
||||
"includeFilenameInOpened": True,
|
||||
"hasBed": True,
|
||||
|
||||
@@ -1 +1 @@
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
|
||||
@@ -325,6 +325,11 @@ var doParse = function () {
|
||||
extrude = false;
|
||||
line = line.split(/[\(;]/)[0];
|
||||
|
||||
if (!line || line.trim() === "") {
|
||||
// empty line, skip entirely
|
||||
continue;
|
||||
}
|
||||
|
||||
var addToModel = false;
|
||||
var move = false;
|
||||
|
||||
@@ -545,7 +550,7 @@ var doParse = function () {
|
||||
}
|
||||
|
||||
if (typeof(z) !== 'undefined' && z !== prevZ) {
|
||||
if (z_heights[z]) {
|
||||
if (z_heights[z] !== undefined) {
|
||||
layer = z_heights[z];
|
||||
} else {
|
||||
layer = model.length;
|
||||
|
||||
@@ -44,15 +44,12 @@ GCODE.gCodeReader = (function(){
|
||||
var prepareGCode = function(totalSize){
|
||||
if(!lines)return;
|
||||
gcode = [];
|
||||
var i, tmp, byteCount;
|
||||
var i, byteCount;
|
||||
|
||||
byteCount = 0;
|
||||
for(i=0;i<lines.length;i++){
|
||||
byteCount += lines[i].length + 1; // line length + \n
|
||||
tmp = lines[i].indexOf(";");
|
||||
if(tmp > 1 || tmp === -1) {
|
||||
gcode.push({line: lines[i], percentage: byteCount * 100 / totalSize});
|
||||
}
|
||||
byteCount += lines[i].length + 1; // line length + line ending
|
||||
gcode.push({line: lines[i], percentage: byteCount * 100 / totalSize});
|
||||
}
|
||||
lines = [];
|
||||
};
|
||||
@@ -146,7 +143,7 @@ GCODE.gCodeReader = (function(){
|
||||
this.clear();
|
||||
|
||||
var totalSize = reader.target.result.length;
|
||||
lines = reader.target.result.split(/\n/);
|
||||
lines = reader.target.result.split(/[\r\n]/g);
|
||||
reader.target.result = null;
|
||||
prepareGCode(totalSize);
|
||||
|
||||
|
||||
@@ -89,6 +89,10 @@
|
||||
return this.issueEntryCommand(location, path, "select", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.analyse = function (location, path, parameters, opts) {
|
||||
return this.issueEntryCommand(location, path, "analyse", parameters || {}, opts);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.slice = function (location, path, parameters, opts) {
|
||||
return this.issueEntryCommand(location, path, "slice",
|
||||
parameters || {}, opts);
|
||||
|
||||
@@ -1000,10 +1000,13 @@ function setOnViewModelsIf(allViewModels, key, value, condition) {
|
||||
}
|
||||
|
||||
function callViewModels(allViewModels, method, callback) {
|
||||
if (!allViewModels) return;
|
||||
callViewModelsIf(allViewModels, method, undefined, callback);
|
||||
}
|
||||
|
||||
function callViewModelsIf(allViewModels, method, condition, callback) {
|
||||
if (!allViewModels) return;
|
||||
|
||||
if (condition == undefined || !_.isFunction(condition)) {
|
||||
condition = function() { return true; };
|
||||
}
|
||||
|
||||
@@ -581,7 +581,7 @@ $(function() {
|
||||
|
||||
var additionalInfo = $(".additionalInfo", entryElement);
|
||||
additionalInfo.slideToggle("fast", function() {
|
||||
$(".toggleAdditionalData i", entryElement).toggleClass("icon-chevron-down icon-chevron-up");
|
||||
$(".toggleAdditionalData i", entryElement).toggleClass("fa-chevron-down fa-chevron-up");
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -109,8 +109,7 @@ $(function() {
|
||||
self.reader_sortLayers.subscribe(self.synchronizeOptions);
|
||||
self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions);
|
||||
|
||||
// subscribe to relevant printer settings...
|
||||
self.settings.printerProfiles.currentProfileData.subscribe(function() {
|
||||
self._printerProfileUpdated = function() {
|
||||
if (!self.enabled) return;
|
||||
|
||||
var currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
@@ -146,6 +145,27 @@ $(function() {
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// subscribe to relevant printer settings...
|
||||
self.settings.printerProfiles.currentProfileData.subscribe(function() {
|
||||
self._printerProfileUpdated();
|
||||
if (self.settings.printerProfiles.currentProfileData()) {
|
||||
if (self.settings.printerProfiles.currentProfileData().extruder) {
|
||||
self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles.currentProfileData().extruder.sharedNozzle.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles.currentProfileData().extruder.offsets.subscribe(self._printerProfileUpdated);
|
||||
}
|
||||
if (self.settings.printerProfiles.currentProfileData().volume) {
|
||||
self.settings.printerProfiles.currentProfileData().volume.width.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles.currentProfileData().volume.depth.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles.currentProfileData().volume.formFactor.subscribe(self._printerProfileUpdated);
|
||||
}
|
||||
if (self.settings.printerProfiles.currentProfileData().axes) {
|
||||
self.settings.printerProfiles.currentProfileData().axes.x.inverted.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles.currentProfileData().axes.y.inverted.subscribe(self._printerProfileUpdated);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
self.settings.feature_g90InfluencesExtruder.subscribe(function() {
|
||||
@@ -194,11 +214,13 @@ $(function() {
|
||||
currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
}
|
||||
|
||||
if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets() && !currentProfileData.extruder.sharedNozzle()) {
|
||||
if (currentProfileData && currentProfileData.extruder) {
|
||||
var offsets = [];
|
||||
_.each(currentProfileData.extruder.offsets(), function(offset) {
|
||||
offsets.push({x: offset[0], y: offset[1]})
|
||||
});
|
||||
if (currentProfileData.extruder.offsets() && !currentProfileData.extruder.sharedNozzle()) {
|
||||
_.each(currentProfileData.extruder.offsets(), function(offset) {
|
||||
offsets.push({x: offset[0], y: offset[1]})
|
||||
});
|
||||
}
|
||||
return offsets;
|
||||
} else {
|
||||
return undefined;
|
||||
|
||||
@@ -225,14 +225,16 @@ $(function() {
|
||||
|
||||
var result = [];
|
||||
if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) {
|
||||
for (var key in data.filament) {
|
||||
if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) continue;
|
||||
var keys = _.keys(data.filament);
|
||||
keys.sort();
|
||||
_.each(keys, function(key) {
|
||||
if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) return;
|
||||
|
||||
result.push({
|
||||
name: ko.observable(gettext("Tool") + " " + key.substr("tool".length)),
|
||||
data: ko.observable(data.filament[key])
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
self.filament(result);
|
||||
};
|
||||
|
||||
@@ -173,6 +173,8 @@ $(function() {
|
||||
self.serial_disconnectOnErrors = ko.observable(undefined);
|
||||
self.serial_triggerOkForM29 = ko.observable(undefined);
|
||||
self.serial_supportResendsWithoutOk = ko.observable(undefined);
|
||||
self.serial_logPositionOnPause = ko.observable(undefined);
|
||||
self.serial_logPositionOnCancel = ko.observable(undefined);
|
||||
self.serial_maxTimeoutsIdle = ko.observable(undefined);
|
||||
self.serial_maxTimeoutsPrinting = ko.observable(undefined);
|
||||
self.serial_maxTimeoutsLong = ko.observable(undefined);
|
||||
@@ -211,6 +213,11 @@ $(function() {
|
||||
self.server_diskspace_warning_str = sizeObservable(self.server_diskspace_warning);
|
||||
self.server_diskspace_critical_str = sizeObservable(self.server_diskspace_critical);
|
||||
|
||||
self.server_onlineCheck_enabled = ko.observable();
|
||||
self.server_onlineCheck_interval = ko.observable();
|
||||
self.server_onlineCheck_host = ko.observable();
|
||||
self.server_onlineCheck_port = ko.observable();
|
||||
|
||||
self.settings = undefined;
|
||||
self.lastReceivedSettings = undefined;
|
||||
|
||||
|
||||
@@ -47,7 +47,18 @@ $(function() {
|
||||
var callback = function() {
|
||||
OctoPrint.system.executeCommand(commandSpec.actionSource, commandSpec.action)
|
||||
.done(function() {
|
||||
new PNotify({title: "Success", text: _.sprintf(gettext("The command \"%(command)s\" executed successfully"), {command: commandSpec.name}), type: "success"});
|
||||
var text;
|
||||
if (commandSpec.async) {
|
||||
text = gettext("The command \"%(command)s\" executed successfully");
|
||||
} else {
|
||||
text = gettext("The command \"%(command)s\" was triggered asychronously");
|
||||
}
|
||||
|
||||
new PNotify({
|
||||
title: "Success",
|
||||
text: _.sprintf(text, {command: commandSpec.name}),
|
||||
type: "success"
|
||||
});
|
||||
deferred.resolve(["success", arguments]);
|
||||
})
|
||||
.fail(function(jqXHR, textStatus, errorThrown) {
|
||||
|
||||
@@ -95,7 +95,7 @@ $(function() {
|
||||
self._printerProfileUpdated = function() {
|
||||
var graphColors = ["red", "orange", "green", "brown", "purple"];
|
||||
var heaterOptions = {};
|
||||
var tools = self.tools();
|
||||
var tools = [];
|
||||
var color;
|
||||
|
||||
// tools
|
||||
@@ -123,7 +123,7 @@ $(function() {
|
||||
if (tools.length < 1 || !tools[0]) {
|
||||
tools[0] = self._createToolEntry();
|
||||
}
|
||||
tools[0]["name"](gettext("Hotend"));
|
||||
tools[0]["name"](gettext("Tool"));
|
||||
tools[0]["key"]("tool0");
|
||||
}
|
||||
|
||||
@@ -147,6 +147,7 @@ $(function() {
|
||||
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
|
||||
self._printerProfileUpdated();
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().extruder.sharedNozzle.subscribe(self._printerProfileUpdated);
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated);
|
||||
});
|
||||
|
||||
@@ -721,9 +722,7 @@ $(function() {
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.changeOffsetDialog = $("#change_offset_dialog");
|
||||
};
|
||||
|
||||
|
||||
@@ -272,6 +272,16 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.gotoTerminalCommand = function() {
|
||||
// skip if user highlights text.
|
||||
var sel = getSelection().toString();
|
||||
if (sel) {
|
||||
return;
|
||||
}
|
||||
|
||||
$("#terminal-command").focus();
|
||||
};
|
||||
|
||||
self.toggleAutoscroll = function() {
|
||||
self.autoscrollEnabled(!self.autoscrollEnabled());
|
||||
};
|
||||
|
||||
@@ -192,9 +192,25 @@ $(function() {
|
||||
self.onSettingsPreventRefresh = function() {
|
||||
if (!self.finishing && self.isDialogActive()
|
||||
&& hasDataChanged(self.settingsViewModel.getLocalData(), self.settingsViewModel.lastReceivedSettings)) {
|
||||
var preventSettingsRefreshDialog = false;
|
||||
callViewModels(self.allViewModels, "onWizardPreventSettingsRefreshDialog", function(method) {
|
||||
// if any of our methods returns that it wants to prevent the dialog
|
||||
// we'll need to set preventSettingsRefreshDialog to true
|
||||
//
|
||||
// order is important here - the method call needs to happen
|
||||
// first, or it won't happen after the flag has been
|
||||
// set once due to the || making further evaluation unnecessary
|
||||
// then
|
||||
preventSettingsRefreshDialog = (method() === true) || preventSettingsRefreshDialog;
|
||||
});
|
||||
|
||||
// we have local changes, show update dialog
|
||||
self.settingsViewModel.settingsUpdatedDialog.modal("show");
|
||||
return true;
|
||||
if (preventSettingsRefreshDialog) {
|
||||
return false;
|
||||
} else {
|
||||
self.settingsViewModel.settingsUpdatedDialog.modal("show");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
@@ -435,8 +435,11 @@ table {
|
||||
}
|
||||
|
||||
&.temperature_tool {
|
||||
width: 18%;
|
||||
width: 16%;
|
||||
text-align: left;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
&.temperature_actual {
|
||||
@@ -444,7 +447,7 @@ table {
|
||||
}
|
||||
|
||||
&.temperature_target {
|
||||
width: 40%;
|
||||
width: 42%;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
@@ -875,10 +878,6 @@ ul.dropdown-menu li a {
|
||||
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
#terminal-sendpanel {
|
||||
text-align: right;
|
||||
}
|
||||
}
|
||||
|
||||
#settings_dialog {
|
||||
@@ -1129,10 +1128,6 @@ textarea.block {
|
||||
display: inline-block !important;
|
||||
}
|
||||
|
||||
a.dropdown-sd {
|
||||
padding-top: 4px !important;
|
||||
}
|
||||
|
||||
.center {
|
||||
float: none;
|
||||
margin-left: auto;
|
||||
@@ -1295,6 +1290,40 @@ _::-webkit-full-page-media, _:future, :root .full-sized-box {
|
||||
}
|
||||
}
|
||||
|
||||
// block level inputs with add-ons
|
||||
//
|
||||
// LESS based on CSS from https://stackoverflow.com/a/17466199/2028598
|
||||
//
|
||||
// Note: do not use <button> for attached buttons, use <a class="btn add-on">...</a>
|
||||
// instead
|
||||
|
||||
.input-append,
|
||||
.input-prepend {
|
||||
&.input-block-level {
|
||||
display: table;
|
||||
|
||||
.add-on {
|
||||
display: table-cell;
|
||||
width: 1%; /* remove this if you want default bootstrap button width */
|
||||
}
|
||||
|
||||
> input {
|
||||
box-sizing: border-box; /* use bootstrap mixin or include vendor variants */
|
||||
display: table; /* table-cell is not working well in Chrome for small widths */
|
||||
min-height: inherit;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.input-append.input-block-level > input {
|
||||
border-right: 0;
|
||||
}
|
||||
|
||||
.input-prepend.input-block-level > input {
|
||||
border-left: 0;
|
||||
}
|
||||
|
||||
.btn-input-dec,
|
||||
.btn-input-enc {
|
||||
//font-size: 80%;
|
||||
|
||||
@@ -151,6 +151,18 @@
|
||||
<input type="checkbox" data-bind="checked: serial_supportResendsWithoutOk" id="settings-supportResendsWithoutOk"> {{ _('Simulate an additional <code>ok</code> for resend requests') }}
|
||||
</label>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_logPositionOnPause" id="settings-logPositionOnPause"> {{ _('Log position on pause') }} <span class="label label-important">{{ _('Warning') }}</span>
|
||||
<span class="help-block">{{ _('If you disabled this, the <code>pause_position</code> placeholders in your pause/resume GCODE scripts will stay unpopulated! However, pausing speed might improve slightly.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_logPositionOnCancel" id="settings-logPositionOnCancel"> {{ _('Log position on cancel') }} <span class="label label-important">{{ _('Warning') }}</span>
|
||||
<span class="help-block">{{ _('If you disabled this, the <code>cancel_position</code> placeholders in your cancel GCODE script and the corresponding data in the print recovery data will stay unpopulated! However, cancelling speed might improve slightly.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while idle. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
|
||||
<label class="control-label" for="settings-serialMaxTimeoutsIdle">{{ _('Max. consecutive timeouts while idle') }}</label>
|
||||
<div class="controls">
|
||||
|
||||
@@ -4,4 +4,10 @@
|
||||
{% include "snippets/settings/server/serverCommandServerRestart.jinja2" %}
|
||||
{% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %}
|
||||
{% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
|
||||
|
||||
<h3>{{ _('Connectivity check') }}</h3>
|
||||
|
||||
{% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheck.jinja2" %}
|
||||
|
||||
</form>
|
||||
@@ -5,7 +5,7 @@
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p data-bind="text: changingOffset.description"></p>
|
||||
<form class="form-horizontal">
|
||||
<form class="form-horizontal" data-bind="submit: confirmChangeOffset">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Current Offset') }}</label>
|
||||
<div class="controls">
|
||||
@@ -29,6 +29,6 @@
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
|
||||
<a href="javascript:void(0)" class="btn btn-primary" data-bind="click: confirmChangeOffset">{{ _('Submit') }}</a>
|
||||
<a href="javascript:void(0)" class="btn btn-primary" data-bind="click: confirmChangeOffset">{{ _('Save') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -5,7 +5,7 @@
|
||||
<div id="login_dropdown_loggedout" style="padding: 15px" class="dropdown-menu" data-bind="css: {hide: loginState.loggedIn(), 'dropdown-menu': !loginState.loggedIn()}">
|
||||
<form id="loginForm" data-bind="event: {'submit': loginState.prepareLogin }">
|
||||
<label for="login_user">{{ _('Username') }}</label>
|
||||
<input type="text" id="login_user" name="username" data-bind="valueWithInit: loginState.loginUser" placeholder="{{ _('Username') }}" autocapitalize="none">
|
||||
<input type="text" id="login_user" name="username" data-bind="valueWithInit: loginState.loginUser" placeholder="{{ _('Username') }}" autocapitalize="none" autocorrect="off">
|
||||
<label for="login_pass">{{ _('Password') }}</label>
|
||||
<input type="password" id="login_pass" name="password" data-bind="valueWithInit: loginState.loginPass" placeholder="{{ _('Password') }}">
|
||||
<label class="checkbox">
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
|
||||
{% if enableSdSupport %}
|
||||
<div class="sd-trigger accordion-heading-button btn-group">
|
||||
<a class="dropdown-toggle dropdown-sd" data-toggle="dropdown" href="#" title="{{ _('SD Card operations') }}">
|
||||
<a class="dropdown-toggle" data-toggle="dropdown" href="#" title="{{ _('SD Card operations') }}">
|
||||
<span class="icon-sd-black-14"></span>
|
||||
</a>
|
||||
<ul class="dropdown-menu">
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
{% include "snippets/settings/server/serverOnlineCheckEnabled.jinja2" %}
|
||||
|
||||
<div data-bind="visible: server_onlineCheck_enabled">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<p>{% trans %}
|
||||
Define a check interval, a host and a port to check against. If you don't know what to set here, the
|
||||
default values (using Google's DNS server) should work. If you have concerns about using
|
||||
that, define the IP and port of a different online server that you trust and that has a high
|
||||
availability.
|
||||
{% endtrans %}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %}
|
||||
</div>
|
||||
@@ -0,0 +1,5 @@
|
||||
<p>{% trans %}
|
||||
If the connectivity check is enabled, OctoPrint will regularly check if it's connected to the internet.
|
||||
This is <strong>useful to prevent resource intensive operations</strong> (such as checking for updates) if it's already
|
||||
clear that they won't succeed anyhow.
|
||||
{% endtrans %}</p>
|
||||
@@ -0,0 +1,7 @@
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: server_onlineCheck_enabled" id="settings-serverOnlineCheckEnabled"> {{ _('Enable regular connectivity check') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,6 @@
|
||||
<div class="control-group" title="{{ _('Host against which to check for internet connectivity') }}">
|
||||
<label class="control-label" for="settings-serverOnlineCheckHost">{{ _('Host IP') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-small" data-bind="value: server_onlineCheck_host" id="settings-serverOnlineCheckHost">
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,9 @@
|
||||
<div class="control-group" title="{{ _('Interval in which to check for internet connectivity') }}">
|
||||
<label class="control-label" for="settings-serverOnlineCheckInterval">{{ _('Check interval') }}</label>
|
||||
<div class="controls">
|
||||
<span class="input-append">
|
||||
<input type="number" min="1" step="1" class="input-mini" data-bind="value: server_onlineCheck_interval" id="settings-serverOnlineCheckInterval">
|
||||
<span class="add-on">min</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,6 @@
|
||||
<div class="control-group" title="{{ _('Port against which to check for internet connectivity') }}">
|
||||
<label class="control-label" for="settings-serverOnlineCheckHost">{{ _('Port') }}</label>
|
||||
<div class="controls">
|
||||
<input type="number" min="1" max="65535" step="1" class="input-small" data-bind="value: server_onlineCheck_port" id="settings-serverOnlineCheckPort">
|
||||
</div>
|
||||
</div>
|
||||
@@ -130,7 +130,7 @@
|
||||
</script>
|
||||
<script type="text/html" id="customControls_containerTemplate_collapsable">
|
||||
<div class="custom_section">
|
||||
<h1 class="fa" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.custom_section', container: '> div' }"><i class="fa" data-bind="css: {'fa-caret-down': !collapsed, 'fa-caret-right': collapsed}"></i> <span data-bind="text: name"></span></h1>
|
||||
<h1 data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.custom_section', container: '> div' }"><i class="fa" data-bind="css: {'fa-caret-down': !collapsed, 'fa-caret-right': collapsed}"></i> <span data-bind="text: name"></span></h1>
|
||||
<!-- ko template: { name: 'customControls_containerTemplate', data: $data } --><!-- /ko -->
|
||||
</div>
|
||||
</script>
|
||||
|
||||
@@ -19,8 +19,8 @@
|
||||
</table>
|
||||
|
||||
<script type="text/html" id="temprow-template">
|
||||
<th class="temperature_tool" data-bind="text: name"></th>
|
||||
<td class="temperature_actual" data-bind="html: formatTemperature(actual())"></td>
|
||||
<th class="temperature_tool" data-bind="text: name, attr: {title: name}"></th>
|
||||
<td class="temperature_actual" data-bind="html: formatTemperature(actual()), attr: {title: formatTemperature(actual())}"></td>
|
||||
<td class="temperature_target">
|
||||
<form class="form-inline" style="margin:0" data-bind="submit: function(element) { $root.setTarget($data, element) }">
|
||||
<div class="input-prepend input-append">
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
<div class="terminal">
|
||||
<pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality()"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span></pre>
|
||||
<pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality(), click: function(){ gotoTerminalCommand(); }"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span></pre>
|
||||
<pre id="terminal-output-lowfi" style="display: none" class="pre-scrollable" data-bind="text: plainLogOutput, visible: !fancyFunctionality()"></pre>
|
||||
<div id="terminal-sendpanel" style="display: none;" data-bind="visible: loginState.isUser">
|
||||
<div class="input-block-level input-append">
|
||||
<input type="text" id="terminal-command" data-bind="value: command, event: { keyup: function(d,e) { return handleKeyUp(e); }, keydown: function(d,e) { return handleKeyDown(e); } }, enable: isOperational() && loginState.isUser()" autocomplete="off">
|
||||
<a class="btn add-on" id="terminal-send" data-bind="click: sendCommand, enable: isOperational() && loginState.isUser()">{{ _('Send') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
<small class="pull-left" data-bind="visible: fancyFunctionality()"><button class="btn btn-mini" data-bind="click: toggleAutoscroll, css: {active: autoscrollEnabled}">{{ _('Autoscroll') }}</button> <span data-bind="text: lineCount, visible: enableFancyFunctionality"></span></small>
|
||||
<small class="pull-right" data-bind="visible: fancyFunctionality()"><a href="#" data-bind="click: scrollToEnd">{{ _("Scroll to end") }}</a> | <a href="#" data-bind="click: selectAll">{{ _("Select all") }}</a></small>
|
||||
<small class="pull-left muted" data-bind="visible: !fancyFunctionality()" style="display: none">{{ _('For performance reasons only a limited amount of terminal functionality is enabled right now.') }}</small>
|
||||
<small class="pull-left text-warning" data-bind="visible: !fancyFunctionality()" style="display: none">{{ _('For performance reasons only a limited amount of terminal functionality is enabled right now.') }}</small>
|
||||
</div>
|
||||
|
||||
<div class="row-fluid">
|
||||
@@ -14,13 +20,6 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="span6" id="terminal-sendpanel" style="display: none;" data-bind="visible: loginState.isUser">
|
||||
<div class="input-append">
|
||||
<input type="text" id="terminal-command" data-bind="value: command, event: { keyup: function(d,e) { return handleKeyUp(e); }, keydown: function(d,e) { return handleKeyDown(e); } }, enable: isOperational() && loginState.isUser()" autocomplete="off">
|
||||
<button class="btn" type="button" id="terminal-send" data-bind="click: sendCommand, enable: isOperational() && loginState.isUser()">{{ _('Send') }}</button>
|
||||
</div>
|
||||
<small class="muted">{{ _('Hint: Use the arrow up/down keys to recall commands sent previously') }}</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
|
||||
@@ -116,7 +116,7 @@
|
||||
</div>
|
||||
|
||||
<div data-bind="visible: unrenderedListHelper.allSize">
|
||||
<div><small><a href="javascript:void(0)" class="fa muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Unrendered Timelapses') }}</a></small></div>
|
||||
<div><small><a href="javascript:void(0)" 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> {{ _('Unrendered Timelapses') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<div class="pull-left">
|
||||
<div class="btn-group">
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
+166
-16
@@ -735,22 +735,47 @@ def interface_addresses(family=None):
|
||||
if not ifaddress["addr"].startswith("169.254."):
|
||||
yield ifaddress["addr"]
|
||||
|
||||
def address_for_client(host, port):
|
||||
def address_for_client(host, port, timeout=3.05):
|
||||
"""
|
||||
Determines the address of the network interface on this host needed to connect to the indicated client host and port.
|
||||
"""
|
||||
|
||||
import socket
|
||||
|
||||
for address in interface_addresses():
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.bind((address, 0))
|
||||
sock.connect((host, port))
|
||||
return address
|
||||
if server_reachable(host, port, timeout=timeout, proto="udp", source=address):
|
||||
return address
|
||||
except:
|
||||
continue
|
||||
|
||||
def server_reachable(host, port, timeout=3.05, proto="tcp", source=None):
|
||||
"""
|
||||
Checks if a server is reachable
|
||||
|
||||
Args:
|
||||
host (str): host to check against
|
||||
port (int): port to check against
|
||||
timeout (float): timeout for check
|
||||
proto (str): ``tcp`` or ``udp``
|
||||
source (str): optional, socket used for check will be bound against this address if provided
|
||||
|
||||
Returns:
|
||||
boolean: True if a connection to the server could be opened, False otherwise
|
||||
"""
|
||||
|
||||
import socket
|
||||
|
||||
if proto not in ("tcp", "udp"):
|
||||
raise ValueError("proto must be either 'tcp' or 'udp'")
|
||||
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM if proto == "udp" else socket.SOCK_STREAM)
|
||||
sock.settimeout(timeout)
|
||||
if source is not None:
|
||||
sock.bind((source, 0))
|
||||
sock.connect((host, port))
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
@contextlib.contextmanager
|
||||
def atomic_write(filename, mode="w+b", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777):
|
||||
@@ -1046,7 +1071,7 @@ class InvariantContainer(object):
|
||||
return self._data.__iter__()
|
||||
|
||||
|
||||
class PrependQueue(queue.Queue):
|
||||
class PrependableQueue(queue.Queue):
|
||||
|
||||
def __init__(self, maxsize=0):
|
||||
queue.Queue.__init__(self, maxsize=maxsize)
|
||||
@@ -1082,21 +1107,21 @@ class PrependQueue(queue.Queue):
|
||||
self.queue.appendleft(item)
|
||||
|
||||
|
||||
class TypedQueue(PrependQueue):
|
||||
class TypedQueue(PrependableQueue):
|
||||
|
||||
def __init__(self, maxsize=0):
|
||||
PrependQueue.__init__(self, maxsize=maxsize)
|
||||
PrependableQueue.__init__(self, maxsize=maxsize)
|
||||
self._lookup = set()
|
||||
|
||||
def put(self, item, item_type=None, *args, **kwargs):
|
||||
PrependQueue.put(self, (item, item_type), *args, **kwargs)
|
||||
PrependableQueue.put(self, (item, item_type), *args, **kwargs)
|
||||
|
||||
def get(self, *args, **kwargs):
|
||||
item, _ = PrependQueue.get(self, *args, **kwargs)
|
||||
item, _ = PrependableQueue.get(self, *args, **kwargs)
|
||||
return item
|
||||
|
||||
def prepend(self, item, item_type=None, *args, **kwargs):
|
||||
PrependQueue.prepend(self, (item, item_type), *args, **kwargs)
|
||||
PrependableQueue.prepend(self, (item, item_type), *args, **kwargs)
|
||||
|
||||
def _put(self, item):
|
||||
_, item_type = item
|
||||
@@ -1106,10 +1131,10 @@ class TypedQueue(PrependQueue):
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
|
||||
queue.Queue._put(self, item)
|
||||
PrependableQueue._put(self, item)
|
||||
|
||||
def _get(self):
|
||||
item = PrependQueue._get(self)
|
||||
item = PrependableQueue._get(self)
|
||||
_, item_type = item
|
||||
|
||||
if item_type is not None:
|
||||
@@ -1125,10 +1150,135 @@ class TypedQueue(PrependQueue):
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
|
||||
PrependQueue._prepend(self, item)
|
||||
PrependableQueue._prepend(self, item)
|
||||
|
||||
class TypeAlreadyInQueue(Exception):
|
||||
def __init__(self, t, *args, **kwargs):
|
||||
Exception.__init__(self, *args, **kwargs)
|
||||
self.type = t
|
||||
|
||||
|
||||
class ConnectivityChecker(object):
|
||||
"""
|
||||
Regularly checks for online connectivity.
|
||||
|
||||
Tries to open a connection to the provided ``host`` and ``port`` every ``interval``
|
||||
seconds and sets the ``online`` status accordingly.
|
||||
"""
|
||||
|
||||
def __init__(self, interval, host, port, enabled=True, on_change=None):
|
||||
self._interval = interval
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._enabled = enabled
|
||||
self._on_change = on_change
|
||||
|
||||
self._logger = logging.getLogger(__name__ + ".connectivity_checker")
|
||||
|
||||
# we initialize the online flag to True if we are not enabled (we don't know any better
|
||||
# but these days it's probably a sane default)
|
||||
self._online = not self._enabled
|
||||
|
||||
self._check_worker = None
|
||||
self._check_mutex = threading.RLock()
|
||||
|
||||
self._run()
|
||||
|
||||
@property
|
||||
def online(self):
|
||||
"""Current online status, True if online, False if offline."""
|
||||
with self._check_mutex:
|
||||
return self._online
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
"""DNS host to query."""
|
||||
with self._check_mutex:
|
||||
return self._host
|
||||
|
||||
@host.setter
|
||||
def host(self, value):
|
||||
with self._check_mutex:
|
||||
self._host = value
|
||||
|
||||
@property
|
||||
def port(self):
|
||||
"""DNS port to query."""
|
||||
with self._check_mutex:
|
||||
return self._port
|
||||
|
||||
@port.setter
|
||||
def port(self, value):
|
||||
with self._check_mutex:
|
||||
self._port = value
|
||||
|
||||
@property
|
||||
def interval(self):
|
||||
"""Interval between consecutive automatic checks."""
|
||||
return self._interval
|
||||
|
||||
@interval.setter
|
||||
def interval(self, value):
|
||||
self._interval = value
|
||||
|
||||
@property
|
||||
def enabled(self):
|
||||
"""Whether the check is enabled or not."""
|
||||
return self._enabled
|
||||
|
||||
@enabled.setter
|
||||
def enabled(self, value):
|
||||
with self._check_mutex:
|
||||
old_enabled = self._enabled
|
||||
self._enabled = value
|
||||
|
||||
if not self._enabled:
|
||||
if self._check_worker is not None:
|
||||
self._check_worker.cancel()
|
||||
|
||||
old_value = self._online
|
||||
self._online = True
|
||||
|
||||
if old_value != self._online:
|
||||
self._trigger_change(old_value, self._online)
|
||||
|
||||
elif self._enabled and not old_enabled:
|
||||
self._run()
|
||||
|
||||
def check_immediately(self):
|
||||
"""Check immediately and return result."""
|
||||
with self._check_mutex:
|
||||
self._perform_check()
|
||||
return self.online
|
||||
|
||||
def _run(self):
|
||||
from octoprint.util import RepeatedTimer
|
||||
|
||||
if not self._enabled:
|
||||
return
|
||||
|
||||
if self._check_worker is not None:
|
||||
self._check_worker.cancel()
|
||||
|
||||
self._check_worker = RepeatedTimer(self._interval, self._perform_check,
|
||||
run_first=True)
|
||||
self._check_worker.start()
|
||||
|
||||
def _perform_check(self):
|
||||
if not self._enabled:
|
||||
return
|
||||
|
||||
with self._check_mutex:
|
||||
self._logger.debug("Checking against {}:{} if we are online...".format(self._host, self._port))
|
||||
|
||||
old_value = self._online
|
||||
self._online = server_reachable(self._host, port=self._port)
|
||||
|
||||
if old_value != self._online:
|
||||
self._trigger_change(old_value, self._online)
|
||||
|
||||
def _trigger_change(self, old_value, new_value):
|
||||
self._logger.info("Connectivity changed from {} to {}".format("online" if old_value else "offline",
|
||||
"online" if new_value else "offline"))
|
||||
if callable(self._on_change):
|
||||
self._on_change(old_value, new_value)
|
||||
+223
-115
@@ -32,7 +32,7 @@ from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import valid_file_type
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \
|
||||
to_unicode, bom_aware_open, TypedQueue, TypeAlreadyInQueue, chunks
|
||||
to_unicode, bom_aware_open, TypedQueue, PrependableQueue, TypeAlreadyInQueue, chunks
|
||||
|
||||
try:
|
||||
import _winreg
|
||||
@@ -47,7 +47,7 @@ regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
|
||||
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
|
||||
regex_int_pattern = "\d+"
|
||||
|
||||
regex_command = re.compile("^\s*((?P<commandGM>[GM]\d+)|(?P<commandT>T)\d+|(?P<commandF>F)\d+)")
|
||||
regex_command = re.compile("^\s*((?P<codeGM>[GM]\d+)(\\.(?P<subcode>\d+))?|(?P<codeT>T)\d+|(?P<codeF>F)\d+)")
|
||||
"""Regex for a GCODE command."""
|
||||
|
||||
regex_float = re.compile(regex_float_pattern)
|
||||
@@ -89,7 +89,7 @@ Groups will be as follows:
|
||||
* ``size``: size of the file in bytes (int)
|
||||
"""
|
||||
|
||||
regex_temp = re.compile("(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?" % (regex_positive_float_pattern, regex_positive_float_pattern))
|
||||
regex_temp = re.compile("(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?" % (regex_float_pattern, regex_float_pattern))
|
||||
"""Regex matching temperature entries in line.
|
||||
|
||||
Groups will be as follows:
|
||||
@@ -100,7 +100,7 @@ Groups will be as follows:
|
||||
* ``target``: target temperature, if provided (float)
|
||||
"""
|
||||
|
||||
regex_repetierTempExtr = re.compile("TargetExtr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern)
|
||||
regex_repetierTempExtr = re.compile("TargetExtr(?P<toolnum>\d+):(?P<target>%s)" % regex_float_pattern)
|
||||
"""Regex for matching target temp reporting from Repetier.
|
||||
|
||||
Groups will be as follows:
|
||||
@@ -110,7 +110,7 @@ Groups will be as follows:
|
||||
* ``target``: new target temperature (float)
|
||||
"""
|
||||
|
||||
regex_repetierTempBed = re.compile("TargetBed:(?P<target>%s)" % regex_positive_float_pattern)
|
||||
regex_repetierTempBed = re.compile("TargetBed:(?P<target>%s)" % regex_float_pattern)
|
||||
"""Regex for matching target temp reporting from Repetier for beds.
|
||||
|
||||
Groups will be as follows:
|
||||
@@ -422,7 +422,7 @@ class MachineCom(object):
|
||||
self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"])
|
||||
|
||||
self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
|
||||
self._send_queue = TypedQueue()
|
||||
self._send_queue = SendQueue()
|
||||
self._temperature_timer = None
|
||||
self._sd_status_timer = None
|
||||
|
||||
@@ -461,6 +461,9 @@ class MachineCom(object):
|
||||
self._record_pause_data = False
|
||||
self._record_cancel_data = False
|
||||
|
||||
self._log_position_on_pause = settings().getBoolean(["serial", "logPositionOnPause"])
|
||||
self._log_position_on_cancel = settings().getBoolean(["serial", "logPositionOnCancel"])
|
||||
|
||||
# print job
|
||||
self._currentFile = None
|
||||
|
||||
@@ -944,7 +947,10 @@ class MachineCom(object):
|
||||
except:
|
||||
pass
|
||||
|
||||
self.sendCommand("M400", on_sent=_on_M400_sent)
|
||||
if self._log_position_on_cancel:
|
||||
self.sendCommand("M400", on_sent=_on_M400_sent)
|
||||
else:
|
||||
self._cancel_preparation_done()
|
||||
|
||||
def _pause_preparation_done(self):
|
||||
self._callback.on_comm_print_job_paused()
|
||||
@@ -991,7 +997,10 @@ class MachineCom(object):
|
||||
self._record_pause_data = True
|
||||
self.sendCommand("M114")
|
||||
|
||||
self.sendCommand("M400", on_sent=_on_M400_sent)
|
||||
if self._log_position_on_pause:
|
||||
self.sendCommand("M400", on_sent=_on_M400_sent)
|
||||
else:
|
||||
self._pause_preparation_done()
|
||||
|
||||
def getSdFiles(self):
|
||||
return self._sdFiles
|
||||
@@ -2068,6 +2077,7 @@ class MachineCom(object):
|
||||
self._to_logfile_with_terminal("Got a resend request from the printer: requested line = {}, current line = {}".format(lineToResend, self._currentLine))
|
||||
self._log_resends_rate_count += 1
|
||||
|
||||
self._send_queue.resend_active = True
|
||||
return True
|
||||
finally:
|
||||
if self._supportResendsWithoutOk:
|
||||
@@ -2096,7 +2106,7 @@ class MachineCom(object):
|
||||
cmd = self._lastLines[-self._resendDelta]
|
||||
lineNumber = self._currentLine - self._resendDelta
|
||||
|
||||
result = self._enqueue_for_sending(cmd, linenumber=lineNumber)
|
||||
result = self._enqueue_for_sending(cmd, linenumber=lineNumber, resend=True)
|
||||
|
||||
self._resendDelta -= 1
|
||||
if self._resendDelta <= 0:
|
||||
@@ -2104,6 +2114,8 @@ class MachineCom(object):
|
||||
self._lastResendNumber = None
|
||||
self._currentResendCount = 0
|
||||
|
||||
self._send_queue.resend_active = False
|
||||
|
||||
return result
|
||||
|
||||
def _sendCommand(self, cmd, cmd_type=None, on_sent=None):
|
||||
@@ -2112,20 +2124,20 @@ class MachineCom(object):
|
||||
if self._serial is None:
|
||||
return False
|
||||
|
||||
gcode = None
|
||||
gcode, subcode = gcode_and_subcode_for_cmd(cmd)
|
||||
|
||||
if not self.isStreaming():
|
||||
# trigger the "queuing" phase only if we are not streaming to sd right now
|
||||
results = self._process_command_phase("queuing", cmd, cmd_type, gcode=gcode)
|
||||
results = self._process_command_phase("queuing", cmd, command_type=cmd_type, gcode=gcode, subcode=subcode)
|
||||
|
||||
if not results:
|
||||
# command is no more, return
|
||||
return False
|
||||
else:
|
||||
results = [(cmd, cmd_type, gcode)]
|
||||
results = [(cmd, cmd_type, gcode, subcode)]
|
||||
|
||||
# process helper
|
||||
def process(cmd, cmd_type, gcode, on_sent=None):
|
||||
def process(cmd, cmd_type, gcode, subcode, on_sent=None):
|
||||
if cmd is None:
|
||||
# no command, next entry
|
||||
return False
|
||||
@@ -2138,7 +2150,7 @@ class MachineCom(object):
|
||||
if self._enqueue_for_sending(cmd, command_type=cmd_type, on_sent=on_sent):
|
||||
if not self.isStreaming():
|
||||
# trigger the "queued" phase only if we are not streaming to sd right now
|
||||
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
|
||||
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode, subcode=subcode)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
@@ -2155,18 +2167,18 @@ class MachineCom(object):
|
||||
enqueued_something = False
|
||||
|
||||
# process all but the last ...
|
||||
for (cmd, cmd_type, gcode) in results:
|
||||
enqueued_something = process(cmd, cmd_type, gcode) or enqueued_something
|
||||
for (cmd, cmd_type, gcode, subcode) in results:
|
||||
enqueued_something = process(cmd, cmd_type, gcode, subcode) or enqueued_something
|
||||
|
||||
# ... and then process the last one with the on_sent callback attached
|
||||
cmd, cmd_type, gcode = last_command
|
||||
enqueued_something = process(cmd, cmd_type, gcode, on_sent=on_sent) or enqueued_something
|
||||
cmd, cmd_type, gcode, subcode = last_command
|
||||
enqueued_something = process(cmd, cmd_type, gcode, subcode, on_sent=on_sent) or enqueued_something
|
||||
|
||||
return enqueued_something
|
||||
|
||||
##~~ send loop handling
|
||||
|
||||
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None):
|
||||
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None, resend=False):
|
||||
"""
|
||||
Enqueues a command and optional linenumber to use for it in the send queue.
|
||||
|
||||
@@ -2180,7 +2192,11 @@ class MachineCom(object):
|
||||
"""
|
||||
|
||||
try:
|
||||
self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type)
|
||||
target = "send"
|
||||
if resend:
|
||||
target = "resend"
|
||||
|
||||
self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type, target=target)
|
||||
return True
|
||||
except TypeAlreadyInQueue as e:
|
||||
self._logger.debug("Type already in send queue: " + e.type)
|
||||
@@ -2188,7 +2204,7 @@ class MachineCom(object):
|
||||
|
||||
def _send_loop(self):
|
||||
"""
|
||||
The send loop is reponsible of sending commands in ``self._send_queue`` over the line, if it is cleared for
|
||||
The send loop is responsible of sending commands in ``self._send_queue`` over the line, if it is cleared for
|
||||
sending (through received ``ok`` responses from the printer's firmware.
|
||||
"""
|
||||
|
||||
@@ -2216,7 +2232,7 @@ class MachineCom(object):
|
||||
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
|
||||
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
|
||||
# at hand here and only clear our clear_to_send flag later if that's the case
|
||||
gcode = gcode_command_for_cmd(command)
|
||||
gcode, subcode = gcode_and_subcode_for_cmd(command)
|
||||
|
||||
if linenumber is not None:
|
||||
# line number predetermined - this only happens for resends, so we'll use the number and
|
||||
@@ -2226,7 +2242,7 @@ class MachineCom(object):
|
||||
else:
|
||||
if not processed:
|
||||
# trigger "sending" phase if we didn't so far
|
||||
results = self._process_command_phase("sending", command, command_type, gcode=gcode)
|
||||
results = self._process_command_phase("sending", command, command_type, gcode=gcode, subcode=subcode)
|
||||
|
||||
if not results:
|
||||
# No, we are not going to send this, that was a last-minute bail.
|
||||
@@ -2239,20 +2255,14 @@ class MachineCom(object):
|
||||
# and now let's fetch the next item from the queue
|
||||
continue
|
||||
|
||||
if len(results) > 1:
|
||||
# last command gets on_sent attached
|
||||
last = results[-1]
|
||||
self._send_queue.prepend((last[0], None, None, on_sent, True))
|
||||
on_sent = None
|
||||
# we explicitly throw away plugin hook results that try
|
||||
# to perform command expansion in the sending/sent phase,
|
||||
# so "results" really should only have more than one entry
|
||||
# at this point if our core code contains a bug
|
||||
assert len(results) == 1
|
||||
|
||||
# middle gets prepended reversed (so order gets restored)
|
||||
if len(results) > 2:
|
||||
to_prepend = reversed(results[1:-1])
|
||||
for m in to_prepend:
|
||||
self._send_queue.prepend((m[0], None, None, None, True))
|
||||
|
||||
# we only actually send the first entry here
|
||||
command, _, gcode = results[0]
|
||||
# we only use the first (and only!) entry here
|
||||
command, _, gcode, subcode = results[0]
|
||||
|
||||
if command.strip() == "":
|
||||
self._logger.info("Refusing to send an empty line to the printer")
|
||||
@@ -2280,7 +2290,7 @@ class MachineCom(object):
|
||||
if on_sent is not None and callable(on_sent):
|
||||
# we have a sent callback for this specific command, let's execute it now
|
||||
on_sent()
|
||||
self._process_command_phase("sent", command, command_type, gcode=gcode)
|
||||
self._process_command_phase("sent", command, command_type, gcode=gcode, subcode=subcode)
|
||||
|
||||
# we only need to use up a clear if the command we just sent was either a gcode command or if we also
|
||||
# require ack's for unknown commands
|
||||
@@ -2308,10 +2318,10 @@ class MachineCom(object):
|
||||
self._logger.exception("Caught an exception in the send loop")
|
||||
self._log("Closing down send loop")
|
||||
|
||||
def _process_command_phase(self, phase, command, command_type=None, gcode=None):
|
||||
def _process_command_phase(self, phase, command, command_type=None, gcode=None, subcode=None):
|
||||
if gcode is None:
|
||||
gcode = gcode_command_for_cmd(command)
|
||||
results = [(command, command_type, gcode)]
|
||||
gcode, subcode = gcode_and_subcode_for_cmd(command)
|
||||
results = [(command, command_type, gcode, subcode)]
|
||||
|
||||
if (self.isStreaming() and self.isPrinting()) or phase not in ("queuing", "queued", "sending", "sent"):
|
||||
return results
|
||||
@@ -2319,14 +2329,20 @@ class MachineCom(object):
|
||||
# send it through the phase specific handlers provided by plugins
|
||||
for name, hook in self._gcode_hooks[phase].items():
|
||||
new_results = []
|
||||
for command, command_type, gcode in results:
|
||||
for command, command_type, gcode, subcode in results:
|
||||
try:
|
||||
hook_results = hook(self, phase, command, command_type, gcode)
|
||||
hook_results = hook(self, phase, command, command_type, gcode, subcode=subcode)
|
||||
except:
|
||||
self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals()))
|
||||
else:
|
||||
normalized = _normalize_command_handler_result(command, command_type, gcode, hook_results)
|
||||
new_results += normalized
|
||||
normalized = _normalize_command_handler_result(command, command_type, gcode, subcode, hook_results)
|
||||
|
||||
# make sure we don't allow multi entry results in anything but the queuing phase
|
||||
if not phase in ("queuing",) and len(normalized) > 1:
|
||||
self._logger.error("Error while processing hook {name} for phase {phase} and command {command}: Hook returned multi-entry result for phase {phase} and command {command}. That's not supported, if you need to do multi expansion of commands you need to do this in the queuing phase. Ignoring hook result and sending command as-is.".format(**locals()))
|
||||
new_results.append((command, command_type, gcode, subcode))
|
||||
else:
|
||||
new_results += normalized
|
||||
if not new_results:
|
||||
# hook handler returned None or empty list for all commands, so we'll stop here and return a full out empty result
|
||||
return []
|
||||
@@ -2335,15 +2351,15 @@ class MachineCom(object):
|
||||
# if it's a gcode command send it through the specific handler if it exists
|
||||
new_results = []
|
||||
modified = False
|
||||
for command, command_type, gcode in results:
|
||||
for command, command_type, gcode, subcode in results:
|
||||
if gcode is not None:
|
||||
gcode_handler = "_gcode_" + gcode + "_" + phase
|
||||
if hasattr(self, gcode_handler):
|
||||
handler_results = getattr(self, gcode_handler)(command, cmd_type=command_type)
|
||||
new_results += _normalize_command_handler_result(command, command_type, gcode, handler_results)
|
||||
handler_results = getattr(self, gcode_handler)(command, cmd_type=command_type, subcode=subcode)
|
||||
new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results)
|
||||
modified = True
|
||||
else:
|
||||
new_results.append((command, command_type, gcode))
|
||||
new_results.append((command, command_type, gcode, subcode))
|
||||
modified = True
|
||||
if modified:
|
||||
if not new_results:
|
||||
@@ -2356,9 +2372,9 @@ class MachineCom(object):
|
||||
command_phase_handler = "_command_phase_" + phase
|
||||
if hasattr(self, command_phase_handler):
|
||||
new_results = []
|
||||
for command, command_type, gcode in results:
|
||||
handler_results = getattr(self, command_phase_handler)(command, cmd_type=command_type, gcode=gcode)
|
||||
new_results += _normalize_command_handler_result(command, command_type, gcode, handler_results)
|
||||
for command, command_type, gcode, subcode in results:
|
||||
handler_results = getattr(self, command_phase_handler)(command, cmd_type=command_type, gcode=gcode, subcode=subcode)
|
||||
new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results)
|
||||
results = new_results
|
||||
|
||||
# finally return whatever we resulted on
|
||||
@@ -2444,7 +2460,7 @@ class MachineCom(object):
|
||||
|
||||
##~~ command handlers
|
||||
|
||||
def _gcode_T_queuing(self, cmd, cmd_type=None):
|
||||
def _gcode_T_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
toolMatch = regexes_parameters["intT"].search(cmd)
|
||||
if toolMatch:
|
||||
current_tool = self._currentTool
|
||||
@@ -2455,14 +2471,14 @@ class MachineCom(object):
|
||||
|
||||
return before + [cmd] + after
|
||||
|
||||
def _gcode_T_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_T_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
toolMatch = regexes_parameters["intT"].search(cmd)
|
||||
if toolMatch:
|
||||
old = self._currentTool
|
||||
self._currentTool = int(toolMatch.group("value"))
|
||||
eventManager().fire(Events.TOOL_CHANGE, dict(old=old, new=self._currentTool))
|
||||
|
||||
def _gcode_G0_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_G0_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if "Z" in cmd or "F" in cmd:
|
||||
# track Z
|
||||
match = regexes_parameters["floatZ"].search(cmd)
|
||||
@@ -2485,7 +2501,7 @@ class MachineCom(object):
|
||||
pass
|
||||
_gcode_G1_sent = _gcode_G0_sent
|
||||
|
||||
def _gcode_G28_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_G28_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if "F" in cmd:
|
||||
match = regexes_parameters["floatF"].search(cmd)
|
||||
if match:
|
||||
@@ -2495,34 +2511,34 @@ class MachineCom(object):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def _gcode_M0_queuing(self, cmd, cmd_type=None):
|
||||
def _gcode_M0_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
self.setPause(True)
|
||||
return None, # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
|
||||
_gcode_M1_queuing = _gcode_M0_queuing
|
||||
|
||||
def _gcode_M25_queuing(self, cmd, cmd_type=None):
|
||||
def _gcode_M25_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
# M25 while not printing from SD will be handled as pause. This way it can be used as another marker
|
||||
# for GCODE induced pausing. Send it to the printer anyway though.
|
||||
if self.isPrinting() and not self.isSdPrinting():
|
||||
self.setPause(True)
|
||||
|
||||
def _gcode_M28_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_M28_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if not self.isStreaming():
|
||||
self._log("Detected manual streaming. Disabling temperature polling. Finish writing with M29. Do NOT attempt to print while manually streaming!")
|
||||
self._manualStreaming = True
|
||||
|
||||
def _gcode_M29_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_M29_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if self._manualStreaming:
|
||||
self._log("Manual streaming done. Re-enabling temperature polling. All is well.")
|
||||
self._manualStreaming = False
|
||||
|
||||
def _gcode_M140_queuing(self, cmd, cmd_type=None):
|
||||
def _gcode_M140_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if not self._printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
self._log("Warn: Not sending \"{}\", printer profile has no heated bed".format(cmd))
|
||||
return None, # Don't send bed commands if we don't have a heated bed
|
||||
_gcode_M190_queuing = _gcode_M140_queuing
|
||||
|
||||
def _gcode_M104_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
|
||||
def _gcode_M104_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, wait=False, support_r=False, *args, **kwargs):
|
||||
toolNum = self._currentTool
|
||||
toolMatch = regexes_parameters["intT"].search(cmd)
|
||||
|
||||
@@ -2545,7 +2561,7 @@ class MachineCom(object):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def _gcode_M140_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
|
||||
def _gcode_M140_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, wait=False, support_r=False, *args, **kwargs):
|
||||
match = regexes_parameters["floatS"].search(cmd)
|
||||
if not match and support_r:
|
||||
match = regexes_parameters["floatR"].search(cmd)
|
||||
@@ -2558,24 +2574,24 @@ class MachineCom(object):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def _gcode_M109_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_M109_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
self._heatupWaitStartTime = time.time()
|
||||
self._long_running_command = True
|
||||
self._heating = True
|
||||
self._gcode_M104_sent(cmd, cmd_type, wait=True, support_r=True)
|
||||
|
||||
def _gcode_M190_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_M190_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
self._heatupWaitStartTime = time.time()
|
||||
self._long_running_command = True
|
||||
self._heating = True
|
||||
self._gcode_M140_sent(cmd, cmd_type, wait=True, support_r=True)
|
||||
|
||||
def _gcode_M116_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_M116_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
self._heatupWaitStartTime = time.time()
|
||||
self._long_running_command = True
|
||||
self._heating = True
|
||||
|
||||
def _gcode_M155_sending(self, cmd, cmd_type=None):
|
||||
def _gcode_M155_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
match = regexes_parameters["intS"].search(cmd)
|
||||
if match:
|
||||
try:
|
||||
@@ -2585,7 +2601,7 @@ class MachineCom(object):
|
||||
except:
|
||||
pass
|
||||
|
||||
def _gcode_M110_sending(self, cmd, cmd_type=None):
|
||||
def _gcode_M110_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
newLineNumber = 0
|
||||
match = regexes_parameters["intN"].search(cmd)
|
||||
if match:
|
||||
@@ -2604,7 +2620,7 @@ class MachineCom(object):
|
||||
self._lastLines.clear()
|
||||
self._resendDelta = None
|
||||
|
||||
def _gcode_M112_queuing(self, cmd, cmd_type=None):
|
||||
def _gcode_M112_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
# emergency stop, jump the queue with the M112
|
||||
self._do_send_without_checksum("M112")
|
||||
self._do_increment_and_send_with_checksum("M112")
|
||||
@@ -2633,7 +2649,7 @@ class MachineCom(object):
|
||||
# I hope it got it the first time because as far as I can tell, there is no way to know
|
||||
return None,
|
||||
|
||||
def _gcode_G4_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_G4_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
# we are intending to dwell for a period of time, increase the timeout to match
|
||||
p_match = regexes_parameters["floatP"].search(cmd)
|
||||
s_match = regexes_parameters["floatS"].search(cmd)
|
||||
@@ -2649,7 +2665,7 @@ class MachineCom(object):
|
||||
|
||||
##~~ command phase handlers
|
||||
|
||||
def _command_phase_sending(self, cmd, cmd_type=None, gcode=None):
|
||||
def _command_phase_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if gcode is not None and gcode in self._long_running_commands:
|
||||
self._long_running_command = True
|
||||
|
||||
@@ -2925,6 +2941,88 @@ class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
|
||||
duration=duration)
|
||||
self._logger.info("Finished in {duration:.3f} s. Approx. transfer rate of {rate:.3f} lines/s or {time_per_line:.3f} ms per line".format(**stats))
|
||||
|
||||
|
||||
class SendQueue(PrependableQueue):
|
||||
|
||||
def __init__(self, maxsize=0):
|
||||
PrependableQueue.__init__(self, maxsize=maxsize)
|
||||
|
||||
self._resend_queue = PrependableQueue()
|
||||
self._send_queue = PrependableQueue()
|
||||
self._lookup = set()
|
||||
|
||||
self._resend_active = False
|
||||
|
||||
@property
|
||||
def resend_active(self):
|
||||
return self._resend_active
|
||||
|
||||
@resend_active.setter
|
||||
def resend_active(self, resend_active):
|
||||
with self.mutex:
|
||||
self._resend_active = resend_active
|
||||
|
||||
def prepend(self, item, item_type=None, target=None, block=True, timeout=None):
|
||||
PrependableQueue.prepend(self, (item, item_type, target), block=block, timeout=timeout)
|
||||
|
||||
def put(self, item, item_type=None, target=None, block=True, timeout=None):
|
||||
PrependableQueue.put(self, (item, item_type, target), block=block, timeout=timeout)
|
||||
|
||||
def get(self, block=True, timeout=None):
|
||||
item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout)
|
||||
return item
|
||||
|
||||
def _put(self, item):
|
||||
_, item_type, target = item
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
|
||||
if target == "resend":
|
||||
self._resend_queue.put(item)
|
||||
else:
|
||||
self._send_queue.put(item)
|
||||
|
||||
pass
|
||||
|
||||
def _prepend(self, item):
|
||||
_, item_type, target = item
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
|
||||
if target == "resend":
|
||||
self._resend_queue.prepend(item)
|
||||
else:
|
||||
self._send_queue.prepend(item)
|
||||
|
||||
def _get(self):
|
||||
if self.resend_active:
|
||||
item = self._resend_queue.get(block=False)
|
||||
else:
|
||||
try:
|
||||
item = self._resend_queue.get(block=False)
|
||||
except queue.Empty:
|
||||
item = self._send_queue.get(block=False)
|
||||
|
||||
_, item_type, _ = item
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
self._lookup.remove(item_type)
|
||||
|
||||
return item
|
||||
|
||||
def _qsize(self):
|
||||
if self.resend_active:
|
||||
return self._resend_queue.qsize()
|
||||
else:
|
||||
return self._resend_queue.qsize() + self._send_queue.qsize()
|
||||
|
||||
|
||||
def get_new_timeout(type, intervals):
|
||||
now = time.time()
|
||||
return now + intervals.get(type, 0.0)
|
||||
@@ -3277,35 +3375,43 @@ def gcode_command_for_cmd(cmd):
|
||||
Returns:
|
||||
str or None: The GCODE command identifier if it could be parsed, or None if not.
|
||||
"""
|
||||
|
||||
gcode, _ = gcode_and_subcode_for_cmd(cmd)
|
||||
return gcode
|
||||
|
||||
|
||||
def gcode_and_subcode_for_cmd(cmd):
|
||||
if not cmd:
|
||||
return None
|
||||
return None, None
|
||||
|
||||
gcode = regex_command.search(cmd)
|
||||
if not gcode:
|
||||
return None
|
||||
match = regex_command.search(cmd)
|
||||
if not match:
|
||||
return None, None
|
||||
|
||||
values = gcode.groupdict()
|
||||
if "commandGM" in values and values["commandGM"]:
|
||||
return values["commandGM"]
|
||||
elif "commandT" in values and values["commandT"]:
|
||||
return values["commandT"]
|
||||
elif settings().getBoolean(["feature", "supportFAsCommand"]) and "commandF" in values and values["commandF"]:
|
||||
return values["commandF"]
|
||||
values = match.groupdict()
|
||||
if "codeGM" in values and values["codeGM"]:
|
||||
gcode = values["codeGM"]
|
||||
elif "codeT" in values and values["codeT"]:
|
||||
gcode = values["codeT"]
|
||||
elif settings().getBoolean(["feature", "supportFAsCommand"]) and "codeF" in values and values["codeF"]:
|
||||
gcode = values["codeF"]
|
||||
else:
|
||||
# this should never happen
|
||||
return None
|
||||
return None, None
|
||||
|
||||
return gcode, values.get("subcode", None)
|
||||
|
||||
|
||||
def _normalize_command_handler_result(command, command_type, gcode, handler_results):
|
||||
def _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results):
|
||||
"""
|
||||
Normalizes a command handler result.
|
||||
|
||||
Handler results can be either ``None``, a single result entry or a list of result
|
||||
entries.
|
||||
|
||||
``None`` results are ignored, the provided ``command``, ``command_type``
|
||||
and ``gcode`` are returned in that case (as single-entry list with one
|
||||
3-tuple as entry).
|
||||
``None`` results are ignored, the provided ``command``, ``command_type``,
|
||||
``gcode`` and ``subcode`` are returned in that case (as single-entry list with
|
||||
one 4-tuple as entry).
|
||||
|
||||
Single result entries are either:
|
||||
|
||||
@@ -3317,31 +3423,31 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
|
||||
the normalized result.
|
||||
|
||||
The method returns a list of normalized result entries. Normalized result
|
||||
entries always are a 3-tuple consisting of ``command``, ``command_type``
|
||||
and ``gcode``, the latter two being allowed to be ``None``. The list may
|
||||
entries always are a 4-tuple consisting of ``command``, ``command_type``,
|
||||
``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may
|
||||
be empty in which case the command is to be suppressed.
|
||||
|
||||
Examples:
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None)
|
||||
[('M105', None, 'M105')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", "M110")
|
||||
[('M110', None, 'M110')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", ["M110"])
|
||||
[('M110', None, 'M110')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", ["M110", "M117 Foobar"])
|
||||
[('M110', None, 'M110'), ('M117 Foobar', None, 'M117')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", [("M110",), "M117 Foobar"])
|
||||
[('M110', None, 'M110'), ('M117 Foobar', None, 'M117')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", [("M110", "lineno_reset"), "M117 Foobar"])
|
||||
[('M110', 'lineno_reset', 'M110'), ('M117 Foobar', None, 'M117')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", [])
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None)
|
||||
[('M105', None, 'M105', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, "M110")
|
||||
[('M110', None, 'M110', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, ["M110"])
|
||||
[('M110', None, 'M110', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, ["M110", "M117 Foobar"])
|
||||
[('M110', None, 'M110', None), ('M117 Foobar', None, 'M117', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), "M117 Foobar"])
|
||||
[('M110', None, 'M110', None), ('M117 Foobar', None, 'M117', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110", "lineno_reset"), "M117 Foobar"])
|
||||
[('M110', 'lineno_reset', 'M110', None), ('M117 Foobar', None, 'M117', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, [])
|
||||
[]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", ["M110", None])
|
||||
[('M110', None, 'M110')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", [("M110",), (None, "ignored")])
|
||||
[('M110', None, 'M110')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of unexpected", "length"), ("M110", "lineno_reset")])
|
||||
[('M110', None, 'M110'), ('M117 Foobar', 'display_message', 'M117'), ('M110', 'lineno_reset', 'M110')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, ["M110", None])
|
||||
[('M110', None, 'M110', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), (None, "ignored")])
|
||||
[('M110', None, 'M110', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of unexpected", "length"), ("M110", "lineno_reset")])
|
||||
[('M110', None, 'M110', None), ('M117 Foobar', 'display_message', 'M117', None), ('M110', 'lineno_reset', 'M110', None)]
|
||||
|
||||
Arguments:
|
||||
command (str or None): The command for which the handler result was
|
||||
@@ -3350,16 +3456,18 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
|
||||
result was generated
|
||||
gcode (str or None): The GCODE for which the handler result was
|
||||
generated
|
||||
subcode (str or None): The GCODE subcode for which the handler result
|
||||
was generated
|
||||
handler_results: The handler result(s) to normalized. Can be either
|
||||
a single result entry or a list of result entries.
|
||||
|
||||
Returns:
|
||||
(list) - A list of normalized handler result entries, which are
|
||||
3-tuples consisting of ``command``, ``command_type`` and
|
||||
``gcode``, the latter two of which may be ``None``.
|
||||
4-tuples consisting of ``command``, ``command_type``, ``gcode``
|
||||
and ``subcode``, the latter three of which may be ``None``.
|
||||
"""
|
||||
|
||||
original = (command, command_type, gcode)
|
||||
original = (command, command_type, gcode, subcode)
|
||||
|
||||
if handler_results is None:
|
||||
# handler didn't return anything, we'll just continue
|
||||
@@ -3380,8 +3488,8 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
|
||||
if isinstance(handler_result, basestring):
|
||||
# entry is just a string, replace command with it
|
||||
command = handler_result
|
||||
gcode = gcode_command_for_cmd(command)
|
||||
result.append((command, command_type, gcode))
|
||||
gcode, subcode = gcode_and_subcode_for_cmd(command)
|
||||
result.append((command, command_type, gcode, subcode))
|
||||
|
||||
elif isinstance(handler_result, tuple):
|
||||
# entry is a tuple, extract command and command_type
|
||||
@@ -3401,11 +3509,11 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
|
||||
# command is None, ignore it and continue
|
||||
continue
|
||||
|
||||
gcode = gcode_command_for_cmd(command)
|
||||
result.append((command, command_type, gcode))
|
||||
gcode, subcode = gcode_and_subcode_for_cmd(command)
|
||||
result.append((command, command_type, gcode, subcode))
|
||||
|
||||
# reset to original
|
||||
command, command_type, gcode = original
|
||||
command, command_type, gcode, subcode = original
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -222,7 +222,6 @@ class gcode(object):
|
||||
lineNo = 0
|
||||
readBytes = 0
|
||||
pos = Vector3D(0.0, 0.0, 0.0)
|
||||
toolOffset = Vector3D(0.0, 0.0, 0.0)
|
||||
currentE = [0.0]
|
||||
totalExtrusion = [0.0]
|
||||
maxExtrusion = [0.0]
|
||||
@@ -320,16 +319,16 @@ class gcode(object):
|
||||
|
||||
# Use new coordinates if provided. If not provided, use prior coordinates (minus tool offset)
|
||||
# in absolute and 0.0 in relative mode.
|
||||
newPos = Vector3D(x if x is not None else (0.0 if relativeMode else pos.x - toolOffset.x),
|
||||
y if y is not None else (0.0 if relativeMode else pos.y - toolOffset.y),
|
||||
z if z is not None else (0.0 if relativeMode else pos.z - toolOffset.z))
|
||||
newPos = Vector3D(x if x is not None else (0.0 if relativeMode else pos.x),
|
||||
y if y is not None else (0.0 if relativeMode else pos.y),
|
||||
z if z is not None else (0.0 if relativeMode else pos.z))
|
||||
|
||||
if relativeMode:
|
||||
# Relative mode: scale and add to current position
|
||||
pos += newPos * scale
|
||||
else:
|
||||
# Absolute mode: scale coordinates and apply tool offsets
|
||||
pos = newPos * scale + toolOffset
|
||||
pos = newPos * scale
|
||||
|
||||
if f is not None and f != 0:
|
||||
feedrate = f
|
||||
@@ -442,14 +441,16 @@ class gcode(object):
|
||||
elif T is not None:
|
||||
if T > max_extruders:
|
||||
self._logger.warn("GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis" % T)
|
||||
elif T == currentExtruder:
|
||||
pass
|
||||
else:
|
||||
toolOffset.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
|
||||
toolOffset.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
|
||||
pos.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
|
||||
pos.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
|
||||
|
||||
currentExtruder = T
|
||||
|
||||
toolOffset.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
|
||||
toolOffset.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
|
||||
pos.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
|
||||
pos.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
|
||||
|
||||
if len(currentE) <= currentExtruder:
|
||||
for i in range(len(currentE), currentExtruder + 1):
|
||||
|
||||
+108
-103
@@ -10,6 +10,7 @@ import sarge
|
||||
import sys
|
||||
import logging
|
||||
import site
|
||||
import threading
|
||||
|
||||
import pkg_resources
|
||||
|
||||
@@ -17,6 +18,7 @@ from .commandline import CommandlineCaller, clean_ansi
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
_cache = dict(version=dict(), setup=dict())
|
||||
_cache_mutex = threading.RLock()
|
||||
|
||||
class UnknownPip(Exception):
|
||||
pass
|
||||
@@ -173,8 +175,6 @@ class PipCaller(CommandlineCaller):
|
||||
self._logger.error("This version of pip is known to have bugs that make it incompatible with how it needs to be used by OctoPrint. Please upgrade your pip version.")
|
||||
return
|
||||
|
||||
self._logger.info("Version of pip is {}".format(version_segment))
|
||||
|
||||
# Now figure out if pip belongs to a virtual environment and if the
|
||||
# default installation directory is writable.
|
||||
#
|
||||
@@ -194,10 +194,6 @@ class PipCaller(CommandlineCaller):
|
||||
self._logger.error("Cannot use pip")
|
||||
return
|
||||
|
||||
self._logger.info("pip installs to {}, --user flag needed => {}, virtual env => {}".format(pip_install_dir,
|
||||
"yes" if pip_user else "no",
|
||||
"yes" if pip_virtual_env else "no"))
|
||||
|
||||
self._command = pip_command
|
||||
self._version = pip_version
|
||||
self._version_string = version_segment
|
||||
@@ -251,122 +247,131 @@ class PipCaller(CommandlineCaller):
|
||||
if isinstance(pip_command_str, list):
|
||||
pip_command_str = " ".join(pip_command_str)
|
||||
|
||||
if not self.ignore_cache and pip_command_str in _cache["version"]:
|
||||
self._logger.debug("Using cached pip version information for {}".format(pip_command_str))
|
||||
return _cache["version"][pip_command_str]
|
||||
with _cache_mutex:
|
||||
if not self.ignore_cache and pip_command_str in _cache["version"]:
|
||||
self._logger.debug("Using cached pip version information for {}".format(pip_command_str))
|
||||
return _cache["version"][pip_command_str]
|
||||
|
||||
sarge_command = self.to_sarge_command(pip_command, "--version")
|
||||
p = sarge.run(sarge_command, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
sarge_command = self.to_sarge_command(pip_command, "--version")
|
||||
p = sarge.run(sarge_command, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
|
||||
if p.returncode != 0:
|
||||
self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
|
||||
return None, None
|
||||
if p.returncode != 0:
|
||||
self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
|
||||
return None, None
|
||||
|
||||
output = PipCaller._preprocess(p.stdout.text)
|
||||
# output should look something like this:
|
||||
#
|
||||
# pip <version> from <path> (<python version>)
|
||||
#
|
||||
# we'll just split on whitespace and then try to use the second entry
|
||||
output = PipCaller._preprocess(p.stdout.text)
|
||||
# output should look something like this:
|
||||
#
|
||||
# pip <version> from <path> (<python version>)
|
||||
#
|
||||
# we'll just split on whitespace and then try to use the second entry
|
||||
|
||||
if not output.startswith("pip"):
|
||||
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
|
||||
if not output.startswith("pip"):
|
||||
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
|
||||
|
||||
split_output = map(lambda x: x.strip(), output.split())
|
||||
if len(split_output) < 2:
|
||||
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
|
||||
split_output = map(lambda x: x.strip(), output.split())
|
||||
if len(split_output) < 2:
|
||||
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
|
||||
|
||||
version_segment = split_output[1]
|
||||
version_segment = split_output[1]
|
||||
|
||||
try:
|
||||
pip_version = pkg_resources.parse_version(version_segment)
|
||||
except:
|
||||
self._logger.exception("Error while trying to parse version string from pip command")
|
||||
return None, None
|
||||
try:
|
||||
pip_version = pkg_resources.parse_version(version_segment)
|
||||
except:
|
||||
self._logger.exception("Error while trying to parse version string from pip command")
|
||||
return None, None
|
||||
|
||||
result = pip_version, version_segment
|
||||
_cache["version"][pip_command_str] = result
|
||||
return result
|
||||
self._logger.info("Version of pip is {}".format(version_segment))
|
||||
|
||||
result = pip_version, version_segment
|
||||
_cache["version"][pip_command_str] = result
|
||||
return result
|
||||
|
||||
def _check_pip_setup(self, pip_command):
|
||||
pip_command_str = pip_command
|
||||
if isinstance(pip_command_str, list):
|
||||
pip_command_str = " ".join(pip_command_str)
|
||||
|
||||
if not self.ignore_cache and pip_command_str in _cache["setup"]:
|
||||
self._logger.debug("Using cached pip setup information for {}".format(pip_command_str))
|
||||
return _cache["setup"][pip_command_str]
|
||||
with _cache_mutex:
|
||||
if not self.ignore_cache and pip_command_str in _cache["setup"]:
|
||||
self._logger.debug("Using cached pip setup information for {}".format(pip_command_str))
|
||||
return _cache["setup"][pip_command_str]
|
||||
|
||||
# This is horribly ugly and I'm sorry...
|
||||
#
|
||||
# While we can figure out the install directory, if that's writable and if a virtual environment
|
||||
# is active for pip that belongs to our sys.executable python instance by just checking some
|
||||
# variables, we can't for stuff like third party software we allow to update via the software
|
||||
# update plugin.
|
||||
#
|
||||
# What we do instead for these situations is try to install (and of course uninstall) the
|
||||
# testballoon dummy package, which collects that information for us. For pip <= 7 we could
|
||||
# have the testballoon provide us with the info needed through stdout, if pip was called
|
||||
# with --verbose anything printed to stdout within setup.py would be output. Pip 8 managed
|
||||
# to break this mechanism. Any (!) output within setup.py appears to be suppressed now, and
|
||||
# no combination of --log and multiple --verbose or -v arguments could get it to bring the
|
||||
# output back.
|
||||
#
|
||||
# So here's what we do now instead. Our sarge call sets an environment variable
|
||||
# "TESTBALLOON_OUTPUT" that points to a temporary file. If the testballoon sees that
|
||||
# variable set, it opens the file and writes to it the output it so far printed on stdout.
|
||||
# We then open the file and read in the data that way.
|
||||
#
|
||||
# Yeah, I'm not happy with that either. But as long as there's no way to otherwise figure
|
||||
# out for a generic pip command whether OctoPrint can even install anything with that
|
||||
# and if so how, well, that's how we'll have to do things.
|
||||
# This is horribly ugly and I'm sorry...
|
||||
#
|
||||
# While we can figure out the install directory, if that's writable and if a virtual environment
|
||||
# is active for pip that belongs to our sys.executable python instance by just checking some
|
||||
# variables, we can't for stuff like third party software we allow to update via the software
|
||||
# update plugin.
|
||||
#
|
||||
# What we do instead for these situations is try to install (and of course uninstall) the
|
||||
# testballoon dummy package, which collects that information for us. For pip <= 7 we could
|
||||
# have the testballoon provide us with the info needed through stdout, if pip was called
|
||||
# with --verbose anything printed to stdout within setup.py would be output. Pip 8 managed
|
||||
# to break this mechanism. Any (!) output within setup.py appears to be suppressed now, and
|
||||
# no combination of --log and multiple --verbose or -v arguments could get it to bring the
|
||||
# output back.
|
||||
#
|
||||
# So here's what we do now instead. Our sarge call sets an environment variable
|
||||
# "TESTBALLOON_OUTPUT" that points to a temporary file. If the testballoon sees that
|
||||
# variable set, it opens the file and writes to it the output it so far printed on stdout.
|
||||
# We then open the file and read in the data that way.
|
||||
#
|
||||
# Yeah, I'm not happy with that either. But as long as there's no way to otherwise figure
|
||||
# out for a generic pip command whether OctoPrint can even install anything with that
|
||||
# and if so how, well, that's how we'll have to do things.
|
||||
|
||||
import os
|
||||
testballoon = os.path.join(os.path.realpath(os.path.dirname(__file__)), "piptestballoon")
|
||||
import os
|
||||
testballoon = os.path.join(os.path.realpath(os.path.dirname(__file__)), "piptestballoon")
|
||||
|
||||
from octoprint.util import temppath
|
||||
with temppath() as testballoon_output_file:
|
||||
sarge_command = self.to_sarge_command(pip_command, "install", ".")
|
||||
try:
|
||||
# our testballoon is no real package, so this command will fail - that's ok though,
|
||||
# we only need the output produced within the pip environment
|
||||
sarge.run(sarge_command,
|
||||
stdout=sarge.Capture(),
|
||||
stderr=sarge.Capture(),
|
||||
cwd=testballoon,
|
||||
env=dict(TESTBALLOON_OUTPUT=testballoon_output_file))
|
||||
except:
|
||||
self._logger.exception("Error while trying to install testballoon to figure out pip setup")
|
||||
from octoprint.util import temppath
|
||||
with temppath() as testballoon_output_file:
|
||||
sarge_command = self.to_sarge_command(pip_command, "install", ".")
|
||||
try:
|
||||
# our testballoon is no real package, so this command will fail - that's ok though,
|
||||
# we only need the output produced within the pip environment
|
||||
sarge.run(sarge_command,
|
||||
stdout=sarge.Capture(),
|
||||
stderr=sarge.Capture(),
|
||||
cwd=testballoon,
|
||||
env=dict(TESTBALLOON_OUTPUT=testballoon_output_file))
|
||||
except:
|
||||
self._logger.exception("Error while trying to install testballoon to figure out pip setup")
|
||||
return False, False, False, None
|
||||
|
||||
data = dict()
|
||||
with open(testballoon_output_file) as f:
|
||||
for line in f:
|
||||
key, value = line.split("=", 2)
|
||||
data[key] = value
|
||||
|
||||
install_dir_str = data.get("PIP_INSTALL_DIR", None)
|
||||
virtual_env_str = data.get("PIP_VIRTUAL_ENV", None)
|
||||
writable_str = data.get("PIP_WRITABLE", None)
|
||||
|
||||
if install_dir_str is not None and virtual_env_str is not None and writable_str is not None:
|
||||
install_dir = install_dir_str.strip()
|
||||
virtual_env = virtual_env_str.strip() == "True"
|
||||
writable = writable_str.strip() == "True"
|
||||
|
||||
can_use_user_flag = not virtual_env and site.ENABLE_USER_SITE
|
||||
|
||||
ok = writable or can_use_user_flag
|
||||
user_flag = not writable and can_use_user_flag
|
||||
|
||||
self._logger.info("pip installs to {}, --user flag needed => {}, "
|
||||
"virtual env => {}".format(install_dir,
|
||||
"yes" if user_flag else "no",
|
||||
"yes" if virtual_env else "no"))
|
||||
|
||||
# ok, enable user flag, virtual env yes/no, installation dir
|
||||
result = ok, user_flag, virtual_env, install_dir
|
||||
_cache["setup"][pip_command_str] = result
|
||||
return result
|
||||
else:
|
||||
self._logger.debug("Could not detect desired output from testballoon install, got this instead: {!r}".format(data))
|
||||
return False, False, False, None
|
||||
|
||||
data = dict()
|
||||
with open(testballoon_output_file) as f:
|
||||
for line in f:
|
||||
key, value = line.split("=", 2)
|
||||
data[key] = value
|
||||
|
||||
install_dir_str = data.get("PIP_INSTALL_DIR", None)
|
||||
virtual_env_str = data.get("PIP_VIRTUAL_ENV", None)
|
||||
writable_str = data.get("PIP_WRITABLE", None)
|
||||
|
||||
if install_dir_str is not None and virtual_env_str is not None and writable_str is not None:
|
||||
install_dir = install_dir_str.strip()
|
||||
virtual_env = virtual_env_str.strip() == "True"
|
||||
writable = writable_str.strip() == "True"
|
||||
|
||||
can_use_user_flag = not virtual_env and site.ENABLE_USER_SITE
|
||||
|
||||
# ok, enable user flag, virtual env yes/no, installation dir
|
||||
result = writable or can_use_user_flag, \
|
||||
not writable and can_use_user_flag, \
|
||||
virtual_env, \
|
||||
install_dir
|
||||
_cache["setup"][pip_command_str] = result
|
||||
return result
|
||||
else:
|
||||
self._logger.debug("Could not detect desired output from testballoon install, got this instead: {!r}".format(data))
|
||||
return False, False, False, None
|
||||
|
||||
def _preprocess_lines(self, *lines):
|
||||
return map(self._preprocess, lines)
|
||||
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <gina@octoprint.org>"
|
||||
__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 pkg_resources
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
|
||||
def _get_base_from_version_tuple(version_tuple):
|
||||
"""
|
||||
Reduces the version tuple to base version.
|
||||
|
||||
Example::
|
||||
>>> _get_base_from_version_tuple((b"1", b"2", b"5"))
|
||||
('1', '2', '5', '*final')
|
||||
>>> _get_base_from_version_tuple((b"1", b"2", b"15", b"*", b"dev12"))
|
||||
('1', '2', '15', '*final')
|
||||
|
||||
Args:
|
||||
version_tuple (tuple): the version tuple to reduce to the base version
|
||||
|
||||
Returns:
|
||||
(tuple): a version tuple reduced to base version
|
||||
|
||||
"""
|
||||
|
||||
assert len(version_tuple) > 0
|
||||
|
||||
base_version = []
|
||||
for part in version_tuple:
|
||||
if part.startswith("*"):
|
||||
break
|
||||
base_version.append(part)
|
||||
|
||||
if base_version and base_version[-1] != b'*final':
|
||||
base_version.append(b'*final')
|
||||
|
||||
return tuple(base_version)
|
||||
|
||||
|
||||
def parse_version(version_string, base=False):
|
||||
"""
|
||||
Parses the given ``version_string`` using ``pkg_resources.parse_version``
|
||||
|
||||
If ``base`` is ``True``, the version will be reduced to the base version (e.g. ``1.2.0.dev.123`` will be reduced
|
||||
to ``1.2.0``) before returning.
|
||||
|
||||
If a ``-`` is contains in the version string, it and any following parts of the version stirng will be stripped
|
||||
(e.g. ``1.2.0-dev-123`` is turned into ``1.2.0``) to ensure the string is parsable using ``pkg_resources``.
|
||||
|
||||
Parameters:
|
||||
version_string (str, unicode): the version string to parse
|
||||
base (boolean): whether to reduce the version to the base version before returning
|
||||
|
||||
Returns:
|
||||
(tuple or object): the parsed version, as either a tuple or a ``setuptools`` version object, depending on the
|
||||
installed ``setuptools`` version
|
||||
"""
|
||||
|
||||
assert isinstance(version_string, basestring)
|
||||
|
||||
if "-" in version_string:
|
||||
version_string = version_string[:version_string.find("-")]
|
||||
|
||||
try:
|
||||
version = pkg_resources.parse_version(version_string)
|
||||
except:
|
||||
raise ValueError("Invalid version: {!r}".format(version_string))
|
||||
|
||||
# A leading v is common in github release tags and old setuptools doesn't remove it.
|
||||
if version and isinstance(version, tuple) and version[0].lower() == "*v":
|
||||
version = version[1:]
|
||||
|
||||
if base:
|
||||
if isinstance(version, tuple):
|
||||
# old setuptools
|
||||
version = _get_base_from_version_tuple(version)
|
||||
else:
|
||||
# new setuptools
|
||||
version = pkg_resources.parse_version(version.base_version)
|
||||
return version
|
||||
|
||||
|
||||
def version_matches_any_spec(version, specs, package=None, base=False):
|
||||
"""
|
||||
Checks if the supplied version matches any of the supplied specs.
|
||||
|
||||
See `Requirements Parsing <https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing>`_ for
|
||||
details on the format. The version spec does not need to start with ``package``, it will be added automatically
|
||||
if it's missing.
|
||||
|
||||
Example::
|
||||
>>> version_matches_any_spec("1.2.0", ["Foo>=1.1.0,<1.2.0", "Foo>=1.2.0,<1.3.0", "Foo>=1.3.0"])
|
||||
True
|
||||
>>> version_matches_any_spec("1.2.0", ["Foo>=1.1.0,<1.2.0", "Foo>=1.3.0"])
|
||||
False
|
||||
|
||||
Arguments:
|
||||
version (str, unicode, parsed version): version to check
|
||||
specs (list of str or unicode): version specs to check against
|
||||
package (str or unicode): name of the package to use in the spec
|
||||
base (boolean): If True, only check the base version of the version against the spec. Defaults
|
||||
to False.
|
||||
|
||||
Returns:
|
||||
(boolean) True if the version matches any of the version specs, False otherwise.
|
||||
"""
|
||||
|
||||
if isinstance(version, basestring):
|
||||
version = parse_version(version, base=base)
|
||||
|
||||
for spec in specs:
|
||||
if package is not None and not spec.lower().startswith(package.lower()):
|
||||
spec = package.lower() + spec
|
||||
|
||||
try:
|
||||
parsed_spec = next(pkg_resources.parse_requirements(spec))
|
||||
except:
|
||||
raise ValueError("Invalid spec: {!r}".format(spec))
|
||||
|
||||
if version in parsed_spec:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def version_matches_spec(version, spec, package=None, base=False):
|
||||
"""
|
||||
Checks if the supplied version matches the supplied spec.
|
||||
|
||||
See `Requirements Parsing <https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing>`_ for
|
||||
details on the format. The version spec does not need to start with ``package``, it will be added automatically
|
||||
if it's missing.
|
||||
|
||||
Example::
|
||||
>>> version_matches_spec("1.2.0", "Foo>=1.2.0,<1.3.0")
|
||||
True
|
||||
>>> version_matches_spec("1.2.0", "Foo>=1.3.0")
|
||||
False
|
||||
>>> version_matches_spec("1.2.0", ">=1.2.0,<1.3.0", package="Foo")
|
||||
True
|
||||
>>> version_matches_spec("1.2.0.dev.123", ">=1.2.0", package="Foo")
|
||||
False
|
||||
>>> version_matches_spec("1.2.0.dev.123", ">=1.2.0", package="Foo", base=True)
|
||||
True
|
||||
|
||||
Arguments:
|
||||
version (str, unicode, parsed version): version to check
|
||||
spec (str or unicode): version spec to check against
|
||||
package (str or unicode): name of the package to use in the spec
|
||||
base (boolean): If True, only check the base version of the version against the spec. Defaults
|
||||
to False.
|
||||
|
||||
Returns:
|
||||
(boolean) True if the version matches the version spec, False otherwise.
|
||||
"""
|
||||
return version_matches_any_spec(version, [spec], package=package, base=base)
|
||||
|
||||
|
||||
def octoprint_version_matches(spec, base=False):
|
||||
"""
|
||||
Checks if the current OctoPrint version matches the provided spec.
|
||||
|
||||
See `Requirements Parsing <https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing>`_ for
|
||||
details on the format. The version spec does not need to start with "OctoPrint", it will be added automatically
|
||||
if it's missing.
|
||||
|
||||
Example::
|
||||
|
||||
octoprint_version_matches(">=1.2.0")
|
||||
|
||||
octoprint_version_matches("OctoPrint>=1.3.0", base=True)
|
||||
|
||||
Arguments:
|
||||
spec (str or unicode): version spec to check against
|
||||
base (boolean): If True, only check the base version of the OctoPrint version against the spec. Defaults
|
||||
to False.
|
||||
|
||||
Returns:
|
||||
(boolean) True if the version matches the version spec, False otherwise.
|
||||
"""
|
||||
|
||||
from octoprint import __version__
|
||||
return version_matches_any_spec(__version__, [spec], package="OctoPrint", base=base)
|
||||
@@ -480,11 +480,7 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
|
||||
requires = ["OctoPrint"]
|
||||
if not isinstance(requires, list):
|
||||
raise ValueError("requires must be a list")
|
||||
for require in requires:
|
||||
requirement = pkg_resources.Requirement.parse(require)
|
||||
if requirement.key == "octoprint":
|
||||
break
|
||||
else:
|
||||
if "OctoPrint" not in requires:
|
||||
requires = ["OctoPrint"] + list(requires)
|
||||
|
||||
if extra_requires is None:
|
||||
|
||||
@@ -198,12 +198,32 @@ class TestCommHelpers(unittest.TestCase):
|
||||
result = gcode_command_for_cmd(cmd)
|
||||
self.assertEqual(expected, result)
|
||||
|
||||
@data(
|
||||
("G0 X0", "G0", None),
|
||||
("M105", "M105", None),
|
||||
("T2", "T", None),
|
||||
("M80.1", "M80", "1"),
|
||||
("G28.2", "G28", "2"),
|
||||
("T0.3", "T", None),
|
||||
("M80.nosubcode", "M80", None),
|
||||
(None, None, None),
|
||||
("No match", None, None)
|
||||
)
|
||||
@unpack
|
||||
def test_gcode_and_subcode_for_cmd(self, cmd, expected_gcode, expected_subcode):
|
||||
from octoprint.util.comm import gcode_and_subcode_for_cmd
|
||||
actual_gcode, actual_subcode = gcode_and_subcode_for_cmd(cmd)
|
||||
self.assertEqual(expected_gcode, actual_gcode)
|
||||
self.assertEqual(expected_subcode, actual_subcode)
|
||||
|
||||
@data(
|
||||
("T:23.0 B:60.0", 0, dict(T0=(23.0, None), B=(60.0, None)), 0),
|
||||
("T:23.0 B:60.0", 1, dict(T1=(23.0, None), B=(60.0, None)), 1),
|
||||
("T:23.0/220.0 B:60.0/70.0", 0, dict(T0=(23.0, 220.0), B=(60.0, 70.0)), 0),
|
||||
("ok T:23.0/220.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 0, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2),
|
||||
("ok T:50.2/210.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 1, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2)
|
||||
("ok T:50.2/210.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 1, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2),
|
||||
("ok T:-55.7/0 T0:-55.7/0 T1:150.0/210.0", 0, dict(T0=(-55.7, 0), T1=(150.0, 210.0)), 1),
|
||||
("ok T:150.0/210.0 T0:-55.7/0 T1:150.0/210.0", 1, dict(T0=(-55.7, 0), T1=(150.0, 210.0)), 1)
|
||||
)
|
||||
@unpack
|
||||
def test_process_temperature_line(self, line, current, expected_result, expected_max):
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__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 unittest
|
||||
import ddt
|
||||
import mock
|
||||
|
||||
from octoprint.util.version import version_matches_spec, version_matches_any_spec, octoprint_version_matches, parse_version
|
||||
|
||||
|
||||
@ddt.ddt
|
||||
class VersionUtilTest(unittest.TestCase):
|
||||
|
||||
@ddt.data(("1.2.0", "foo>=1.2.0,<1.3.0", None, False, True),
|
||||
("1.2.0", "foo>=1.3.0", None, False, False),
|
||||
("1.2.0-dev-405", "foo>=1.2.0", None, True, True),
|
||||
("1.2.0.dev.405", "foo>=1.2.0", None, False, False),
|
||||
("1.2.0.dev.405", "foo>=1.2.0", None, True, True),
|
||||
("1.2.0", ">=1.2.0,<1.3.0", "foo", False, True),
|
||||
("1.2.0", "FoO>=1.2.0,<1.3.0", "foo", False, True),
|
||||
("1.2.0", ">=1.2.0,<1.3.0", None, False, ValueError),
|
||||
("1.2.fnord", ">=1.2.0", None, False, ValueError)
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_version_matches_spec(self, version, spec, package, base, expected):
|
||||
self.assertExpected(version_matches_spec, (version, spec), dict(package=package, base=base), expected)
|
||||
|
||||
def test_version_matches_any_spec(self):
|
||||
self.assertTrue(version_matches_any_spec("1.2.0", [">=1.1.0,<1.2.0", ">=1.2.0,<1.3.0", "==1.3.0"], package="foo"))
|
||||
|
||||
def test_version_matches_any_spec_nomatch(self):
|
||||
self.assertFalse(version_matches_any_spec("1.2.0", [">=1.1.0,<1.2.0", "==1.3.0"], package="foo"))
|
||||
|
||||
@ddt.data((">=1.2.0,<1.3.0", False, "1.2.0", True),
|
||||
(">=1.2.0,<1.3.0", False, "1.3.0.dev.123", False),
|
||||
(">=1.2.0,<1.3.0", False, "1.2.0.dev.123", False),
|
||||
(">=1.2.0,<1.3.0", True, "1.2.0.dev.123", True))
|
||||
@ddt.unpack
|
||||
def test_octoprint_version_matches(self, spec, base, mocked_version, expected):
|
||||
import octoprint
|
||||
old_version = octoprint.__version__
|
||||
try:
|
||||
octoprint.__version__ = mocked_version
|
||||
self.assertExpected(octoprint_version_matches, (spec,), dict(base=base), expected)
|
||||
finally:
|
||||
octoprint.__version__ = old_version
|
||||
|
||||
@ddt.data(("1.2.0", False, "1.2.0", ("00000001", "00000002", "00000000", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"),
|
||||
("1.2.0-dev-123", False, "1.2.0", ("00000001", "00000002", "00000000", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"),
|
||||
("1.2.0-dev-123", True, "1.2.0", ("00000001", "00000002", "00000000", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"),
|
||||
("1.2.0.dev.123", False, "1.2.0.dev.123", ("00000001", "00000002", "00000000", "*@", "00000123", "*final"), ("00000001", "00000002", "00000000", "*@", "00000123", "*final"), "1.2.0"),
|
||||
("1.2.0.dev.123", True, "1.2.0.dev.123", ("00000001", "00000002", "00000000", "*@", "00000123", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"),
|
||||
("v1.1.0", False, "v1.1.0", ("*v", "00000001", "00000001", "00000000", "*final"), ("00000001", "00000001", "00000000", "*final"), "1.1.0"),
|
||||
("V1.2.0.dev.123", True, "V1.2.0.dev.123", ("*V", "00000001", "00000002", "00000000", "*@", "00000123", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"))
|
||||
@ddt.unpack
|
||||
def test_parse_version(self, version, base, stripped_version, mocked_tuple, expected_tuple, mocked_base_version):
|
||||
mocked_obj = mock.MagicMock()
|
||||
mocked_obj.base_version = mocked_base_version
|
||||
|
||||
# old setuptools return a tuple for parse_version, we simulate that here
|
||||
with mock.patch("pkg_resources.parse_version") as mocked_parse_version:
|
||||
mocked_parse_version.return_value = mocked_tuple
|
||||
|
||||
result = parse_version(version, base=base)
|
||||
self.assertEqual(expected_tuple, result)
|
||||
|
||||
mocked_parse_version.assert_called_with(stripped_version)
|
||||
|
||||
# newer setuptools return a version object, we simulate that here
|
||||
with mock.patch("pkg_resources.parse_version") as mocked_parse_version:
|
||||
mocked_parse_version.return_value = mocked_obj
|
||||
|
||||
result = parse_version(version, base=base)
|
||||
self.assertEqual(mocked_obj, result)
|
||||
|
||||
expected_calls = [mock.call(stripped_version)]
|
||||
if base:
|
||||
expected_calls.append(mock.call(mocked_base_version))
|
||||
|
||||
self.assertListEqual(expected_calls, mocked_parse_version.call_args_list)
|
||||
|
||||
def assertExpected(self, method, args, kwargs, expected):
|
||||
"""
|
||||
Helper for checking the return value against an expected one.
|
||||
|
||||
Maybe an exception class in which case a try-catch-block is created and a test for the correct
|
||||
exception is set up.
|
||||
"""
|
||||
|
||||
if isinstance(expected, type) and issubclass(expected, Exception):
|
||||
try:
|
||||
method(*args, **kwargs)
|
||||
self.fail("Expected {}".format(expected))
|
||||
except Exception as e:
|
||||
if not isinstance(e, expected):
|
||||
self.fail("Expected exception of type {}, got {} instead".format(expected, e.__class__.__name__))
|
||||
else:
|
||||
self.assertEqual(expected, method(*args, **kwargs))
|
||||
Binary file not shown.
+1251
-1760
File diff suppressed because it is too large.
Load diff
+887
-519
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user