Compare commits

..
107 changed files with 2559 additions and 5804 deletions

No files matched your search

+5 -7
View File
@@ -18,14 +18,12 @@ HEAD
# maintenance is currently the branch for preparation of maintenance release 1.3.5
# so are any fix/... and improve/... branches
maintenance 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
fix/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
improve/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
maintenance 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
fix/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
improve/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.5rc4
# so is regressionfix/...
staging/maintenance 1.3.5rc4 679674df2282af0c4500367fa93864c6defa3802 pep440-dev
regressionfix/.* 1.3.5rc4 679674df2282af0c4500367fa93864c6defa3802 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.5rc1
staging/maintenance 1.3.5rc1 fe481e12b3c50a2def3b41515200e13a8c6a5c72 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
-93
View File
@@ -1,98 +1,5 @@
# OctoPrint Changelog
## 1.3.5 (2017-10-16)
### 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.
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for legend in graph not updating with current values on mouse over.
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for new temperature inputs not fitting on one line in Firefox.
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - 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) (regression) - Wizard: Fix sorting of required wizards not properly handling non-ASCII unicode.
* [#2035](https://github.com/foosel/OctoPrint/issues/2035) (regression) - 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.
* [#2059](https://github.com/foosel/OctoPrint/issues/2059) (regression) - Fix an issue causing the new temperature controls to wrap on touch enabled devices when the temperature dropdown is opened.
* [#2090](https://github.com/foosel/OctoPrint/issues/2090) (regression) - Fix an issue causing an aborted server startup under Windows if the timing is just right.
* [#2135](https://github.com/foosel/OctoPrint/issues/2135) (regression) - Fix an issue causing import errors inside the GCODE analysis tool in certain environments due to `sys.path` entries causing relative imports.
* [#2136](https://github.com/foosel/OctoPrint/issues/2136) (regression) - Fix wrong minimum version for `sockjs-tornado` dependency.
* [#2137](https://github.com/foosel/OctoPrint/issues/2137) (regression) - Fix issue with session cookies getting lost when running an OctoPrint instance on a subpath of another (e.g. `octopi.local/` and `octopi.local/octoprint2`).
* [#2140](https://github.com/foosel/OctoPrint/issues/2140) (regression) - Fix issue with locale dependent sorting of sub wizards during first time setup causing issues leading to the wizard not being able to complete.
* 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.
* Wizard: Fix `onWizardPreventSettingsRefreshDialog` callback invocation. (regression)
* 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. (regression)
* Fix an issue causing rollover of `serial.log` to fail under Windows. (regression)
### More Information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.4...1.3.5)
* Release Candidates:
* [1.3.5rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc1)
* [1.3.5rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc2)
* [1.3.5rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc3)
* [1.3.5rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc4)
* A special **Thank you!** to everyone who reported back on these release candidates this time: [alexxy](https://github.com/alexxy), [andrivet](https://github.com/andrivet), [b-morgan](https://github.com/b-morgan), [BillyBlaze](https://github.com/BillyBlaze), [CapnBry](https://github.com/CapnBry), [chippypilot](https://github.com/chippypilot), [ctgreybeard](https://github.com/ctgreybeard), [cxt666](https://github.com/cxt666), [DaSTIG](https://github.com/DaSTIG), [fhbmax](https://github.com/fhbmax), [fiveangle](https://github.com/fiveangle), [goeland86](https://github.com/goeland86), [JohnOCFII](https://github.com/JohnOCFII), [Kunsi](https://github.com/Kunsi), [mgrl](https://github.com/mgrl), [MoonshineSG](https://github.com/MoonshineSG), [nate-ubiquisoft](https://github.com/nate-ubiquisoft), [Neoolog](https://github.com/Neoolog), [ntoff](https://github.com/ntoff), [oferfrid](https://github.com/oferfrid), [roygilby](https://github.com/roygilby), [SAinc](https://github.com/SAinc), [sbts](https://github.com/sbts), [thess](https://github.com/thess), [tkurbad](https://github.com/tkurbad), [tsillini](https://github.com/tsillini) and [TylonHH](https://github.com/TylonHH).
## 1.3.4 (2017-06-01)
### Note for owners of Malyan M200/Monoprice Select Mini
+7 -6
View File
@@ -14,29 +14,30 @@ 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
* Kale Stedman
* Kazuhiro Ogura
* Lamin Kivelä
* Makespace Madrid
* Marcus Ackermann
* Mark Qvist
@@ -44,7 +45,6 @@ thanks to everyone who contributed!
* Masayoshi Mitsui
* Michael Aumock
* Miles Flavel
* mitchell hirsch
* Mohammed khorakiwala
* Noe Ruiz
* Patrick McGinnis
@@ -55,13 +55,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 1133 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1098 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
-7
View File
@@ -198,13 +198,6 @@ 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:
+1 -1
View File
@@ -33,7 +33,7 @@ needs_sphinx = '1.3'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain',
'sphinx.ext.napoleon', 'sphinxcontrib.mermaid']
'sphinx.ext.napoleon']
todo_include_todos = True
# Add any paths that contain templates here, relative to this directory.
-14
View File
@@ -909,20 +909,6 @@ 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:
-8
View File
@@ -110,14 +110,6 @@ 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
---------------------
-6
View File
@@ -87,9 +87,6 @@ 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.
@@ -97,9 +94,6 @@ 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.
-1
View File
@@ -14,5 +14,4 @@ Internal Modules
server.rst
settings.rst
slicing.rst
users.rst
util.rst
-9
View File
@@ -1,9 +0,0 @@
.. _sec-modules-users:
octoprint.users
---------------
.. automodule:: octoprint.users
:members:
+9 -49
View File
@@ -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, subcode=None, *args, **kwargs)
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, *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 and equivalent:
examples are all falling into this category:
.. code-block:: python
@@ -451,24 +451,21 @@ 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.
* **"queuing" phase only**: A list of any of the above to allow for expanding one command into
* 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"), # 2-tuple, command & command type
("M110",), # 1-tuple, just the command
"M117 echo foo: {}".format(cmd)] # string, just the command
return [("M105", "temperature_poll"),
("M110",),
"M117 echo foo: {}".format(cmd)]
__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.
@@ -491,8 +488,6 @@ 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:
@@ -946,38 +941,3 @@ 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
-2
View File
@@ -45,8 +45,6 @@ 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::
-124
View File
@@ -299,130 +299,6 @@ on your view model, taking a list of all bound view models:
});
})
.. _sec-plugins-viewmodels-livecycle:
Lifecycle diagrams
------------------
.. _sec-plugins-viewmodels-startup:
Web interface startup
~~~~~~~~~~~~~~~~~~~~~
.. mermaid::
sequenceDiagram
participant Main
participant onServerConnect
participant fetchSettings
participant bindViewModels
participant DataUpdater
participant LoginStateViewModel
Note right of DataUpdater: connectCallback = undefined
activate Main
Main->>+DataUpdater: connect
Note right of DataUpdater: initialized = false
DataUpdater-->>Main: ok
deactivate Main
DataUpdater->>DataUpdater: asynchronous connect to server...
activate DataUpdater
Note right of DataUpdater: store any callbacks instead of triggering (e.g. onServerConnect, fromHistoryData, fromCurrentData, ...)
DataUpdater-X+Main: done
deactivate DataUpdater
deactivate DataUpdater
Main->>+DataUpdater: connectCallback = onServerConnect
Note right of DataUpdater: connectCallback = onServerConnect
DataUpdater-->>-Main: ok
Main->>+onServerConnect: call
onServerConnect->>+LoginStateViewModel: passiveLogin
LoginStateViewModel-->>onServerConnect: ok
onServerConnect-->>Main: ok
deactivate onServerConnect
deactivate Main
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
Note over Main,LoginStateViewModel: Session available!
LoginStateViewModel-X+onServerConnect: done
deactivate LoginStateViewModel
deactivate LoginStateViewModel
onServerConnect->>+DataUpdater: initialized
Note right of DataUpdater: initialized = true
DataUpdater->DataUpdater: trigger stored callbacks
DataUpdater-->>-onServerConnect: ok
onServerConnect-X+Main: done
deactivate onServerConnect
Main->>+fetchSettings: call
Note right of fetchSettings: trigger onStartup
fetchSettings-->>Main: ok
deactivate Main
fetchSettings->>+fetchSettings: asynchronous settings fetch
fetchSettings->>+bindViewModels: call
loop for each view model
bindViewModels->bindViewModels: trigger onBeforeBinding
bindViewModels->bindViewModels: trigger onBoundTo
bindViewModels->bindViewModels: trigger onAfterBinding
end
bindViewModels->bindViewModels: trigger onAllBound
opt User is logged in
bindViewModels->>+LoginStateViewModel: onAllBound
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
LoginStateViewModel-->>-bindViewModels: ok
end
bindViewModels->bindViewModels: trigger onStartupComplete
bindViewModels-->>-fetchSettings: ok
deactivate fetchSettings
deactivate fetchSettings
.. _sec-plugins-viewmodels-reconnect:
Web interface reconnect
~~~~~~~~~~~~~~~~~~~~~~~
.. mermaid::
sequenceDiagram
participant onServerConnect
participant DataUpdater
participant LoginStateViewModel
activate DataUpdater
DataUpdater->>DataUpdater: call connectCallback
DataUpdater->>+onServerConnect: call
onServerConnect-->>DataUpdater: ok
deactivate DataUpdater
onServerConnect->>+LoginStateViewModel: passiveLogin
LoginStateViewModel-->>onServerConnect: ok
deactivate onServerConnect
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
Note over onServerConnect,LoginStateViewModel: Session available!
opt User is logged in
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
end
activate onServerConnect
LoginStateViewModel-XonServerConnect: done
deactivate LoginStateViewModel
deactivate LoginStateViewModel
onServerConnect->>+DataUpdater: initialized
DataUpdater->DataUpdater: trigger stored callbacks
DataUpdater-->>onServerConnect: ok
deactivate DataUpdater
deactivate onServerConnect
.. seealso::
`OctoPrint's core viewmodels <https://github.com/foosel/OctoPrint/tree/devel/src/octoprint/static/js/app/viewmodels>`_
+27 -85
View File
@@ -7,99 +7,41 @@ __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the
import codecs
import requests
from contextlib import closing
import urllib2
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
nodes, set_source_info, parselinenos, logger, container_wrapper
if False:
# For type annotation
from typing import Any, List # NOQA
from sphinx.directives import LiteralInclude, dedent_lines
cache = dict()
class OnlineIncludeReader(LiteralIncludeReader):
def read_file(self, filename, location=None):
# type: (unicode, Any) -> List[unicode]
global cache
try:
if filename in cache:
lines = cache[filename]
else:
with closing(requests.get(filename, stream=True)) as r:
r.encoding = self.encoding
lines = r.text.splitlines(True)
cache[filename] = lines
if 'tab-width' in self.options:
lines = [line.expandtabs(self.options['tab-width']) for line in lines]
return lines
except (IOError, OSError):
raise IOError(_('Include file %r not found or reading it failed') % filename)
except UnicodeError:
raise UnicodeError(_('Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option') %
(self.encoding, filename))
class OnlineIncludeDirective(LiteralInclude):
def run(self):
# type: () -> List[nodes.Node]
document = self.state.document
if not document.settings.file_insertion_enabled:
return [document.reporter.warning('File insertion disabled',
line=self.lineno)]
env = document.settings.env
# convert options['diff'] to absolute path
if 'diff' in self.options:
_, path = env.relfn2path(self.options['diff'])
self.options['diff'] = path
def read_with_encoding(self, filename, document, codec_info, encoding):
global cache
f = None
try:
location = self.state_machine.get_source_and_line(self.lineno)
url = self.arguments[0]
reader = OnlineIncludeReader(url, self.options, env.config)
text, lines = reader.read(location=location)
retnode = nodes.literal_block(text, text, source=url)
set_source_info(self, retnode)
if self.options.get('diff'): # if diff is set, set udiff
retnode['language'] = 'udiff'
elif 'language' in self.options:
retnode['language'] = self.options['language']
retnode['linenos'] = ('linenos' in self.options or
'lineno-start' in self.options or
'lineno-match' in self.options)
retnode['classes'] += self.options.get('class', [])
extra_args = retnode['highlight_args'] = {}
if 'emphasize-lines' in self.options:
hl_lines = parselinenos(self.options['emphasize-lines'], lines)
if any(i >= lines for i in hl_lines):
logger.warning('line number spec is out of range(1-%d): %r' %
(lines, self.options['emphasize-lines']),
location=location)
extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
extra_args['linenostart'] = reader.lineno_start
if 'caption' in self.options:
caption = self.options['caption'] or self.arguments[0]
retnode = container_wrapper(self, retnode, caption)
# retnode will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
self.add_name(retnode)
return [retnode]
except Exception as exc:
return [document.reporter.warning(str(exc), line=self.lineno)]
if not self.arguments[0] in cache:
f = codecs.StreamReaderWriter(urllib2.urlopen(self.arguments[0]), codec_info[2],
codec_info[3], 'strict')
lines = f.readlines()
cache[self.arguments[0]] = lines
else:
lines = cache[self.arguments[0]]
lines = dedent_lines(lines, self.options.get('dedent'))
return lines
except (IOError, OSError, urllib2.URLError):
return [document.reporter.warning(
'Include file %r not found or reading it failed' % self.arguments[0],
line=self.lineno)]
except UnicodeError:
return [document.reporter.warning(
'Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option' %
(encoding, self.arguments[0]))]
finally:
if f is not None:
f.close()
def visit_onlineinclude(translator, node):
translator.visit_literal_block(node)
@@ -111,4 +53,4 @@ def setup(app):
app.add_directive("onlineinclude", OnlineIncludeDirective)
handler = (visit_onlineinclude, depart_onlineinclude)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
+4 -6
View File
@@ -23,7 +23,7 @@ INSTALL_REQUIRES = [
# to some voodoo needed to get large streamed uploads and downloads
# to work that is probably not completely straightforward and therefore
# something for post-1.3.0-stable release
"sockjs-tornado>=1.0.3,<1.1",
"sockjs-tornado>=1.0.2,<1.1",
"PyYAML>=3.10,<3.11",
"Flask-Login>=0.2.2,<0.3",
"Flask-Principal>=0.3.5,<0.4",
@@ -49,8 +49,7 @@ 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",
"futures>=3.1.1,<3.2"
"wrapt>=1.10.10,<1.11"
]
if sys.platform == "darwin":
@@ -66,10 +65,9 @@ EXTRA_REQUIRES = dict(
"ddt",
# Documentation dependencies
"sphinx>=1.6,<1.7",
"sphinx>=1.3,<1.4",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid",
"sphinx_bootstrap_theme",
"sphinx_rtd_theme",
# PyPi upload related
"pypandoc"
+1 -2
View File
@@ -194,8 +194,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
"level": "DEBUG",
"formatter": "serial",
"backupCount": 3,
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log"),
"delay": True
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log")
}
},
"loggers": {
-7
View File
@@ -1,7 +0,0 @@
#!/usr/bin/env python2
# coding=utf-8
from __future__ import absolute_import, division, print_function
if __name__ == "__main__":
import octoprint
octoprint.main()
+1 -2
View File
@@ -135,10 +135,9 @@ from .plugins import plugin_commands
from .dev import dev_commands
from .client import client_commands
from .config import config_commands
from .analysis import analysis_commands
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands])
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands])
@standard_options()
@legacy_options
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
-73
View File
@@ -1,73 +0,0 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
#~~ "octoprint util" commands
@click.group()
def analysis_commands():
pass
@analysis_commands.group(name="analysis")
def util():
"""Analysis tools."""
pass
@util.command(name="gcode")
@click.option("--throttle", "throttle", type=float, default=None)
@click.option("--throttle-lines", "throttle_lines", type=int, default=None)
@click.option("--speed-x", "speedx", type=float, default=6000)
@click.option("--speed-y", "speedy", type=float, default=6000)
@click.option("--speed-z", "speedz", type=float, default=300)
@click.option("--offset", "offset", type=(float, float), multiple=True)
@click.option("--max-t", "maxt", type=int, default=10)
@click.option("--g90-extruder", "g90_extruder", is_flag=True)
@click.option("--progress", "progress", is_flag=True)
@click.argument("path", type=click.Path())
def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress):
"""Runs a GCODE file analysis."""
import time
import yaml
from octoprint.util.gcodeInterpreter import gcode
throttle_callback = None
if throttle:
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every $throttle_lines lines
time.sleep(throttle)
offsets = offset
if offsets is None:
offsets = []
elif isinstance(offset, tuple):
offsets = list(offsets)
offsets = [(0, 0)] + offsets
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
start_time = time.time()
progress_callback = None
if progress:
def progress_callback(percentage):
click.echo("PROGRESS:{}".format(percentage))
interpreter = gcode(progress_callback=progress_callback)
interpreter.load(path,
speedx=speedx,
speedy=speedy,
offsets=offsets,
throttle=throttle_callback,
max_extruders=maxt,
g90_extruder=g90_extruder)
click.echo("DONE:{}s".format(time.time() - start_time))
click.echo("RESULTS:")
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
+24 -47
View File
@@ -9,7 +9,7 @@ import json
import octoprint_client
from octoprint.cli import get_ctx_obj_option, bulk_options
from octoprint.cli import get_ctx_obj_option
from octoprint import init_settings, FatalStartupError
@@ -23,66 +23,43 @@ 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))
@client_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)
@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))
ctx.obj.client = create_client(settings=settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
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)
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)
+2 -4
View File
@@ -60,8 +60,6 @@ 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):
@@ -90,14 +88,14 @@ class OctoPrintPluginCommands(click.MultiCommand):
continue
result[name + self.sep + command.name] = command
except:
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name))
self._logger.exception("Error while retrieving cli commants for plugin {}".format(name))
return result
@click.group()
@pass_octoprint_ctx
def plugin_commands(obj):
pass
logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN)
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
def plugins():
+8 -35
View File
@@ -27,10 +27,9 @@ def all_events():
class Events(object):
# server
# application startup
STARTUP = "Startup"
SHUTDOWN = "Shutdown"
CONNECTIVITY_CHANGED = "ConnectivityChanged"
# connect/disconnect to printer
CONNECTING = "Connecting"
@@ -54,10 +53,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"
@@ -132,11 +131,9 @@ class EventManager(object):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._startup_signaled = False
self._shutdown_signaled = False
self._queue = queue.Queue()
self._held_back = queue.Queue()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
@@ -163,8 +160,7 @@ class EventManager(object):
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
"on_event",
args=(event, payload),
initialized=True)
args=(event, payload))
self._logger.info("Event loop shut down")
except:
self._logger.exception("Ooops, the event bus worker loop crashed")
@@ -180,30 +176,7 @@ class EventManager(object):
payload being a payload object specific to the event.
"""
send_held_back = False
if event == Events.STARTUP:
self._logger.info("Processing startup event, this is our first event")
self._startup_signaled = True
send_held_back = True
self._enqueue(event, payload)
if send_held_back:
self._logger.info("Adding {} events to queue that "
"were held back before startup event".format(self._held_back.qsize()))
while True:
try:
self._queue.put(self._held_back.get(block=False))
except queue.Empty:
break
def _enqueue(self, event, payload):
if self._startup_signaled:
q = self._queue
else:
q = self._held_back
q.put((event, payload))
self._queue.put((event, payload))
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
@@ -211,7 +184,7 @@ class EventManager(object):
import copy
legacy_payload = copy.deepcopy(payload)
legacy_payload["type"] = "gcode"
q.put((event, legacy_payload))
self._queue.put((event, legacy_payload))
def subscribe(self, event, callback):
"""
+1 -24
View File
@@ -180,12 +180,9 @@ class FileManager(object):
import octoprint.settings
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
def initialize(self, process_backlog=False):
def initialize(self):
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():
@@ -256,26 +253,6 @@ 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)
+3 -3
View File
@@ -324,12 +324,12 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
speedy = self._current.printer_profile["axes"]["y"]["speed"]
offsets = self._current.printer_profile["extruder"]["offsets"]
command = [sys.executable, "-m", "octoprint", "analysis", "gcode",
"--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
interpreter = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "util", "gcodeInterpreter.py"))
command = [sys.executable, interpreter, "--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines)]
for offset in offsets[1:]:
command += ["--offset", str(offset[0]), str(offset[1])]
command += ["--offset", offset[0], offset[1]]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
-13
View File
@@ -135,16 +135,3 @@ 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:]))
+7 -22
View File
@@ -177,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, initialized=True):
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None):
"""
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
@@ -213,8 +213,6 @@ 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.
"""
@@ -227,9 +225,6 @@ 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)
@@ -269,17 +264,13 @@ class PluginSettings(object):
:returns: The retrieved settings value.
:rtype: object
.. method:: get_int(path, min=None, max=None)
.. method:: get_int(path)
Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
the value is greater than it.
Like :func:`get` but tries to convert the retrieved value to ``int``.
.. method:: get_float(path, min=None, max=None)
.. method:: get_float(path)
Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
the value is greater than it.
Like :func:`get` but tries to convert the retrieved value to ``float``.
.. method:: get_boolean(path)
@@ -295,19 +286,13 @@ class PluginSettings(object):
:param boolean force: If set to True, the modified configuration will even be written back to disk if
the value didn't change.
.. method:: set_int(path, value, force=False, min=None, max=None)
.. method:: set_int(path, value, force=False)
Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it.
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
that, ``max`` if greater than that) will be set instead.
.. method:: set_float(path, value, force=False, min=None, max=None)
.. method:: set_float(path, value, force=False)
Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it.
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
that, ``max`` if greater than that) will be set instead.
.. method:: set_boolean(path, value, force=False)
@@ -28,8 +28,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.EventHandlerPlugin):
octoprint.plugin.TemplatePlugin):
def __init__(self):
self._cached_channel_configs = None
@@ -211,14 +210,6 @@ 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):
@@ -275,11 +266,6 @@ 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."""
@@ -312,10 +298,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
if data is None:
# cache not allowed or empty, fetch from network
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))
data = self._get_channel_data_from_network(key, config)
return data
@@ -40,7 +40,7 @@ $(function() {
};
self.toggleButtonCss = function(data) {
var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off";
var icon = data.enabled ? "fa fa-circle" : "fa fa-circle-o";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
@@ -317,13 +317,7 @@ $(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
+3 -54
View File
@@ -25,13 +25,6 @@ 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():
@@ -44,11 +37,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
if not name:
continue
config = dict(type="wizard",
name=name,
template="corewizard_{}_wizard.jinja2".format(key),
div="wizard_plugin_corewizard_{}".format(key),
suffix="_{}".format(key))
config = dict(type="wizard", name=name, template="corewizard_{}_wizard.jinja2".format(key), div="wizard_plugin_corewizard_{}".format(key))
if key in additional:
additional_result = additional[key]()
if additional_result:
@@ -70,16 +59,8 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
#~~ WizardPlugin API
def is_wizard_required(self):
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
methods = self._get_subwizard_attrs("_is_", "_wizard_required")
return self._settings.global_get(["server", "firstRun"]) and any(map(lambda m: m(), methods.values()))
def get_wizard_details(self):
result = dict()
@@ -90,14 +71,8 @@ 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()
@@ -139,9 +114,6 @@ 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"])
@@ -157,9 +129,6 @@ 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"])
@@ -173,28 +142,8 @@ 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,88 +125,6 @@ $(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;
@@ -254,10 +172,6 @@ $(function() {
CoreWizardServerCommandsViewModel,
["settingsViewModel"],
"#wizard_plugin_corewizard_servercommands"
], [
CoreWizardOnlineCheckViewModel,
["settingsViewModel"],
"#wizard_plugin_corewizard_onlinecheck"
], [
CoreWizardPrinterProfileViewModel,
["printerProfilesViewModel"],
@@ -1,46 +0,0 @@
<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>
+10 -35
View File
@@ -36,8 +36,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.EventHandlerPlugin):
octoprint.plugin.BlueprintPlugin):
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
@@ -101,7 +100,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._console_logger.propagate = False
# decouple repository fetching from server startup
self._fetch_all_data(async=True)
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()
##~~ SettingsPlugin
@@ -192,14 +197,6 @@ 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):
@@ -242,8 +239,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
additional_args=self._settings.get(["pip_args"]),
python=sys.executable
),
safe_mode=safe_mode,
online=self._connectivity_checker.online)
safe_mode=safe_mode)
def etag():
import hashlib
@@ -254,7 +250,6 @@ 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():
@@ -684,18 +679,6 @@ 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):
@@ -713,10 +696,6 @@ 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)
@@ -779,17 +758,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
import json
with open(self._notices_cache_path) as f:
notice_data = json.load(f)
self._logger.info("Loaded notice data from disk, was still valid")
self._logger.info("Loaded notices 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)
@@ -174,7 +174,6 @@ $(function() {
self.pipPython = ko.observable();
self.safeMode = ko.observable();
self.online = ko.observable();
self.pipUseUserString = ko.pureComputed(function() {
return self.pipUseUser() ? "yes" : "no";
@@ -235,7 +234,7 @@ $(function() {
};
self.enableRepoInstall = function(data) {
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && self.isCompatible(data);
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data);
};
self.invalidUrl = ko.pureComputed(function() {
@@ -245,7 +244,7 @@ $(function() {
self.enableUrlInstall = ko.pureComputed(function() {
var url = self.installUrl();
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && url !== undefined && url.trim() != "" && !self.invalidUrl();
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl();
});
self.invalidArchive = ko.pureComputed(function() {
@@ -322,7 +321,6 @@ $(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) {
@@ -816,7 +814,7 @@ $(function() {
};
self.toggleButtonCss = function(data) {
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on";
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-circle-o" : "fa fa-circle";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
@@ -1022,10 +1020,6 @@ $(function() {
self._closeAllNotifications();
};
self.onEventConnectivityChanged = function(payload) {
self.requestData({eval_notices: true});
};
self._closeAllNotifications = function() {
if (self.notifications) {
_.each(self.notifications, function(notification) {
@@ -20,13 +20,6 @@
{% 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() }}
@@ -131,7 +124,6 @@
{{ 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">
+58 -128
View File
@@ -15,9 +15,6 @@ import time
import logging
import logging.handlers
import hashlib
import traceback
from concurrent import futures
from . import version_checks, updaters, exceptions, util, cli
@@ -37,8 +34,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.EventHandlerPlugin):
octoprint.plugin.WizardPlugin):
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
@@ -48,9 +44,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._configured_checks = None
self._refresh_configured_checks = False
self._get_versions_mutex = threading.RLock()
self._get_versions_data = None
self._get_versions_data_ready = threading.Event()
self._get_versions_mutex = threading.Lock()
self._version_cache = dict()
self._version_cache_ttl = 0
@@ -473,6 +467,15 @@ 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))
@@ -499,11 +502,9 @@ 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():
@@ -565,17 +566,6 @@ 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):
@@ -595,91 +585,53 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
information = dict()
# we don't want to do the same work twice, so let's use a lock
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"))
with self._get_versions_mutex:
for target, check in checks.items():
if not target in check_targets:
continue
with futures.ThreadPoolExecutor(max_workers=5) as executor:
for target, check in checks.items():
if not target in check_targets:
continue
if not check:
continue
if not check:
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
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
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), target_information)
for future in futures.as_completed(futures_to_result):
update_available = update_available or target_update_available
update_possible = update_possible or (target_update_possible and target_update_available)
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
local_name = target_information["local"]["name"]
local_value = target_information["local"]["value"]
target_information, target_update_available, target_update_possible, target_online, target_error = future.result()
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 = dict_merge(dict(local=dict(name="?", value="?"),
remote=dict(name="?", value="?",
release_notes=None),
needs_online=True), target_information)
if release_notes:
release_notes = release_notes.format(octoprint_version=VERSION,
target_name=target_information["remote"]["name"],
target_version=target_information["remote"]["value"])
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
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)
if self._version_cache_dirty:
self._save_version_cache()
return information, update_available, update_possible
def _get_check_hash(self, check):
@@ -698,50 +650,36 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
hash.update(dict_to_sorted_repr(check))
return hash.hexdigest()
def _get_current_version(self, target, check, force=False, online=None):
def _get_current_version(self, target, check, force=False):
"""
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"] \
and data.get("online", None) == online:
if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]:
# we also check that timestamp < now to not get confused too much by clock changes
return data["information"], data["available"], data["possible"], data["online"], data.get("error", None)
return data["information"], data["available"], data["possible"]
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, online=online)
information, is_current = version_checker.get_latest(target, check)
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, online=online)
update_possible = updater.can_perform_update(target, check)
except:
update_possible = False
@@ -749,11 +687,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
hash=current_hash,
information=information,
available=update_available,
possible=update_possible,
online=online,
error=error)
possible=update_possible)
self._version_cache_dirty = True
return information, update_available, update_possible, online, error
return information, update_available, update_possible
def perform_updates(self, check_targets=None, force=False):
"""
@@ -865,9 +801,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._send_client_message("success", dict(results=target_results))
def _perform_update(self, target, check, force):
online = self._connectivity_checker.online
information, update_available, update_possible, _, _ = self._get_current_version(target, check, online=online)
information, update_available, update_possible = self._get_current_version(target, check)
if not update_available and not force:
return False, None
@@ -890,7 +824,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, online=online)
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log)
target_result = ("success", update_result)
self._logger.info("Update of %s to %s successful!" % (target, target_version))
@@ -899,10 +833,6 @@ 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 -31
View File
@@ -9,14 +9,12 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
import click
import sys
import requests.exceptions
from octoprint.cli.client import create_client, client_options
import octoprint_client as client
@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, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets):
def check_command(force, targets):
"""
Check for updates.
@@ -39,15 +37,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
if targets:
params["check"] = ",".join(targets)
client = create_client(settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
client.init_client(cli_group.settings)
r = client.get("plugin/softwareupdate/check", params=params)
try:
r.raise_for_status()
@@ -68,15 +58,10 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
status_text = "Update available"
else:
status_text = "Update available (manual)"
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)
line = "{}\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
info["information"]["local"]["name"],
info["information"]["remote"]["name"],
status_text)
if key == "octoprint":
octoprint_line = line
else:
@@ -98,9 +83,8 @@ 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, apikey, host, port, httpuser, httppass, https, prefix, targets):
def update_command(force, targets):
"""
Apply updates.
@@ -124,13 +108,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
if targets:
data["check"] = targets
client = create_client(apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
client.init_client(cli_group.settings)
flags = dict(
waiting_for_restart=False,
@@ -18,20 +18,6 @@ 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
@@ -49,8 +35,3 @@ 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}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}
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}
@@ -417,42 +417,6 @@ $(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;
@@ -643,11 +607,6 @@ $(function() {
return true;
};
self.onEventConnectivityChanged = function(payload) {
if (!payload || !payload.new) return;
self.performCheck();
};
self.onDataUpdaterReconnect = function() {
if (self.waitingForRestart) {
self.waitingForRestart = false;
@@ -2,12 +2,6 @@ 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,12 +29,11 @@
<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" 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>
<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>
<small class="muted">
<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>
{{ _('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>
</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, online=True):
def can_perform_update(target, check):
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 and (online or check.get("offline", False))
return "pip" in check and pip_caller is not None and pip_caller.available
def _get_pip_caller(command=None):
key = command
@@ -35,14 +35,11 @@ def _get_pip_caller(command=None):
return _pip_callers[key]
def perform_update(target, check, target_version, log_cb=None, online=True):
def perform_update(target, check, target_version, log_cb=None):
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,24 +6,9 @@ __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, 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 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 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
def perform_update(target, check, target_version, log_cb=None):
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb)
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import sys
import logging
from ..exceptions import ConfigurationInvalid, UpdateError, CannotUpdateOffline
from ..exceptions import ConfigurationInvalid, UpdateError
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, online=True):
def can_perform_update(target, check):
import os
script_configured = bool("update_script" in check and check["update_script"])
@@ -47,15 +47,12 @@ def can_perform_update(target, check, online=True):
folder = check["checkout_folder"]
folder_configured = bool(folder and os.path.isdir(folder))
return script_configured and folder_configured and (online or check.get("offline", False))
return script_configured and folder_configured
def perform_update(target, check, target_version, log_cb=None, online=True):
def perform_update(target, check, target_version, log_cb=None):
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,26 +6,15 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
import requests
import logging
import base64
from ..exceptions import ConfigurationInvalid
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, 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)
def _get_latest_commit(user, repo, branch):
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch))
if not r.status_code == requests.codes.ok:
return None
@@ -37,33 +26,24 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
return reference["hash"]
def get_latest(target, check, online=True):
from ..exceptions import ConfigurationInvalid
def get_latest(target, check):
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 and check["branch"] is not None:
if "branch" in check:
branch = check["branch"]
api_user = check.get("api_user")
api_password = check.get("api_password")
current = None
if "current" in check:
current = check["current"]
current = check.get("current")
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
information = dict(
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
remote=dict(name="?", value="?"),
needs_online=not check.get("offline", False)
remote=dict(name="Commit {commit}".format(commit=remote_commit if remote_commit is not None else "unknown"), value=remote_commit)
)
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,17 +8,14 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
from ..exceptions import ConfigurationInvalid, CannotCheckOffline
from ..exceptions import ConfigurationInvalid
from ..util import execute
def get_latest(target, check, online=True):
def get_latest(target, check):
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,40 +47,38 @@ def _git(args, cwd, hide_stderr=False):
return p.returncode, stdout
def get_latest(target, check, online=True):
def get_latest(target, check):
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 information, True
return None, True
returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
if returncode != 0:
return information, True
return None, True
if local_commit == remote_commit or remote_commit == base:
information["remote"] = dict(name="Commit %s" % local_commit, value=local_commit)
information = dict(
local=dict(name="Commit %s" % local_commit, value=local_commit),
remote=dict(name="Commit %s" % local_commit, value=local_commit)
)
is_current = True
else:
information["remote"] = dict(name="Commit %s" % remote_commit, value=remote_commit)
information = dict(
local=dict(name="Commit %s" % local_commit, value=local_commit),
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,17 +8,14 @@ __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):
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)
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=30)
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
@@ -33,9 +30,7 @@ def _get_latest_commit(user, repo, branch):
return reference["object"]["sha"]
def get_latest(target, check, online=True):
from ..exceptions import ConfigurationInvalid
def get_latest(target, check):
user = check.get("user")
repo = check.get("repo")
@@ -46,18 +41,16 @@ def get_latest(target, check, online=True):
if "branch" in check and check["branch"] is not None:
branch = check["branch"]
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
current = None
if "current" in check:
current = check["current"]
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["remote"] = dict(name=remote_name, value=remote_commit)
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)
)
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))
@@ -96,14 +96,8 @@ def _get_latest_release(user, repo, compare_type,
include_prerelease=False,
commitish=None,
force_base=True):
from ..exceptions import NetworkError
nothing = None, None, None
try:
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=30)
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
@@ -264,7 +258,7 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
return True
def get_latest(target, check, custom_compare=None, online=True):
def get_latest(target, check, custom_compare=None):
from ..exceptions import ConfigurationInvalid
user = check.get("user", None)
@@ -273,14 +267,6 @@ def get_latest(target, check, custom_compare=None, online=True):
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)
@@ -304,13 +290,10 @@ def get_latest(target, check, custom_compare=None, online=True):
commitish=commitish,
force_base=force_base)
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)
information =dict(
local=dict(name=current, value=current),
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,24 +5,11 @@ __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, CannotCheckOffline
from ..exceptions import ConfigurationInvalid
def get_latest(target, check, full_data=False, online=True):
def get_latest(target, check, full_data=False):
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))
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
return check["python_checker"].get_latest(target, check, full_data=full_data)
@@ -65,9 +65,6 @@ 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)
@@ -1004,10 +1001,6 @@ 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])
+1 -1
View File
@@ -199,7 +199,7 @@ class PrinterInterface(object):
def set_temperature_offset(self, offsets=None):
"""
Sets the temperature ``offsets`` to apply to target temperatures read from a GCODE file while printing.
Sets the temperature ``offsets`` to apply to target temperatures red from a GCODE file while printing.
Arguments:
offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater``
+15 -36
View File
@@ -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 progress == 0 or printTime is None or cleanedPrintTime is None:
if progress is None or printTime is None or cleanedPrintTime is None:
return None, None
dumbTotalPrintTime = printTime / progress
@@ -1000,17 +1000,7 @@ 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:
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._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"])
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
@@ -1101,18 +1091,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
context=dict(event=payload),
must_be_set=False)
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()
self._fileManager.log_print(payload["origin"],
payload["path"],
time.time(),
payload["time"],
True,
self._printerProfileManager.get_current_or_default()["id"])
else:
self._updateProgressData()
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
@@ -1135,18 +1119,13 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
context=dict(event=payload),
must_be_set=False)
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()
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 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)
+19 -137
View File
@@ -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, 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 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.ext.babel import Babel, gettext, ngettext
from flask.ext.assets import Environment, Bundle
from babel import Locale
@@ -27,11 +27,6 @@ import atexit
import signal
import base64
try:
import fcntl
except ImportError:
fcntl = None
SUCCESS = {}
NO_CONTENT = ("", 204)
NOT_MODIFIED = ("Not Modified", 304)
@@ -54,7 +49,6 @@ pluginManager = None
appSessionManager = None
pluginLifecycleManager = None
preemptiveCache = None
connectivityChecker = None
principals = Principal(app)
admin_permission = Permission(RoleNeed("admin"))
@@ -102,29 +96,6 @@ 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()
@@ -189,7 +160,6 @@ class Server(object):
global appSessionManager
global pluginLifecycleManager
global preemptiveCache
global connectivityChecker
global debug
global safe_mode
@@ -219,16 +189,6 @@ class Server(object):
# start the intermediary server
self._start_intermediary_server()
### IMPORTANT!
###
### Best do not start any subprocesses until the intermediary server shuts down again or they MIGHT inherit the
### open port and prevent us from firing up Tornado later.
###
### The intermediary server's socket should have the CLOSE_EXEC flag (or its equivalent) set where possible, but
### we can only do that if fcntl is availabel or we are on Windows, so better safe than sorry.
###
### See also issues #2035 and #2090
# then initialize the plugin manager
pluginManager.reload_plugins(startup=True, initialize_implementations=False)
@@ -245,40 +205,6 @@ 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:
@@ -299,33 +225,10 @@ class Server(object):
file_manager=fileManager,
app_session_manager=appSessionManager,
plugin_lifecycle_manager=pluginLifecycleManager,
preemptive_cache=preemptiveCache,
connectivity_checker=connectivityChecker
user_manager=userManager,
preemptive_cache=preemptiveCache
)
# 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():
@@ -441,7 +344,7 @@ class Server(object):
if not userManager.enabled:
loginManager.anonymous_user = users.DummyUser
principals.identity_loaders.appendleft(users.dummy_identity_loader)
loginManager.init_app(app, add_context_processor=False)
loginManager.init_app(app)
# register API blueprint
self._setup_blueprints()
@@ -584,13 +487,8 @@ 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:
@@ -736,7 +634,8 @@ class Server(object):
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
def _setup_app(self, app):
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, \
OctoPrintFlaskResponse, ServerSideSessionInterface
s = settings()
@@ -770,6 +669,11 @@ class Server(object):
app.request_class = OctoPrintFlaskRequest
app.response_class = OctoPrintFlaskResponse
def session_persistent(app, request):
return "X-Preemptive-Cache" not in request.headers
app.session_interface = ServerSideSessionInterface(s.getBaseFolder("sessions"),
persistent_callback=session_persistent)
@app.before_request
def before_request():
g.locale = self._get_locale()
@@ -952,6 +856,7 @@ class Server(object):
headers = kwargs.get("headers", dict())
headers["X-Force-View"] = plugin if plugin else "_default"
headers["X-Preemptive-Record"] = "no"
headers["X-Preemptive-Cache"] = "true"
kwargs["headers"] = headers
builder = EnvironBuilder(**kwargs)
@@ -1376,44 +1281,21 @@ 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),
bind_and_activate=False)
self._intermediary_server = BaseHTTPServer.HTTPServer((host, port), lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs))
# if possible, make sure our socket's port descriptor isn't handed over to subprocesses
from octoprint.util.platform import set_close_exec
try:
set_close_exec(self._intermediary_server.fileno())
except:
self._logger.exception("Error while attempting to set_close_exec on intermediary server socket")
# 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
def serve():
try:
self._intermediary_server.serve_forever()
except:
self._logger.exception("Error in intermediary server")
thread = threading.Thread(target=serve)
thread = threading.Thread(target=self._intermediary_server.serve_forever)
thread.daemon = True
thread.start()
self._logger.info("Intermediary server started")
self._logger.debug("Intermediary server started")
def _stop_intermediary_server(self):
if self._intermediary_server is None:
return
self._logger.info("Shutting down intermediary server...")
self._logger.debug("Shutting down intermediary server...")
self._intermediary_server.shutdown()
self._intermediary_server.server_close()
self._logger.info("Intermediary server shut down")
self._logger.debug("Intermediary server shut down")
class LifecycleManager(object):
def __init__(self, plugin_manager):
+6 -5
View File
@@ -222,21 +222,22 @@ def login():
@api.route("/logout", methods=["POST"])
@restricted_access
def logout():
# logout from user manager...
_logout(current_user)
# 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())
# ... and from flask login (and principal)
_logout(current_user)
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)
-12
View File
@@ -464,7 +464,6 @@ def gcodeFileCommand(filename, target):
valid_commands = {
"select": [],
"slice": [],
"analyse": [],
"copy": ["destination"],
"move": ["destination"]
}
@@ -617,17 +616,6 @@ 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]:
+1 -25
View File
@@ -154,8 +154,6 @@ 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"]),
@@ -170,9 +168,7 @@ def getSettings():
},
"temperature": {
"profiles": s.get(["temperature", "profiles"]),
"cutoff": s.getInt(["temperature", "cutoff"]),
"sendAutomatically": s.getBoolean(["temperature", "sendAutomatically"]),
"sendAutomaticallyAfter": s.getInt(["temperature", "sendAutomaticallyAfter"], min=0, max=30),
"cutoff": s.getInt(["temperature", "cutoff"])
},
"system": {
"actions": s.get(["system", "actions"]),
@@ -202,12 +198,6 @@ 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"])
}
}
}
@@ -373,8 +363,6 @@ 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"])
@@ -400,8 +388,6 @@ def _saveSettings(data):
if "temperature" in data.keys():
if "profiles" in data["temperature"]: s.set(["temperature", "profiles"], data["temperature"]["profiles"])
if "cutoff" in data["temperature"]: s.setInt(["temperature", "cutoff"], data["temperature"]["cutoff"])
if "sendAutomatically" in data["temperature"]: s.setBoolean(["temperature", "sendAutomatically"], data["temperature"]["sendAutomatically"])
if "sendAutomaticallyAfter" in data["temperature"]: s.setInt(["temperature", "sendAutomaticallyAfter"], data["temperature"]["sendAutomaticallyAfter"], min=0, max=30)
if "terminalFilters" in data.keys():
s.set(["terminalFilters"], data["terminalFilters"])
@@ -425,16 +411,6 @@ 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):
+16 -46
View File
@@ -7,7 +7,6 @@ __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
@@ -17,7 +16,6 @@ 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"])
@@ -76,59 +74,38 @@ def executeSystemCommand(source, command):
do_async = command_spec.get("async", False)
do_ignore = command_spec.get("ignore", False)
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))
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["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\" for {}:{} failed: {}".format(source, command, str(e))
error = "Command \"before\" failed: {}".format(str(e))
logger.warn(error)
return make_response(error, 500)
try:
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)
# 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:
if not do_ignore and p.returncode != 0:
returncode = p.returncode
stdout_text = p.stdout.text
stderr_text = p.stderr.text
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)
error = "Command failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(returncode, stdout_text, stderr_text)
logger.warn(error)
return make_response(error, 500)
except Exception as e:
if not do_ignore:
error = "Command for {}:{} failed: {}".format(source, command, str(e))
error = "Command failed: {}".format(str(e))
logger.warn(error)
return make_response(error, 500)
@@ -187,10 +164,7 @@ 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,
debug=True))
spec.update(dict(action=action, source="core", async=True, ignore=True))
available_commands[action] = spec
return available_commands
@@ -228,7 +202,3 @@ def _get_custom_command_spec(action):
return available_actions[action]
class CommandFailed(Exception):
def __init__(self, error):
self.error = error
+175 -6
View File
@@ -21,13 +21,23 @@ import threading
import logging
import netaddr
import os
import uuid
import collections
import pylru
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
from octoprint.settings import settings
import octoprint.server
import octoprint.users
import octoprint.plugin
import octoprint.util
from werkzeug.contrib.cache import BaseCache
from werkzeug.datastructures import CallbackDict
from past.builtins import basestring
@@ -455,12 +465,9 @@ class OctoPrintFlaskRequest(flask.Request):
We need this because cookies are not port-specific and we don't want to overwrite our
session and other cookies from one OctoPrint instance on our machine with those of another
one who happens to listen on the same address albeit a different port or script root.
one who happens to listen on the same address albeit a different port.
"""
result = "_P" + self.server_port
if self.script_root:
return result + "_R" + self.script_root.replace("/", "|")
return result
return "_P" + self.server_port
class OctoPrintFlaskResponse(flask.Response):
@@ -479,6 +486,168 @@ class OctoPrintFlaskResponse(flask.Response):
flask.Response.set_cookie(self, key, expires=0, max_age=0, path=path, domain=domain)
#~~ Sessions
class ServerSideSession(CallbackDict, flask.sessions.SessionMixin):
def __init__(self, sid, path, serializer, persistent=True, new=False):
def on_update(self):
self.modified = True
CallbackDict.__init__(self, on_update=on_update)
self.sid = sid
self.path = path
self.new = new
self.modified = False
self._logger = logging.getLogger(__name__ + ".sessions.session")
self._persistent = persistent
self._serializer = serializer
self._lock = threading.RLock()
self.read()
@property
def persistent(self):
return self._persistent
def read(self):
with self._lock:
if not os.path.exists(self.path):
return
try:
with open(self.path, "rb") as f:
data = self._serializer.loads(f.read())
self.clear()
self.update(data)
self.modified = False
return
except:
self._logger.exception("Could not read session file for session {}".format(self.sid))
def save(self):
if not self.persistent:
return
from octoprint.util import atomic_write
with self._lock:
try:
with atomic_write(self.path, mode="wb") as f:
f.write(self._serializer.dumps(dict(self)))
self.modified = False
except:
self._logger.exception("Could not write session file for session {}".format(self.sid))
self._logger.debug("Saved session file for session {}".format(self.sid))
def remove(self):
with self._lock:
if not os.path.exists(self.path):
return
try:
os.remove(self.path)
self._logger.debug("Removed session file for session {}".format(self.sid))
except:
self._logger.exception("Could not remove session file for session {}".format(self.sid))
class ServerSideSessionInterface(flask.sessions.SessionInterface):
serializer = flask.sessions.session_json_serializer
session_class = ServerSideSession
def __init__(self, directory, persistent_callback=None, min_cleanup_interval=300):
self.directory = directory
self.persistent_callback = persistent_callback
self.min_cleanup_interval = min_cleanup_interval
self._cleanup_lock = threading.RLock()
self._last_cleanup = None
self._logger = logging.getLogger(__name__ + ".sessions.interface")
def open_session(self, app, request):
self.cleanup_stale_sessions(app)
persistent = self.persistent_callback(app, request) if callable(self.persistent_callback) else True
sid = request.cookies.get(app.session_cookie_name)
try:
uuid.UUID(octoprint.util.to_str(sid))
except:
sid = None
is_new = False
if not sid:
sid = self.generate_sid()
is_new = True
if persistent:
self._logger.debug("Generated a new SID {} for path {}".format(sid, request.path))
return self.session_class(sid, self.path_for_sid(sid), self.serializer, persistent=persistent, new=is_new)
def save_session(self, app, session, response):
domain = self.get_cookie_domain(app)
path = self.get_cookie_path(app)
if not session:
if session.persistent:
session.remove()
if session.modified:
response.delete_cookie(app.session_cookie_name,
domain=domain, path=path)
return
session.save()
httponly = self.get_cookie_httponly(app)
secure = self.get_cookie_secure(app)
expires = self.get_expiration_time(app, session)
response.set_cookie(app.session_cookie_name, session.sid,
httponly=httponly, secure=secure, expires=expires,
domain=domain, path=path)
def generate_sid(self):
while True:
sid = str(uuid.uuid4())
if not os.path.exists(self.path_for_sid(sid)):
return sid
def cleanup_stale_sessions(self, app):
if self._last_cleanup is not None and self._last_cleanup - time.time() < self.min_cleanup_interval:
return
maxage = flask.sessions.total_seconds(app.permanent_session_lifetime)
cutoff = time.time() - maxage
to_clean = []
with self._cleanup_lock:
for entry in scandir(self.directory):
try:
if entry.stat().st_mtime < cutoff:
to_clean.append(entry.path)
except:
self._logger.exception("Error checking session file for session {} for staleness".format(entry.name))
for path in to_clean:
try:
os.remove(path)
self._logger.debug("Cleaned up session file for stale session {}".format(os.path.basename(path)))
except:
self._logger.exception("Error while removing session file for stale session {}".format(os.path.basename(path)))
pass
self._last_cleanup = time.time()
def path_for_sid(self, sid):
return os.path.join(self.directory, sid)
#~~ passive login helper
def passive_login():
@@ -612,7 +781,7 @@ def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=No
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
logger = logging.getLogger(__name__)
logger = logging.getLogger(__name__ + ".cache")
cache_key = key()
+1 -15
View File
@@ -21,7 +21,6 @@ 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
@@ -461,26 +460,13 @@ def _process_templates():
)
# sorting orders
def wizard_key_extractor(d, k):
if d[1].get("_key", None) == "plugin_corewizard_acl":
# Ultra special case - we MUST always have the ACL wizard first since otherwise any steps that follow and
# that require to access APIs to function will run into errors since those APIs won't work before ACL
# has been configured. See also #2140
return u"0:{}".format(to_unicode(d[0]))
elif d[1].get("mandatory", False):
# Other mandatory steps come before the optional ones
return u"1:{}".format(to_unicode(d[0]))
else:
# Finally everything else
return u"2:{}".format(to_unicode(d[0]))
template_sorting = dict(
navbar=dict(add="prepend", key=None),
sidebar=dict(add="append", key="name"),
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=wizard_key_extractor),
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])),
about=dict(add="append", key="name"),
generic=dict(add="append", key=None)
)
+5 -51
View File
@@ -112,8 +112,6 @@ default_settings = {
"ignoreErrorsFromFirmware": False,
"logResends": True,
"supportResendsWithoutOk": False,
"logPositionOnPause": True,
"logPositionOnCancel": True,
# command specific flags
"triggerOkForM29": True
@@ -148,12 +146,6 @@ 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
@@ -232,16 +224,15 @@ default_settings = {
"scripts": None,
"translations": None,
"generated": None,
"data": None
"data": None,
"sessions": None
},
"temperature": {
"profiles": [
{"name": "ABS", "extruder" : 210, "bed" : 100 },
{"name": "PLA", "extruder" : 180, "bed" : 60 }
],
"cutoff": 30,
"sendAutomatically": False,
"sendAutomaticallyAfter": 1,
"cutoff": 30
},
"printerProfiles": {
"default": None
@@ -350,7 +341,6 @@ default_settings = {
"okAfterResend": False,
"forceChecksum": False,
"numExtruders": 1,
"pinnedExtruders": None,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
"hasBed": True,
@@ -1286,43 +1276,23 @@ class Settings(object):
return None
def getInt(self, path, **kwargs):
minimum = kwargs.pop("min", None)
maximum = kwargs.pop("max", None)
value = self.get(path, **kwargs)
if value is None:
return None
try:
intValue = int(value)
if minimum is not None and intValue < minimum:
return minimum
elif maximum is not None and intValue > maximum:
return maximum
else:
return intValue
return int(value)
except ValueError:
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
return None
def getFloat(self, path, **kwargs):
minimum = kwargs.pop("min", None)
maximum = kwargs.pop("max", None)
value = self.get(path, **kwargs)
if value is None:
return None
try:
floatValue = float(value)
if minimum is not None and floatValue < minimum:
return minimum
elif maximum is not None and floatValue > maximum:
return maximum
else:
return floatValue
return float(value)
except ValueError:
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
return None
@@ -1478,16 +1448,8 @@ class Settings(object):
self.set(path, None, **kwargs)
return
minimum = kwargs.pop("min", None)
maximum = kwargs.pop("max", None)
try:
intValue = int(value)
if minimum is not None and intValue < minimum:
intValue = minimum
if maximum is not None and intValue > maximum:
intValue = maximum
except ValueError:
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
return
@@ -1499,16 +1461,8 @@ class Settings(object):
self.set(path, None, **kwargs)
return
minimum = kwargs.pop("min", None)
maximum = kwargs.pop("max", None)
try:
floatValue = float(value)
if minimum is not None and floatValue < minimum:
floatValue = minimum
if maximum is not None and floatValue > maximum:
floatValue = maximum
except ValueError:
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
return
+1 -1
View File
@@ -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
+29 -41
View File
@@ -301,16 +301,10 @@ var doParse = function () {
var tool = 0;
var prev_extrude = [{a: 0, b: 0, c: 0, e: 0, abs: 0}];
var prev_retract = [0];
// we keep track of our active toolOffset here so that our visualization lines up - if we didn't
// offset the coordinates from the GCODE file with the tool offset, stuff would look wonky since our
// visualizer doesn't actually have a physical offset ;)
var activeToolOffset = toolOffsets[0];
var i, j, args;
var offset = toolOffsets[0];
model = [];
for (i = 0; i < gcode.length; i++) {
for (var i = 0; i < gcode.length; i++) {
x = undefined;
y = undefined;
z = undefined;
@@ -325,35 +319,30 @@ var doParse = function () {
extrude = false;
line = line.split(/[\(;]/)[0];
if (!line || line.trim() === "") {
// empty line, skip entirely
continue;
}
var addToModel = false;
var move = false;
var log = false;
if (/^(?:G0|G1|G2|G3)\s/i.test(line)) {
args = line.split(/\s/);
var args = line.split(/\s/);
for (j = 0; j < args.length; j++) {
for (var j = 0; j < args.length; j++) {
switch (argChar = args[j].charAt(0).toLowerCase()) {
case 'x':
if (relativeMode) {
x = prevX + Number(args[j].slice(1)) + activeToolOffset.x;
x = prevX + Number(args[j].slice(1)) + offset.x;
} else {
x = Number(args[j].slice(1)) + activeToolOffset.x;
x = Number(args[j].slice(1)) + offset.x;
}
break;
case 'y':
if (relativeMode) {
y = prevY + Number(args[j].slice(1)) + activeToolOffset.y;
y = prevY + Number(args[j].slice(1)) + offset.y;
} else {
y = Number(args[j].slice(1)) + activeToolOffset.y;
y = Number(args[j].slice(1)) + offset.y;
}
break;
@@ -387,7 +376,7 @@ var doParse = function () {
if (prev_extrude[tool]["abs"] < 0) {
prev_retract[tool] = -1;
retract = -1;
} else if (prev_extrude[tool]["abs"] === 0) {
} else if (prev_extrude[tool]["abs"] == 0) {
retract = 0;
} else if (prev_extrude[tool]["abs"] > 0 && prev_retract[tool] < 0) {
prev_retract[tool] = 0;
@@ -409,9 +398,9 @@ var doParse = function () {
center_j = Number(args[j].slice(1));
break;
case 'g':
if(args[j].charAt(1).toLowerCase() === '2')
if(args[j].charAt(1).toLowerCase()=='2')
direction=1;
if(args[j].charAt(1).toLowerCase() === '3')
if(args[j].charAt(1).toLowerCase()=='3')
direction=-1;
break;
}
@@ -422,7 +411,7 @@ var doParse = function () {
prev_extrude[tool]["abs"] = Math.sqrt((prevX - x) * (prevX - x) + (prevY - y) * (prevY - y));
}
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) {
addToModel = true;
move = true;
}
@@ -445,12 +434,12 @@ var doParse = function () {
} else if (/^(?:M103)/i.test(line)) {
dcExtrude = false;
} else if (/^(?:G92)/i.test(line)) {
args = line.split(/\s/);
var args = line.split(/\s/);
for (j = 0; j < args.length; j++) {
for (var j = 0; j < args.length; j++) {
if (!args[j]) continue;
if (args.length === 1) {
if (args.length == 1) {
// G92 without coordinates => reset all axes to 0
x = 0;
y = 0;
@@ -462,11 +451,11 @@ var doParse = function () {
} else {
switch (argChar = args[j].charAt(0).toLowerCase()) {
case 'x':
x = Number(args[j].slice(1)) + activeToolOffset.x;
x = Number(args[j].slice(1)) + offset.x;
break;
case 'y':
y = Number(args[j].slice(1)) + activeToolOffset.y;
y = Number(args[j].slice(1)) + offset.y;
break;
case 'z':
@@ -495,9 +484,9 @@ var doParse = function () {
}
} else if (/^(?:G28)/i.test(line)) {
args = line.split(/\s/);
var args = line.split(/\s/);
if (args.length === 1) {
if (args.length == 1) {
// G28 with no arguments => home all axis
x = 0;
y = 0;
@@ -521,11 +510,11 @@ var doParse = function () {
}
// if it's the first layer and G28 was without z
if (layer === 0 && typeof(z) === 'undefined') {
if (layer == 0 && typeof(z) === 'undefined') {
z = 0;
}
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) {
addToModel = true;
move = true;
}
@@ -534,13 +523,13 @@ var doParse = function () {
if (!prev_extrude[tool]) prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0};
if (!prev_retract[tool]) prev_retract[tool] = 0;
activeToolOffset = toolOffsets[tool];
if (!activeToolOffset) activeToolOffset = {x: 0, y: 0};
offset = toolOffsets[tool];
if (!offset) offset = {x: 0, y: 0};
}
// If move is on a new height and it's not extruding and
// it's not currently already in a Z-lift, assume it's possibly a Z-lift
if (typeof(z) !== 'undefined' && z !== prevZ && !extrude && !zLift) {
if (typeof(z) !== 'undefined' && z != prevZ && !extrude && !zLift) {
zLift = true;
zLiftZ = prevZ;
}
@@ -549,8 +538,8 @@ var doParse = function () {
zLift = false;
}
if (typeof(z) !== 'undefined' && z !== prevZ) {
if (z_heights[z] !== undefined) {
if (typeof(z) !== 'undefined' && z != prevZ) {
if (z_heights[z]) {
layer = z_heights[z];
} else {
layer = model.length;
@@ -560,7 +549,7 @@ var doParse = function () {
sendLayer = layer;
sendLayerZ = z;
prevZ = z;
} else if (typeof(z) === 'undefined' && typeof(prevZ) !== 'undefined') {
} else if (typeof(z) == 'undefined' && typeof(prevZ) != 'undefined') {
if (z_heights.hasOwnProperty(prevZ)) {
layer = z_heights[prevZ];
} else {
@@ -620,7 +609,7 @@ var doParse = function () {
}
if (typeof(sendLayer) !== "undefined") {
if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length !== 0) {
if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length != 0) {
lastSend = i;
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100);
sendMultiLayer = [];
@@ -640,7 +629,7 @@ var parseGCode = function (message) {
gcode = message.gcode;
firstReport = message.options.firstReport;
toolOffsets = message.options.toolOffsets;
if (!toolOffsets || toolOffsets.length === 0) toolOffsets = [{x: 0, y: 0}];
if (!toolOffsets || toolOffsets.length == 0) toolOffsets = [{x: 0, y: 0}];
bed = message.options.bed;
ignoreOutsideBed = message.options.ignoreOutsideBed;
g90InfluencesExtruder = message.options.g90InfluencesExtruder;
@@ -677,7 +666,6 @@ var runAnalyze = function (message) {
var setOption = function (options) {
for (var opt in options) {
if (!options.hasOwnProperty(opt)) continue;
gCodeOptions[opt] = options[opt];
}
};
@@ -44,12 +44,15 @@ GCODE.gCodeReader = (function(){
var prepareGCode = function(totalSize){
if(!lines)return;
gcode = [];
var i, byteCount;
var i, tmp, byteCount;
byteCount = 0;
for(i=0;i<lines.length;i++){
byteCount += lines[i].length + 1; // line length + line ending
gcode.push({line: lines[i], percentage: byteCount * 100 / totalSize});
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});
}
}
lines = [];
};
@@ -143,7 +146,7 @@ GCODE.gCodeReader = (function(){
this.clear();
var totalSize = reader.target.result.length;
lines = reader.target.result.split(/[\r\n]/g);
lines = reader.target.result.split(/\n/);
reader.target.result = null;
prepareGCode(totalSize);
@@ -89,10 +89,6 @@
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);
-19
View File
@@ -983,30 +983,11 @@ function getOnlyChangedData(data, oldData) {
return f(data, oldData);
}
function setOnViewModels(allViewModels, key, value) {
setOnViewModelsIf(allViewModels, key, value, undefined);
}
function setOnViewModelsIf(allViewModels, key, value, condition) {
if (condition === undefined || !_.isFunction(condition)) {
condition = function() { return true; };
}
_.each(allViewModels, function(viewModel) {
if (condition(viewModel)) {
viewModel[key] = value;
}
})
}
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; };
}
+12 -42
View File
@@ -613,7 +613,6 @@ $(function() {
// startup complete
callViewModels(allViewModels, "onStartupComplete");
setOnViewModels(allViewModels, "_startupComplete", true);
// make sure we can track the browser tab visibility
OctoPrint.coreui.onBrowserVisibilityChange(function(status) {
@@ -649,59 +648,30 @@ $(function() {
log.info("Initial application setup done, connecting to server...");
/**
* The following looks a bit complicated, so let me explain...
*
* Once we connect to the server (and that also includes consecutive reconnects), the
* first thing we need to do is perform a passive login to a) establish a proper request
* session with the server and b) figure out the login status of our client. That passive
* login will be responded to with our session cookie and we must make absolutely sure that
* this cannot be overridden by any concurrent requests. E.g. if we would send the passive
* login request and also something like a settings fetch, the settings would not have the
* cookie yet, hence the server would generate a new session for that request, and if the
* response for the settings now arrives later than the passive login we'll get our
* session cookie from that login directly overwritten again. That will not only lead to
* us losing our login session with the server but also the client _thinking_ it is logged
* in when in fact it isn't. See also #1881.
*
* So what we do here is ensure that we send the passive login request _and nothing else_
* until that has been responded to and hence our session been properly established. Only
* then we may trigger stuff like the various view model callbacks that might cause
* additional requests.
*
* onServerConnect below takes care of the passive login. Only once that's completed it tells
* our DataUpdater that it's ok to trigger any callbacks in view models. On the initial
* server connect (during first initialization) we also trigger the settings fetch and
* binding proceedure once that's done, but only then.
*
* Or, as a fancy diagram: https://gist.githubusercontent.com/foosel/0cdc3a03cf5311804271f12e87293c0c/raw/abc84fdc3b13030d70961539d9c132ae39c32085/octoprint_web_startup.txt
*/
var onServerConnect = function() {
// Always perform a passive login on server (re)connect. No need for
// onServerConnect/onServerReconnect on the LoginStateViewModel with this in place.
return viewModelMap["loginStateViewModel"].requestData()
// onServerConnect/onServerReconnect with this in place.
viewModelMap["loginStateViewModel"].requestData()
.done(function() {
// Only mark our data updater as initialized once we've done our initial
// passive login request.
//
// This is to ensure that we have no concurrent requests triggered by socket events
// overriding each other's session during app intialization
// This is to ensure that we have no concurrent requests overriding each other's
// session during app intialization, and has the additional benefit of reducing the
// number of required requests since we don't have re-request data that might have
// changed if we turn out to be logged in.
dataUpdater.initialized();
});
};
var dataUpdater = new DataUpdater(allViewModels);
var dataUpdater = new DataUpdater(allViewModels, onServerConnect);
dataUpdater.connect()
.done(function() {
// make sure we trigger onServerConnect should we dis- and reconnect to the server
dataUpdater.connectCallback = onServerConnect;
// perform passive login first
onServerConnect().done(function() {
// then trigger a settings fetch
window.setTimeout(fetchSettings, 0);
});
// onServerConnect will have been called just before this.
//
// Decoupled settings fetch, for the reasons see above's lengthy description
// on a weird JQuery AJAX issue with ETag headers and promise handling.
window.setTimeout(fetchSettings, 0);
});
}
);
@@ -581,7 +581,7 @@ $(function() {
var additionalInfo = $(".additionalInfo", entryElement);
additionalInfo.slideToggle("fast", function() {
$(".toggleAdditionalData i", entryElement).toggleClass("fa-chevron-down fa-chevron-up");
$(".toggleAdditionalData i", entryElement).toggleClass("icon-chevron-down icon-chevron-up");
});
};
@@ -109,7 +109,8 @@ $(function() {
self.reader_sortLayers.subscribe(self.synchronizeOptions);
self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions);
self._printerProfileUpdated = function() {
// subscribe to relevant printer settings...
self.settings.printerProfiles.currentProfileData.subscribe(function() {
if (!self.enabled) return;
var currentProfileData = self.settings.printerProfiles.currentProfileData();
@@ -145,27 +146,6 @@ $(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() {
@@ -214,13 +194,11 @@ $(function() {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
if (currentProfileData && currentProfileData.extruder) {
if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets() && !currentProfileData.extruder.sharedNozzle()) {
var offsets = [];
if (currentProfileData.extruder.offsets() && !currentProfileData.extruder.sharedNozzle()) {
_.each(currentProfileData.extruder.offsets(), function(offset) {
offsets.push({x: offset[0], y: offset[1]})
});
}
_.each(currentProfileData.extruder.offsets(), function(offset) {
offsets.push({x: offset[0], y: offset[1]})
});
return offsets;
} else {
return undefined;
@@ -52,21 +52,16 @@ $(function() {
self.fromResponse = function(response) {
var process = function() {
var currentLoggedIn = self.loggedIn();
if (response && response.name) {
self.loggedIn(true);
self.updateCurrentUserData(response);
if (!currentLoggedIn) {
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
log.info("User " + response.name + " logged in")
}
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
log.info("User " + response.name + " logged in")
} else {
self.loggedIn(false);
self.resetCurrentUserData();
if (currentLoggedIn) {
callViewModels(self.allViewModels, "onUserLoggedOut");
log.info("User logged out");
}
callViewModels(self.allViewModels, "onUserLoggedOut");
log.info("User logged out");
}
};
@@ -225,16 +225,14 @@ $(function() {
var result = [];
if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) {
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;
for (var key in data.filament) {
if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) continue;
result.push({
name: ko.observable(gettext("Tool") + " " + key.substr("tool".length)),
data: ko.observable(data.filament[key])
});
});
}
}
self.filament(result);
};
@@ -173,8 +173,6 @@ $(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);
@@ -197,8 +195,6 @@ $(function() {
self.temperature_profiles = ko.observableArray(undefined);
self.temperature_cutoff = ko.observable(undefined);
self.temperature_sendAutomatically = ko.observable(undefined);
self.temperature_sendAutomaticallyAfter = ko.observable(undefined);
self.system_actions = ko.observableArray([]);
@@ -213,11 +209,6 @@ $(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;
@@ -893,14 +884,12 @@ $(function() {
};
self.onUserLoggedIn = function() {
// we might have other user rights now, refresh (but only if startup has fully completed)
if (!self._startupComplete) return;
// we might have other user rights now, refresh
self.requestData();
};
self.onUserLoggedOut = function() {
// we might have other user rights now, refresh (but only if startup has fully completed)
if (!self._startupComplete) return;
// we might have other user rights now, refresh
self.requestData();
}
}
@@ -47,18 +47,7 @@ $(function() {
var callback = function() {
OctoPrint.system.executeCommand(commandSpec.actionSource, commandSpec.action)
.done(function() {
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"
});
new PNotify({title: "Success", text: _.sprintf(gettext("The command \"%(command)s\" executed successfully"), {command: commandSpec.name}), type: "success"});
deferred.resolve(["success", arguments]);
})
.fail(function(jqXHR, textStatus, errorThrown) {
@@ -6,7 +6,7 @@ $(function() {
self.settingsViewModel = parameters[1];
self._createToolEntry = function() {
var entry = {
return {
name: ko.observable(),
key: ko.observable(),
actual: ko.observable(0),
@@ -14,63 +14,11 @@ $(function() {
offset: ko.observable(0),
newTarget: ko.observable(),
newOffset: ko.observable()
};
entry.newTargetValid = ko.pureComputed(function() {
var value = entry.newTarget();
try {
value = parseInt(value);
} catch (exc) {
return false;
}
return (value >= 0 && value <= 999);
});
entry.newOffsetValid = ko.pureComputed(function() {
var value = entry.newOffset();
try {
value = parseInt(value);
} catch (exc) {
return false;
}
return (-50 <= value <= 50);
});
entry.offset.subscribe(function(newValue) {
if (self.changingOffset.item !== undefined && self.changingOffset.item.key() == entry.key()) {
// if our we currently have the offset dialog open for this entry and the offset changed
// meanwhile, update the displayed value in the dialog
self.changingOffset.offset(newValue);
}
});
return entry;
}
};
self.changingOffset = {
offset: ko.observable(0),
newOffset: ko.observable(0),
name: ko.observable(""),
item: undefined,
title: ko.pureComputed(function() {
return _.sprintf(gettext("Changing Offset of %(name)s"), {name: self.changingOffset.name()});
}),
description: ko.pureComputed(function() {
return _.sprintf(gettext("Use the form below to specify a new offset to apply to all temperature commands sent from printed files for \"%(name)s\""),
{name: self.changingOffset.name()});
})
};
self.changeOffsetDialog = undefined;
self.tools = ko.observableArray([]);
self.hasBed = ko.observable(true);
self.bedTemp = self._createToolEntry();
self.bedTemp["name"](gettext("Bed"));
self.bedTemp["key"]("bed");
@@ -95,7 +43,7 @@ $(function() {
self._printerProfileUpdated = function() {
var graphColors = ["red", "orange", "green", "brown", "purple"];
var heaterOptions = {};
var tools = [];
var tools = self.tools();
var color;
// tools
@@ -123,7 +71,7 @@ $(function() {
if (tools.length < 1 || !tools[0]) {
tools[0] = self._createToolEntry();
}
tools[0]["name"](gettext("Tool"));
tools[0]["name"](gettext("Hotend"));
tools[0]["key"]("tool0");
}
@@ -147,7 +95,6 @@ $(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);
});
@@ -453,191 +400,66 @@ $(function() {
return maxTemp;
};
self.incrementTarget = function(item) {
self.setTarget = function(item) {
var value = item.newTarget();
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) {
value = item.target();
}
try {
value = parseInt(value);
if (value > 999) return;
item.newTarget(value + 1);
self.autosendTarget(item);
} catch (ex) {
// do nothing
}
};
self.decrementTarget = function(item) {
var value = item.newTarget();
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) {
value = item.target();
}
try {
value = parseInt(value);
if (value <= 0) return;
item.newTarget(value - 1);
self.autosendTarget(item);
} catch (ex) {
// do nothing
}
};
var _sendTimeout = {};
self.autosendTarget = function(item) {
if (!self.settingsViewModel.temperature_sendAutomatically()) return;
var delay = self.settingsViewModel.temperature_sendAutomaticallyAfter() * 1000;
var name = item.name();
if (_sendTimeout[name]) {
window.clearTimeout(_sendTimeout[name]);
}
_sendTimeout[name] = window.setTimeout(function() {
self.setTarget(item);
delete _sendTimeout[name];
}, delay);
};
self.clearAutosendTarget = function(item) {
var name = item.name();
if (_sendTimeout[name]) {
window.clearTimeout(_sendTimeout[name]);
delete _sendTimeout[name];
}
};
self.setTarget = function(item, form) {
var value = item.newTarget();
if (form !== undefined) {
$(form).find("input").blur();
}
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) return OctoPrintClient.createRejectedDeferred();
self.clearAutosendTarget(item);
return self.setTargetToValue(item, value);
};
self.setTargetFromProfile = function(item, profile) {
if (!profile) return OctoPrintClient.createRejectedDeferred();
self.clearAutosendTarget(item);
return self.setTargetToValue(item, (item.key() == "bed" ? profile.bed : profile.extruder));
};
self.setTargetToZero = function(item) {
self.clearAutosendTarget(item);
return self.setTargetToValue(item, 0);
};
self.setTargetToValue = function(item, value) {
self.clearAutosendTarget(item);
try {
value = parseInt(value);
} catch (ex) {
return OctoPrintClient.createRejectedDeferred();
}
if (value < 0 || value > 999) return OctoPrintClient.createRejectedDeferred();
if (!value) return;
var onSuccess = function() {
item.target(value);
item.newTarget("");
};
if (item.key() == "bed") {
return self._setBedTemperature(value)
self._setBedTemperature(value)
.done(onSuccess);
} else {
return self._setToolTemperature(item.key(), value)
self._setToolTemperature(item.key(), value)
.done(onSuccess);
}
};
self.changeOffset = function(item) {
// copy values
self.changingOffset.item = item;
self.changingOffset.name(item.name());
self.changingOffset.offset(item.offset());
self.changingOffset.newOffset(item.offset());
self.setTargetFromProfile = function(item, profile) {
if (!profile) return;
self.changeOffsetDialog.modal("show");
};
var onSuccess = function() {
item.newTarget("");
};
self.incrementChangeOffset = function() {
var value = self.changingOffset.newOffset();
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) value = self.changingOffset.offset();
try {
value = parseInt(value);
if (value >= 50) return;
self.changingOffset.newOffset(value + 1);
} catch (ex) {
// do nothing
if (item.key() == "bed") {
self._setBedTemperature(profile.bed)
.done(onSuccess);
} else {
self._setToolTemperature(item.key(), profile.extruder)
.done(onSuccess);
}
};
self.decrementChangeOffset = function() {
var value = self.changingOffset.newOffset();
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) value = self.changingOffset.offset();
try {
value = parseInt(value);
if (value <= -50) return;
self.changingOffset.newOffset(value - 1);
} catch (ex) {
// do nothing
self.setTargetToZero = function(item) {
var onSuccess = function() {
item.newTarget("");
};
if (item.key() == "bed") {
self._setBedTemperature(0)
.done(onSuccess);
} else {
self._setToolTemperature(item.key(), 0)
.done(onSuccess);
}
};
self.deleteChangeOffset = function() {
self.changingOffset.newOffset(0);
};
self.confirmChangeOffset = function() {
var item = self.changingOffset.item;
item.newOffset(self.changingOffset.newOffset());
self.setOffset(item)
.done(function() {
self.changeOffsetDialog.modal("hide");
// reset
self.changingOffset.offset(0);
self.changingOffset.newOffset(0);
self.changingOffset.name("");
self.changingOffset.item = undefined;
})
};
self.setOffset = function(item) {
var value = item.newOffset();
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) return OctoPrintClient.createRejectedDeferred();
return self.setOffsetToValue(item, value);
};
self.setOffsetToZero = function(item) {
return self.setOffsetToValue(item, 0);
};
self.setOffsetToValue = function(item, value) {
try {
value = parseInt(value);
} catch (ex) {
return OctoPrintClient.createRejectedDeferred();
}
if (value < -50 || value > 50) return OctoPrintClient.createRejectedDeferred();
if (!value) return;
var onSuccess = function() {
item.offset(value);
item.newOffset("");
};
if (item.key() == "bed") {
return self._setBedOffset(value)
self._setBedOffset(value)
.done(onSuccess);
} else {
return self._setToolOffset(item.key(), value)
self._setToolOffset(item.key(), value)
.done(onSuccess);
}
};
@@ -681,28 +503,13 @@ $(function() {
self.handleEnter = function(event, type, item) {
if (event.keyCode == 13) {
if (type == "target") {
self.setTarget(item)
.done(function() {
event.target.blur();
});
self.setTarget(item);
} else if (type == "offset") {
self.confirmChangeOffset();
self.setOffset(item);
}
}
};
self.handleFocus = function(event, type, item) {
if (type == "target") {
var value = item.newTarget();
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) {
item.newTarget(item.target());
}
event.target.select();
} else if (type == "offset") {
event.target.select();
}
};
self.onAfterTabChange = function(current, previous) {
if (current != "#temp") {
return;
@@ -722,8 +529,6 @@ $(function() {
}
});
}
self.changeOffsetDialog = $("#change_offset_dialog");
};
self.onStartupComplete = function() {
@@ -735,6 +540,6 @@ $(function() {
OCTOPRINT_VIEWMODELS.push([
TemperatureViewModel,
["loginStateViewModel", "settingsViewModel"],
["#temp", "#change_offset_dialog"]
"#temp"
]);
});
@@ -272,16 +272,6 @@ $(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,25 +192,9 @@ $(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
if (preventSettingsRefreshDialog) {
return false;
} else {
self.settingsViewModel.settingsUpdatedDialog.modal("show");
return true;
}
self.settingsViewModel.settingsUpdatedDialog.modal("show");
return true;
}
return false;
+1 -5
View File
@@ -687,11 +687,7 @@
if (!isActive) {
if ('ontouchstart' in document.documentElement) {
// if mobile we we use a backdrop because click events don't delegate
// PATCH by foosel based on CapnBry's suggestion - see foosel/OctoPrint#2059 for details
//$('<div class="dropdown-backdrop"/>').insertBefore($(this)).on('click', clearMenus)
$('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
// /PATCH
$('<div class="dropdown-backdrop"/>').insertBefore($(this)).on('click', clearMenus)
}
$parent.toggleClass('open')
}
+13 -117
View File
@@ -400,6 +400,7 @@ table {
width: 80px;
.actioncol;
}
}
}
@@ -412,57 +413,14 @@ table {
background: url("../img/graph-background.png") no-repeat center;
}
#temperature-table {
table-layout: fixed;
width: 100%;
margin-top: 20px;
th, td {
&.temperature_tool,
&.temperature_actual,
&.temperature_target,
&.temperature_offset {
vertical-align: middle;
text-align: center;
form {
margin: 0;
}
.dropdown-menu {
text-align: left;
}
}
&.temperature_tool {
width: 16%;
text-align: left;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
&.temperature_actual {
width: 12%;
}
&.temperature_target {
width: 42%;
overflow: visible;
}
&.temperature_offset {
width: 30%;
}
}
}
/** Various */
.tab-content, .tab-pane {
overflow: visible;
}
.tempInput {
width: 50px;
}
#temp_newTemp, #temp_newBedTemp, #speed_innerWall, #speed_outerWall, #speed_fill, #speed_support,
#webcam_timelapse_interval, #webcam_timelapse_postRoll, #webcam_timelapse_fps, #webcam_timelapse_retractionZHop {
text-align: right;
@@ -878,6 +836,10 @@ ul.dropdown-menu li a {
margin-bottom: 30px;
}
#terminal-sendpanel {
text-align: right;
}
}
#settings_dialog {
@@ -1128,6 +1090,10 @@ textarea.block {
display: inline-block !important;
}
a.dropdown-sd {
padding-top: 4px !important;
}
.center {
float: none;
margin-left: auto;
@@ -1272,61 +1238,6 @@ _::-webkit-full-page-media, _:future, :root .full-sized-box {
width: inherit;
}
}
.btn-group:first-child {
.btn:first-child {
-webkit-border-radius: 4px 0 0 4px;
-moz-border-radius: 4px 0 0 4px;
border-radius: 4px 0 0 4px;
}
}
.btn-group {
.btn:first-child {
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
}
}
// 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%;
}
.control-group.error .input-prepend .fileinput-button,
@@ -1334,25 +1245,10 @@ _::-webkit-full-page-media, _:future, :root .full-sized-box {
border-color: #b94a48;
}
.control-text {
// like control-label, but without cursor, float, width or text-align
padding-top: 5px;
cursor: default;
}
input[type=number] {
text-align: right;
}
input[type="number"].input-nospin::-webkit-outer-spin-button,
input[type="number"].input-nospin::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"].input-nospin {
-moz-appearance: textfield;
}
// Progress bars with text
//
// .progress-text-front will also need to have the full width of the enclosing
@@ -151,18 +151,6 @@
<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,10 +4,4 @@
{% 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>
@@ -1,5 +1,5 @@
<form class="form-horizontal">
<h3>{{ _('Graph') }}</h3>
<h3>{{ _('Temperature Graph') }}</h3>
<div class="control-group">
<label class="control-label">{{ _('Graph cutoff') }}</label>
<div class="controls">
@@ -10,26 +10,7 @@
<span class="help-block">{{ _('Needs a restart of OctoPrint to become active.') }}</span>
</div>
</div>
<h3>{{ _('Fine adjustments') }}</h3>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: temperature_sendAutomatically"> {{ _('Send temperature fine adjustments automatically') }}
</label>
<span class="help-block">{{ _('Enable this to have temperature fine adjustments you do via the + or - button be sent to the printer automatically.') }}</span>
</div>
</div>
<div class="control-group" data-bind="visible: temperature_sendAutomatically">
<label class="control-label">{{ _('Sending delay') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" class="input-mini" min="0" max="30" data-bind="value: temperature_sendAutomaticallyAfter">
<span class="add-on">sec</span>
</div>
<span class="help-block">{{ _('OctoPrint will use this delay to limit the number of sent temperature commands should you perform multiple fine adjustments in a short time.') }}</span>
</div>
</div>
<h3>{{ _('Presets') }}</h3>
<h3>{{ _('Temperature Presets') }}</h3>
<div class="row-fluid">
<div class="offset4 span3"><h4>{{ _('Extruder') }}</h4></div>
<div class="span3"><h4>{{ _('Bed') }}</h4></div>
@@ -1,34 +0,0 @@
<div id="change_offset_dialog" class="modal hide fade">
<div class="modal-header">
<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 data-bind="text: changingOffset.title"></h3>
</div>
<div class="modal-body">
<p data-bind="text: changingOffset.description"></p>
<form class="form-horizontal" data-bind="submit: confirmChangeOffset">
<div class="control-group">
<label class="control-label">{{ _('Current Offset') }}</label>
<div class="controls">
<label class="control-text" data-bind="html: changingOffset.offset() + ' &deg;C'"></label>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('New Offset') }}</label>
<div class="controls">
<div class="input-prepend input-append">
<button type="button" class="btn btn-input-dec" data-bind="click: $root.decrementChangeOffset" title="{{ _('-1') }}"><i class="fa fa-minus"></i></button>
<input type="number" min="-50" max="50" class="input-mini input-nospin" style="width: 30px" data-bind="value: changingOffset.newOffset, event: { focus: function(d, e) {$root.handleFocus(e, 'target', changingOffset.item);}, keyup: function(d, e) {$root.handleEnter(e, 'offset', changingOffset.item);} }">
<span class="add-on">&deg;C</span>
<button type="button" class="btn btn-input-inc" data-bind="click: $root.incrementChangeOffset" title="{{ _('+1') }}"><i class="fa fa-plus"></i></button>
</div>
<button type="button" class="btn" data-bind="click: $root.deleteChangeOffset" title="{{ _('Delete Offset') }}"><i class="fa fa-trash"></i></button>
<span class="help-block">{{ _('Hint: Hitting <kbd>Enter</kbd> in the input field will also submit the form') }}</span>
</div>
</div>
</form>
</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">{{ _('Save') }}</a>
</div>
</div>
-1
View File
@@ -131,7 +131,6 @@
{% include 'dialogs/wizard.jinja2' %}
{% include 'dialogs/about.jinja2' %}
{% include 'dialogs/files.jinja2' %}
{% include 'dialogs/temperature.jinja2' %}
<!-- End of dialogs -->
<!-- Overlays -->
+1 -1
View File
@@ -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" autocorrect="off">
<input type="text" id="login_user" name="username" data-bind="valueWithInit: loginState.loginUser" placeholder="{{ _('Username') }}" autocapitalize="none">
<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" data-toggle="dropdown" href="#" title="{{ _('SD Card operations') }}">
<a class="dropdown-toggle dropdown-sd" data-toggle="dropdown" href="#" title="{{ _('SD Card operations') }}">
<span class="icon-sd-black-14"></span>
</a>
<ul class="dropdown-menu">
@@ -1,18 +0,0 @@
{% 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>
@@ -1,5 +0,0 @@
<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>
@@ -1,7 +0,0 @@
<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>
@@ -1,6 +0,0 @@
<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>
@@ -1,9 +0,0 @@
<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>
@@ -1,6 +0,0 @@
<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>
+1 -1
View File
@@ -130,7 +130,7 @@
</script>
<script type="text/html" id="customControls_containerTemplate_collapsable">
<div class="custom_section">
<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>
<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>
<!-- ko template: { name: 'customControls_containerTemplate', data: $data } --><!-- /ko -->
</div>
</script>
+25 -33
View File
@@ -5,12 +5,12 @@
{% endif %}
<div class="row-fluid">
<table id="temperature-table" class="table table-bordered table-hover">
<table class="table table-bordered table-hover" style="table-layout: fixed; width: 100%; margin-top: 20px">
<tr>
<th class="temperature_tool"></th>
<th class="temperature_actual" title="{{ _('Current actual temperature as reported by your printer') }}">{{ _('Actual') }}</th>
<th class="temperature_target" title="{{ _('Current target temperature as reported by your printer') }}">{{ _('Target') }}</th>
<th class="temperature_offset" title="{{ _('Offset to apply to temperature commands sent from files') }}">{{ _('Offset') }}</th>
<th style="width: 18%"></th>
<th style="width: 12%; text-align: right">{{ _('Actual') }}</th>
<th style="width: 35%">{{ _('Target') }}</th>
<th style="width: 35%">{{ _('Offset') }}</th>
</tr>
<!-- ko foreach: tools -->
<tr data-bind="template: { name: 'temprow-template' }"></tr>
@@ -19,45 +19,37 @@
</table>
<script type="text/html" id="temprow-template">
<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">
<button type="button" class="btn btn-input-dec" data-bind="click: $root.decrementTarget, enable: $root.isOperational() && $root.loginState.isUser()" title="{{ _('Fine adjust: -1°C') }}"><i class="fa fa-minus"></i></button>
<input type="number" min="0" max="999" class="input-mini input-nospin" style="width: 30px" data-bind="attr: {placeholder: cleanTemperature(target())}, value: newTarget, valueUpdate: 'input', enable: $root.isOperational() && $root.loginState.isUser(), event: { focus: function(d, e) {$root.handleFocus(e, 'target', $data) } }">
<span class="add-on">&deg;C</span>
<button type="button" class="btn btn-input-inc" data-bind="click: $root.incrementTarget, enable: $root.isOperational() && $root.loginState.isUser()" title="{{ _('Fine adjust: +1°C') }}"><i class="fa fa-plus"></i></button>
</div>
<th style="vertical-align: middle" data-bind="text: name"></th>
<td style="text-align: right; vertical-align: middle" data-bind="html: formatTemperature(actual())"></td>
<td style="vertical-align: middle; overflow: visible">
<div class="input-append">
<input type="number" class="input-mini text-right tempInput" data-bind="attr: {placeholder: cleanTemperature(target()) }, value: newTarget, enable: $root.isOperational() && $root.loginState.isUser(), event: { keyup: function(d, e) {$root.handleEnter(e, 'target', $data);} }">
<span class="add-on">&deg;C</span>
<div class="btn-group">
<button type="submit" data-bind="enable: $root.isOperational() && $root.loginState.isUser() && $data.newTargetValid()" class="btn btn-primary" title="{{ _('Set') }}"><i class="fa fa-check"></i></button>
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" data-bind="enable: $root.isOperational() && $root.loginState.isUser()">
<button type="submit" data-bind="click: $parent.setTarget, enable: $root.isOperational() && $root.loginState.isUser()" class="btn">{{ _('Set') }}</button>
<button class="btn dropdown-toggle" data-toggle="dropdown" data-bind="enable: $root.isOperational() && $root.loginState.isUser()">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>
<a href="javascript:void(0)" data-bind="click: $root.setTargetToZero">{{ _('Off') }}</a>
</li>
<li class="divider"></li>
<!-- ko foreach: $root.temperature_profiles -->
<li>
<a href="javascript:void(0)" data-bind="click: function() {$root.setTargetFromProfile($parent, $data);}, text: 'Set ' + name + ' (' + ($parent.key() == 'bed' ? bed : extruder) + '&deg;C)'"></a>
<a href="#" data-bind="click: function() {$root.setTargetFromProfile($parent, $data);}, text: 'Set ' + name + ' (' + ($parent.key() == 'bed' ? bed : extruder) + '&deg;C)'"></a>
</li>
<!-- /ko -->
<li class="divider"></li>
<li>
<a href="#" data-bind="click: $root.setTargetToZero">{{ _('Off') }}</a>
</li>
</ul>
</div>
</form>
</div>
</td>
<td class="temperature_offset">
<form class="form-inline" style="margin:0">
<div class="input-append">
<span class="input-mini uneditable-input text-right" style="width: 30px" data-bind="text: offset"></span>
<span class="add-on">&deg;C</span>
<button class="btn" title="{{ _('Change Offset') }}" data-bind="click: $root.changeOffset, enable: $root.isOperational() && $root.loginState.isUser()"><i class="fa fa-pencil"></i></button>
<button class="btn" title="{{ _('Delete Offset') }}" data-bind="click: $root.setOffsetToZero, enable: $root.isOperational() && $root.loginState.isUser()"><i class="fa fa-trash"></i></button>
</div>
</form>
<td style="vertical-align: middle">
<div class="input-append">
<input type="number" min="-50" max="50" class="input-mini text-right tempInput" data-bind="attr: {placeholder: offset}, value: newOffset, enable: $root.isOperational() && $root.loginState.isUser(), event: { keyup: function(d, e) {$root.handleEnter(e, 'offset', $data);} }">
<span class="add-on">&deg;C</span>
<button type="submit" data-bind="click: $root.setOffset, enable: $root.isOperational() && $root.loginState.isUser()" class="btn">{{ _('Set') }}</button>
</div>
</td>
</script>
</div>
+9 -8
View File
@@ -1,15 +1,9 @@
<div class="terminal">
<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" 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-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>&nbsp;|&nbsp;<a href="#" data-bind="click: selectAll">{{ _("Select all") }}</a></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>
<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>
</div>
<div class="row-fluid">
@@ -20,6 +14,13 @@
</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="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="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 class="hide">
<div class="pull-left">
<div class="btn-group">
File diff suppressed because it is too large. Load diff
+16 -166
View File
@@ -735,47 +735,22 @@ def interface_addresses(family=None):
if not ifaddress["addr"].startswith("169.254."):
yield ifaddress["addr"]
def address_for_client(host, port, timeout=3.05):
def address_for_client(host, port):
"""
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:
if server_reachable(host, port, timeout=timeout, proto="udp", source=address):
return address
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((address, 0))
sock.connect((host, port))
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):
@@ -1071,7 +1046,7 @@ class InvariantContainer(object):
return self._data.__iter__()
class PrependableQueue(queue.Queue):
class PrependQueue(queue.Queue):
def __init__(self, maxsize=0):
queue.Queue.__init__(self, maxsize=maxsize)
@@ -1107,21 +1082,21 @@ class PrependableQueue(queue.Queue):
self.queue.appendleft(item)
class TypedQueue(PrependableQueue):
class TypedQueue(PrependQueue):
def __init__(self, maxsize=0):
PrependableQueue.__init__(self, maxsize=maxsize)
PrependQueue.__init__(self, maxsize=maxsize)
self._lookup = set()
def put(self, item, item_type=None, *args, **kwargs):
PrependableQueue.put(self, (item, item_type), *args, **kwargs)
PrependQueue.put(self, (item, item_type), *args, **kwargs)
def get(self, *args, **kwargs):
item, _ = PrependableQueue.get(self, *args, **kwargs)
item, _ = PrependQueue.get(self, *args, **kwargs)
return item
def prepend(self, item, item_type=None, *args, **kwargs):
PrependableQueue.prepend(self, (item, item_type), *args, **kwargs)
PrependQueue.prepend(self, (item, item_type), *args, **kwargs)
def _put(self, item):
_, item_type = item
@@ -1131,10 +1106,10 @@ class TypedQueue(PrependableQueue):
else:
self._lookup.add(item_type)
PrependableQueue._put(self, item)
queue.Queue._put(self, item)
def _get(self):
item = PrependableQueue._get(self)
item = PrependQueue._get(self)
_, item_type = item
if item_type is not None:
@@ -1150,135 +1125,10 @@ class TypedQueue(PrependableQueue):
else:
self._lookup.add(item_type)
PrependableQueue._prepend(self, item)
PrependQueue._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)
+115 -223
View File
@@ -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, PrependableQueue, TypeAlreadyInQueue, chunks
to_unicode, bom_aware_open, TypedQueue, 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<codeGM>[GM]\d+)(\\.(?P<subcode>\d+))?|(?P<codeT>T)\d+|(?P<codeF>F)\d+)")
regex_command = re.compile("^\s*((?P<commandGM>[GM]\d+)|(?P<commandT>T)\d+|(?P<commandF>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_float_pattern, regex_float_pattern))
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 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_float_pattern)
regex_repetierTempExtr = re.compile("TargetExtr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_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_float_pattern)
regex_repetierTempBed = re.compile("TargetBed:(?P<target>%s)" % regex_positive_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 = SendQueue()
self._send_queue = TypedQueue()
self._temperature_timer = None
self._sd_status_timer = None
@@ -461,9 +461,6 @@ 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
@@ -947,10 +944,7 @@ class MachineCom(object):
except:
pass
if self._log_position_on_cancel:
self.sendCommand("M400", on_sent=_on_M400_sent)
else:
self._cancel_preparation_done()
self.sendCommand("M400", on_sent=_on_M400_sent)
def _pause_preparation_done(self):
self._callback.on_comm_print_job_paused()
@@ -997,10 +991,7 @@ class MachineCom(object):
self._record_pause_data = True
self.sendCommand("M114")
if self._log_position_on_pause:
self.sendCommand("M400", on_sent=_on_M400_sent)
else:
self._pause_preparation_done()
self.sendCommand("M400", on_sent=_on_M400_sent)
def getSdFiles(self):
return self._sdFiles
@@ -2077,7 +2068,6 @@ 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:
@@ -2106,7 +2096,7 @@ class MachineCom(object):
cmd = self._lastLines[-self._resendDelta]
lineNumber = self._currentLine - self._resendDelta
result = self._enqueue_for_sending(cmd, linenumber=lineNumber, resend=True)
result = self._enqueue_for_sending(cmd, linenumber=lineNumber)
self._resendDelta -= 1
if self._resendDelta <= 0:
@@ -2114,8 +2104,6 @@ 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):
@@ -2124,20 +2112,20 @@ class MachineCom(object):
if self._serial is None:
return False
gcode, subcode = gcode_and_subcode_for_cmd(cmd)
gcode = None
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, command_type=cmd_type, gcode=gcode, subcode=subcode)
results = self._process_command_phase("queuing", cmd, cmd_type, gcode=gcode)
if not results:
# command is no more, return
return False
else:
results = [(cmd, cmd_type, gcode, subcode)]
results = [(cmd, cmd_type, gcode)]
# process helper
def process(cmd, cmd_type, gcode, subcode, on_sent=None):
def process(cmd, cmd_type, gcode, on_sent=None):
if cmd is None:
# no command, next entry
return False
@@ -2150,7 +2138,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, subcode=subcode)
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
return True
else:
return False
@@ -2167,18 +2155,18 @@ class MachineCom(object):
enqueued_something = False
# process all but the last ...
for (cmd, cmd_type, gcode, subcode) in results:
enqueued_something = process(cmd, cmd_type, gcode, subcode) or enqueued_something
for (cmd, cmd_type, gcode) in results:
enqueued_something = process(cmd, cmd_type, gcode) or enqueued_something
# ... and then process the last one with the on_sent callback attached
cmd, cmd_type, gcode, subcode = last_command
enqueued_something = process(cmd, cmd_type, gcode, subcode, on_sent=on_sent) or enqueued_something
cmd, cmd_type, gcode = last_command
enqueued_something = process(cmd, cmd_type, gcode, 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, resend=False):
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None):
"""
Enqueues a command and optional linenumber to use for it in the send queue.
@@ -2192,11 +2180,7 @@ class MachineCom(object):
"""
try:
target = "send"
if resend:
target = "resend"
self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type, target=target)
self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in send queue: " + e.type)
@@ -2204,7 +2188,7 @@ class MachineCom(object):
def _send_loop(self):
"""
The send loop is responsible of sending commands in ``self._send_queue`` over the line, if it is cleared for
The send loop is reponsible 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.
"""
@@ -2232,7 +2216,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, subcode = gcode_and_subcode_for_cmd(command)
gcode = gcode_command_for_cmd(command)
if linenumber is not None:
# line number predetermined - this only happens for resends, so we'll use the number and
@@ -2242,7 +2226,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, subcode=subcode)
results = self._process_command_phase("sending", command, command_type, gcode=gcode)
if not results:
# No, we are not going to send this, that was a last-minute bail.
@@ -2255,14 +2239,20 @@ class MachineCom(object):
# and now let's fetch the next item from the queue
continue
# 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
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 only use the first (and only!) entry here
command, _, gcode, subcode = results[0]
# 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]
if command.strip() == "":
self._logger.info("Refusing to send an empty line to the printer")
@@ -2290,7 +2280,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, subcode=subcode)
self._process_command_phase("sent", command, command_type, gcode=gcode)
# 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
@@ -2318,10 +2308,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, subcode=None):
def _process_command_phase(self, phase, command, command_type=None, gcode=None):
if gcode is None:
gcode, subcode = gcode_and_subcode_for_cmd(command)
results = [(command, command_type, gcode, subcode)]
gcode = gcode_command_for_cmd(command)
results = [(command, command_type, gcode)]
if (self.isStreaming() and self.isPrinting()) or phase not in ("queuing", "queued", "sending", "sent"):
return results
@@ -2329,20 +2319,14 @@ 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, subcode in results:
for command, command_type, gcode in results:
try:
hook_results = hook(self, phase, command, command_type, gcode, subcode=subcode)
hook_results = hook(self, phase, command, command_type, gcode)
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, 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
normalized = _normalize_command_handler_result(command, command_type, gcode, hook_results)
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 []
@@ -2351,15 +2335,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, subcode in results:
for command, command_type, gcode 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, subcode=subcode)
new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results)
handler_results = getattr(self, gcode_handler)(command, cmd_type=command_type)
new_results += _normalize_command_handler_result(command, command_type, gcode, handler_results)
modified = True
else:
new_results.append((command, command_type, gcode, subcode))
new_results.append((command, command_type, gcode))
modified = True
if modified:
if not new_results:
@@ -2372,9 +2356,9 @@ class MachineCom(object):
command_phase_handler = "_command_phase_" + phase
if hasattr(self, command_phase_handler):
new_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)
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)
results = new_results
# finally return whatever we resulted on
@@ -2460,7 +2444,7 @@ class MachineCom(object):
##~~ command handlers
def _gcode_T_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
def _gcode_T_queuing(self, cmd, cmd_type=None):
toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch:
current_tool = self._currentTool
@@ -2471,14 +2455,14 @@ class MachineCom(object):
return before + [cmd] + after
def _gcode_T_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
def _gcode_T_sent(self, cmd, cmd_type=None):
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, gcode=None, subcode=None, *args, **kwargs):
def _gcode_G0_sent(self, cmd, cmd_type=None):
if "Z" in cmd or "F" in cmd:
# track Z
match = regexes_parameters["floatZ"].search(cmd)
@@ -2501,7 +2485,7 @@ class MachineCom(object):
pass
_gcode_G1_sent = _gcode_G0_sent
def _gcode_G28_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
def _gcode_G28_sent(self, cmd, cmd_type=None):
if "F" in cmd:
match = regexes_parameters["floatF"].search(cmd)
if match:
@@ -2511,34 +2495,34 @@ class MachineCom(object):
except ValueError:
pass
def _gcode_M0_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
def _gcode_M0_queuing(self, cmd, cmd_type=None):
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, gcode=None, subcode=None, *args, **kwargs):
def _gcode_M25_queuing(self, cmd, cmd_type=None):
# 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, gcode=None, subcode=None, *args, **kwargs):
def _gcode_M28_sent(self, cmd, cmd_type=None):
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, gcode=None, subcode=None, *args, **kwargs):
def _gcode_M29_sent(self, cmd, cmd_type=None):
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, gcode=None, subcode=None, *args, **kwargs):
def _gcode_M140_queuing(self, cmd, cmd_type=None):
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, gcode=None, subcode=None, wait=False, support_r=False, *args, **kwargs):
def _gcode_M104_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
toolNum = self._currentTool
toolMatch = regexes_parameters["intT"].search(cmd)
@@ -2561,7 +2545,7 @@ class MachineCom(object):
except ValueError:
pass
def _gcode_M140_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, wait=False, support_r=False, *args, **kwargs):
def _gcode_M140_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
match = regexes_parameters["floatS"].search(cmd)
if not match and support_r:
match = regexes_parameters["floatR"].search(cmd)
@@ -2574,24 +2558,24 @@ class MachineCom(object):
except ValueError:
pass
def _gcode_M109_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
def _gcode_M109_sent(self, cmd, cmd_type=None):
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, gcode=None, subcode=None, *args, **kwargs):
def _gcode_M190_sent(self, cmd, cmd_type=None):
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, gcode=None, subcode=None, *args, **kwargs):
def _gcode_M116_sent(self, cmd, cmd_type=None):
self._heatupWaitStartTime = time.time()
self._long_running_command = True
self._heating = True
def _gcode_M155_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
def _gcode_M155_sending(self, cmd, cmd_type=None):
match = regexes_parameters["intS"].search(cmd)
if match:
try:
@@ -2601,7 +2585,7 @@ class MachineCom(object):
except:
pass
def _gcode_M110_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
def _gcode_M110_sending(self, cmd, cmd_type=None):
newLineNumber = 0
match = regexes_parameters["intN"].search(cmd)
if match:
@@ -2620,7 +2604,7 @@ class MachineCom(object):
self._lastLines.clear()
self._resendDelta = None
def _gcode_M112_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
def _gcode_M112_queuing(self, cmd, cmd_type=None):
# emergency stop, jump the queue with the M112
self._do_send_without_checksum("M112")
self._do_increment_and_send_with_checksum("M112")
@@ -2649,7 +2633,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, gcode=None, subcode=None, *args, **kwargs):
def _gcode_G4_sent(self, cmd, cmd_type=None):
# 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)
@@ -2665,7 +2649,7 @@ class MachineCom(object):
##~~ command phase handlers
def _command_phase_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
def _command_phase_sending(self, cmd, cmd_type=None, gcode=None):
if gcode is not None and gcode in self._long_running_commands:
self._long_running_command = True
@@ -2941,88 +2925,6 @@ 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)
@@ -3375,43 +3277,35 @@ 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, None
return None
match = regex_command.search(cmd)
if not match:
return None, None
gcode = regex_command.search(cmd)
if not gcode:
return None
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"]
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"]
else:
# this should never happen
return None, None
return gcode, values.get("subcode", None)
return None
def _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results):
def _normalize_command_handler_result(command, command_type, gcode, 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``,
``gcode`` and ``subcode`` are returned in that case (as single-entry list with
one 4-tuple as entry).
``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).
Single result entries are either:
@@ -3423,31 +3317,31 @@ def _normalize_command_handler_result(command, command_type, gcode, subcode, han
the normalized result.
The method returns a list of normalized result entries. Normalized result
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
entries always are a 3-tuple consisting of ``command``, ``command_type``
and ``gcode``, the latter two 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, 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", 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, ["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)]
>>> _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')]
Arguments:
command (str or None): The command for which the handler result was
@@ -3456,18 +3350,16 @@ def _normalize_command_handler_result(command, command_type, gcode, subcode, han
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
4-tuples consisting of ``command``, ``command_type``, ``gcode``
and ``subcode``, the latter three of which may be ``None``.
3-tuples consisting of ``command``, ``command_type`` and
``gcode``, the latter two of which may be ``None``.
"""
original = (command, command_type, gcode, subcode)
original = (command, command_type, gcode)
if handler_results is None:
# handler didn't return anything, we'll just continue
@@ -3488,8 +3380,8 @@ def _normalize_command_handler_result(command, command_type, gcode, subcode, han
if isinstance(handler_result, basestring):
# entry is just a string, replace command with it
command = handler_result
gcode, subcode = gcode_and_subcode_for_cmd(command)
result.append((command, command_type, gcode, subcode))
gcode = gcode_command_for_cmd(command)
result.append((command, command_type, gcode))
elif isinstance(handler_result, tuple):
# entry is a tuple, extract command and command_type
@@ -3509,11 +3401,11 @@ def _normalize_command_handler_result(command, command_type, gcode, subcode, han
# command is None, ignore it and continue
continue
gcode, subcode = gcode_and_subcode_for_cmd(command)
result.append((command, command_type, gcode, subcode))
gcode = gcode_command_for_cmd(command)
result.append((command, command_type, gcode))
# reset to original
command, command_type, gcode, subcode = original
command, command_type, gcode = original
return result
+91 -10
View File
@@ -222,6 +222,7 @@ 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]
@@ -319,16 +320,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),
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))
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))
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
pos = newPos * scale + toolOffset
if f is not None and f != 0:
feedrate = f
@@ -441,16 +442,14 @@ 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:
pos.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
pos.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
toolOffset.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
toolOffset.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
currentExtruder = T
pos.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
pos.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
toolOffset.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
toolOffset.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
if len(currentE) <= currentExtruder:
for i in range(len(currentE), currentExtruder + 1):
@@ -512,3 +511,85 @@ def getCodeFloat(line, code):
except:
return None
if __name__ == "__main__":
import click
import time
import yaml
import sys
@click.command()
@click.option("--throttle", "throttle", type=float, default=None)
@click.option("--throttle-lines", "throttle_lines", type=int, default=None)
@click.option("--speed-x", "speedx", type=float, default=6000)
@click.option("--speed-y", "speedy", type=float, default=6000)
@click.option("--speed-z", "speedz", type=float, default=300)
@click.option("--offset", "offset", type=(float, float), multiple=True)
@click.option("--max-t", "maxt", type=int, default=10)
@click.option("--g90-extruder", "g90_extruder", is_flag=True)
@click.option("--progress", "progress", is_flag=True)
@click.argument("path", type=click.Path())
def main(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress):
throttle_callback = None
if throttle:
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every $throttle_lines lines
time.sleep(throttle)
offsets = offset
if offsets is None:
offsets = []
elif isinstance(offset, tuple):
offsets = list(offsets)
offsets = [(0, 0)] + offsets
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
start_time = time.time()
progress_callback = None
if progress:
def progress_callback(percentage):
print("PROGRESS:{}".format(percentage))
interpreter = gcode(progress_callback=progress_callback)
interpreter.load(path,
speedx=speedx,
speedy=speedy,
offsets=offsets,
throttle=throttle_callback,
max_extruders=maxt,
g90_extruder=g90_extruder)
print("DONE:{}s".format(time.time() - start_time))
print("RESULTS:")
print(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
# os args are gained differently on win32
try:
from click.utils import get_os_args
args = get_os_args()
except ImportError:
# for whatever reason we are running an older Click version?
args = sys.argv[1:]
if len(args) >= len(sys.argv):
# Now some ugly preprocessing of our arguments starts. We have a somewhat difficult situation on our hands
# here if we are running under Windows and want to be able to handle utf-8 command line parameters (think
# plugin parameters such as names or something, e.g. for the "dev plugin:new" command) while at the same
# time also supporting sys.argv rewriting for debuggers etc (e.g. PyCharm).
#
# So what we try to do here is solve this... Generally speaking, sys.argv and whatever Windows returns
# for its CommandLineToArgvW win32 function should have the same length. If it doesn't however and
# sys.argv is shorter than the win32 specific command line arguments, obviously stuff was cut off from
# sys.argv which also needs to be cut off of the win32 command line arguments.
#
# So this is what we do here.
# -1 because first entry is the script that was called
sys_args_length = len(sys.argv) - 1
# cut off stuff from the beginning
args = args[-1 * sys_args_length:] if sys_args_length else []
main(args=args, prog_name="octoprint-gcode-analysis")
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more