Compare commits

...
Author SHA1 Message Date
Gina Häußge 77753ca026 Preparing release of 1.3.5 2017-10-16 13:21:27 +02:00
Gina Häußge e88e6ba292 Preparing release of 1.3.5rc4 2017-10-04 13:33:46 +02:00
Gina Häußge 25c56a5402 Wizard: Force ACL sub wizard to always come first
If required.

Closes #2140
2017-10-04 11:34:06 +02:00
Gina Häußge 7fc0f48659 Adjust unit tests for script root in cookie suffix 2017-09-28 17:43:53 +02:00
Gina Häußge dfe345007e Updated sockjs-tornado dependency
Apparently we need 1.0.3 after all for custom session classes.

Reported by @MoonshineSG in #2095
2017-09-28 16:30:27 +02:00
Gina Häußge 4fe6e0545a Also include script name in cookie name
Otherwise we might run into trouble if we have an OctoPrint instance
running on / and /octoprint2 for example - the browser will send
cookies for both instances to the /octoprint2 instance and whatever
gets processed last will overwrite the value before in Tornado's cookie
processing. This of course will nuke the login session in case of the /
cookie being sent or processed last.

Appending the path/script root to the cookie name solves this, similar
to how we circumvented an identical problem caused by browsers not
distinguishing between ports for cookies.

Solves an issue reported by @mgrl in #2095
2017-09-28 16:23:27 +02:00
Gina Häußge c84e199e87 Add & use "octoprint analysis gcode" subcommand
That should solve any weird import issues we have when
running gcodeInterpreter.py directly (and hence putting
octoprint.util as first entry into the python path,
causing potential issues with imported modules such as
yaml to catch the octoprint.util.platform module instead
of the actual python platform module).

See reported problem with that by @CapnBry in #2095
2017-09-28 10:33:28 +02:00
Gina Häußge 79f7a5a1e7 staging is 1.3.5rc4.dev 2017-08-25 14:56:15 +02:00
Gina Häußge 679674df22 Preparing release of 1.3.5rc3 2017-08-25 11:46:40 +02:00
Gina Häußge 5989d243d3 Fix wrapping of temperature controls on touch devices
Successfully tested in Chrome (desktop & Android), Firefox (desktop &
Android), Safari (desktop & iOS).

Closes #2059
2017-08-25 09:47:11 +02:00
Gina Häußge 97cb0088f6 Delay opening of serial.log until first message
That way we don't risk running into potential "file busy" issues
under windows on log file rollover.
2017-08-24 19:16:41 +02:00
Gina Häußge 2ed36ed383 Do not block when processing held back events! 2017-08-23 19:07:08 +02:00
Gina Häußge 12b8a54081 set_close_exec on intermediary server port for unix & windows
Using the win32 API it's possible to prevent the intermediary server
socket from inheriting itself to subprocesses. So let's use that here.

Another bit of the solution for #2090.
2017-08-23 18:31:42 +02:00
Gina Häußge a35e145649 Don't forward events to uninitialized EventPlugin implementations
Another part of fixing #2090
2017-08-23 18:19:37 +02:00
Gina Häußge f77be701a2 Only fire events once Events.STARTUP has been seen
One part of fixing #2090
2017-08-23 18:11:40 +02:00
Gina Häußge c33e9e4c85 staging is 1.3.5rc3.dev 2017-07-27 14:38:30 +02:00
Gina Häußge 1f9fe8c868 Preparing release of 1.3.5rc2 2017-07-27 13:33:45 +02:00
Gina Häußge 8f2e4ad978 Temperature tab: "Hotend" -> "Tool" 2017-07-27 12:41:08 +02:00
Gina Häußge b82d955ec7 Fix printer profile update on temperature tab & gcode viewer
As reported in #2033
2017-07-27 12:40:27 +02:00
Gina Häußge 832d2f4155 Fix temperature controls in FF not fitting on one line
Mentioned in #2033
2017-07-27 10:14:59 +02:00
Gina Häußge c336452f6c Do not run subprocesses while intermediary server is active
Any processes inheriting the open port descriptor of that server will
cause the actual server startup to fail due to the port still being
claimed.

We can't fully prevent this under Windows thanks to fnctl not being
available and win32api being a PITA, and also close_fds on Popen not
being allowed if we also need to redirect stdout/stderr/stdin for a
process. So let's hope hardening against this problem when running
under *nix, adding a bit fat warning to never start a subprocess
during the intermediary's runtime and also moving the only actual
process we so far DID start (analysis backlog processing) to after
Tornado is running will suffice.

Fixes #2035
2017-07-27 09:58:20 +02:00
Gina Häußge a9b6edde2b Fix incompatibility with non-ASCII strings in wizard sorting 2017-07-26 16:47:57 +02:00
Gina Häußge d59ef5c711 Corewizard: Fix wrongly displaying firstrunonly wizards again 2017-07-26 16:47:40 +02:00
Gina Häußge 375480c707 allViewModels -> self.allViewModels 2017-07-26 16:32:05 +02:00
Gina Häußge 60cacb9447 Temperature: Fix for legend not updating with current values
See #2033
2017-07-26 16:26:27 +02:00
Gina Häußge c159ab7fe2 Merge branch 'rc/maintenance' into staging/maintenance 2017-07-26 14:27:47 +02:00
Gina Häußge e949e0198f maintenance is now 1.3.6.dev, staging is 1.3.5rc2.dev 2017-07-26 14:24:30 +02:00
Gina Häußge 1a6dbb3f4a Preparing release of 1.3.5rc1 2017-07-26 12:47:47 +02:00
Gina Häußge 10e834f623 Improve logging of async system commands
Closes #2025
2017-07-24 18:32:21 +02:00
Gina Häußge 5ce34f774e GCODE Viewer: Fix file position calculation
We were only adding one byte for "\n". That ignored that our regex
could also match "\r\n" or "\r\r" or something like that.

Our split regex now only matches one "\r" or "\n". Empty lines we'll
simply ignore anyhow so no real harm done.

Also, we no longer strip the comments in this step - leave that to
the worker running in its own thread. Not only should that speed
things up a bit, it will also allow us to better debug the worker in
the future.
2017-07-24 12:55:39 +02:00
Gina Häußge 0456896d71 GCODE Viewer: Fix issue with lookup of layer index 0
We were just testing if z_heights[z] was truthy. If the layer index was
set but 0 that wasn't properly detected and let to overwriting our
layer information. Instead check explicitly against undefined.

Closes #2017
2017-07-24 12:52:13 +02:00
Gina Häußge e06c09e206 Fix some more FontAwesome related things
* remove some more "fa" classes where they didn't belong
  * use "fa-toggle-(on|off)" instead of circles where they were used
    to signify toggle actions
  * fix SD card icon being too high

Another follow-up to #1915
2017-07-21 12:29:18 +02:00
Gina Häußge a6d3299b91 Add user manager factory hook 2017-07-20 20:03:05 +02:00
Gina Häußge 0a7f2a209b Add opt-in wizard for online connectivity check
See also #2011
2017-07-20 20:02:57 +02:00
Gina Häußge 67f7580506 Only run connectivity checker if enabled
Otherwise assume we are online but don't ping anything.

See also #2011
2017-07-20 20:02:44 +02:00
Gina Häußge aab3a7bd63 Wizard: Support to prevent the "settings updated" dialog
Subwizards might actually intentionally want to update stuff through
the settings API, let's allow that.
2017-07-20 19:36:14 +02:00
Gina Häußge d0f5592421 Fix sorting of filament usage for more than one tool 2017-07-20 19:23:52 +02:00
Gina Häußge bb6ea4d81b Also set autocorrect to off on username field 2017-07-20 09:50:08 +02:00
Gina Häußge 7e32e5be8f GCODE viewer: Support \r, \n and \r\n line endings
So far we only supported \n and \r\n, leading to problems with MM
GCODE files generated by Slic3r Prusa Edition which apparently
produces \r line endings for some reason.

Closes #1996
2017-07-20 09:18:38 +02:00
Gina Häußge 266cae3509 PMGR: Refresh on any connectivity change 2017-07-19 18:49:52 +02:00
Gina Häußge 0dcbffb9d2 Bundled plugins: Handle connectivity states
See also #2011
2017-07-19 18:42:29 +02:00
Gina Häußge fb8c56be57 SWU: Track network connectivity & handle offline scenarios
See also #2011
2017-07-19 18:42:28 +02:00
Gina Häußge 2bc0c4a77f Synchronize pip helper cache access 2017-07-19 18:42:28 +02:00
Gina Häußge 187c09e7da Centralized online connectivity check
See also #2011
2017-07-19 18:42:27 +02:00
Gina Häußge 5c62b33967 Do not call uninitialized plugins in call_plugin 2017-07-19 18:42:26 +02:00
Gina Häußge 5db9acb359 SWU: Fix CLI commands
Client refactoring in d72c7c14 caused issues here.

Closes #2012
2017-07-18 12:39:11 +02:00
Gina Häußge 962d6ab27f CLI: Helpers for initializing client from command line 2017-07-18 12:37:23 +02:00
Gina Häußge 21699699b6 CLI: Fixed logging init for plugins
Also fixed a stupid typo ;)
2017-07-18 12:36:16 +02:00
Gina Häußge 8fec0859d9 Don't use fixed width on terminal input
Instead added some additional styles to support input-block-level
inputs with add-ons.
2017-07-18 09:46:32 +02:00
Shawn Bruce 1b9ff1b0e2 Move terminal command below terminal output and fill the row
Clicking terminal output (excluding highlighting) will set focus to terminal command
Change fancy functionality style from muted to warning so that it stands out more
2017-07-17 12:42:14 -04:00
Gina Häußge ee2d644239 Remove support for multi command expansion in sending phase
We won't support this after all, it's too much of a headache with
regards to the sending queue. Pausing takes longer, cancelling takes
longer, resends get more complicated and so on.

Command expansion in the queuing phase needs to suffice.
2017-07-17 16:26:32 +02:00
Gina Häußge a50db4b08e Options to disable position logging on cancel/pause
Provided as a workaround for people who don't want the associated
minimal delay in cancelling/pausing.

See #1946
2017-07-17 15:40:08 +02:00
Gina Häußge 6f5707a0fc Attach identity reset to logout signals
Safer than doing it manually
2017-07-17 13:14:45 +02:00
Gina Häußge cf053ddbed Temperatures may in fact be negative
E.g. in case of a disconnected thermistor, or when it is really
really cold. Make sure our parsing doesn't get confuse by this and
thinks that

  ok T:150.0/210.0 T0:-55.7/0 T1:150.0/210.0

is actually only T and T1 being reported by the firmware, causing
stuff to be wrongly canonicalized thanks to T/T1 being Smoothie's way
of reporting dual extruder setups.

Fixes #2007
2017-07-14 11:18:04 +02:00
Gina Häußge b1101f5150 Virtual printer: support pinning of temperatures
Helpful for simulating disconnected thermistors, preparation for
debugging #2007
2017-07-14 11:07:25 +02:00
Gina Häußge 3a9d581423 Decouple writing of print log from everything else
Fixes delay in cancel processing as observed by @capnbry with regards
to #1946.

More tests necessary to ensure this was the only cause.
2017-07-13 20:00:45 +02:00
Gina Häußge 142a1b0dcb Progress might be 0, don't divide by it then 2017-07-13 15:48:22 +02:00
Gina Häußge a33f44ea25 Fix File(Added|Removed) and Folder(Added|Removed) events
Were defined as 1-tuple instead of a string thanks to a syntax error.
2017-07-12 16:13:51 +02:00
Gina Häußge 23e58d2fc1 Make sure resent lines always win before regular ones
Introduced a custom send queue type that actually contains two queues,
one for resends, one for regular lines. A flag indicates whether
lines should be returned from both or only resends. That way we
ensure that as soon as we have an active resend request we ignore
what was already in the queue and only send the lines we need to resend.

Also: PrependQueue => PrependableQueue
2017-07-11 17:10:02 +02:00
Gina Häußge 2e897f19ac Synchronize all writing access to the send queue 2017-07-07 15:56:22 +02:00
Gina Häußge 16e96743c5 Docs for api_user/api_password on bitbucket_commit 2017-07-06 16:30:44 +02:00
Gina Häußge 4c6c764c5c Small simplifications and clarifications 2017-07-06 16:18:55 +02:00
Gina Häußge e86ba9a395 Merge branch 'f_bitbucket_swupdate3' of https://github.com/mrbeam/OctoPrint into pr/mrbeam/f_bitbucket_swupdate3 2017-07-06 15:33:19 +02:00
Gina Häußge c1c09d417d Removed a line that was accidentally committed 2017-07-05 17:58:33 +02:00
Gina Häußge f8d225a768 Support for parsing GCODE subcodes
Hook handlers will get any parsed subcode as optional keyword argument
"subcode".
2017-07-05 17:56:46 +02:00
Gina Häußge 4c3f4c2a8b Fix "additional data" toggle in file list 2017-07-05 16:37:39 +02:00
Gina Häußge cc3d34635e Add API function to (re)analyse files 2017-07-05 16:37:03 +02:00
Gina Häußge c81c93896b Apply tool offsets immediately and only once
Less tracking of offsets and also more similar to how
firmware does this.

We rewrite our current position on tool change to current position
plus tool offset instead of applying it for every single
position change.
2017-07-05 15:16:08 +02:00
Andy Werner 3bb06a1a33 SW Update check type 'bitbucket_commit' now supports API credentials for private repos 2017-07-03 17:17:43 +02:00
99 changed files with 5027 additions and 2232 deletions

No files matched your search

+7 -5
View File
@@ -18,12 +18,14 @@ HEAD
# maintenance is currently the branch for preparation of maintenance release 1.3.5 # maintenance is currently the branch for preparation of maintenance release 1.3.5
# so are any fix/... and improve/... branches # so are any fix/... and improve/... branches
maintenance 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev maintenance 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
fix/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev fix/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
improve/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev improve/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.5rc1 # staging/maintenance is currently the branch for preparation of 1.3.5rc4
staging/maintenance 1.3.5rc1 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev # so is regressionfix/...
staging/maintenance 1.3.5rc4 679674df2282af0c4500367fa93864c6defa3802 pep440-dev
regressionfix/.* 1.3.5rc4 679674df2282af0c4500367fa93864c6defa3802 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now # every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev .* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
+93
View File
@@ -1,5 +1,98 @@
# OctoPrint Changelog # 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) ## 1.3.4 (2017-06-01)
### Note for owners of Malyan M200/Monoprice Select Mini ### Note for owners of Malyan M200/Monoprice Select Mini
+6 -7
View File
@@ -14,30 +14,29 @@ thanks to everyone who contributed!
* Boris Hussein * Boris Hussein
* Brad Jackson * Brad Jackson
* Brian E. Tyler * Brian E. Tyler
* Chris Day
* Christian Petropolis * Christian Petropolis
* COLLE+McVOY
* CreativeTools * CreativeTools
* D Brian Kimmel * D Brian Kimmel
* DeltaMaker 3D Printers * DeltaMaker 3D Printers
* Doug Johnson
* E3D BigBox * E3D BigBox
* Ernesto Martinez * Ernesto Martinez
* Exovite * Exovite
* F. Kunsmann * F. Kunsmann
* Farren Young II
* Frank Sander * Frank Sander
* Gary Deen * Gary Deen
* Gary N McKinney * Gary N McKinney
* George Robles * George Robles
* günter weber * günter weber
* Ivan Krasin
* James Seigel * James Seigel
* Jamie R McGuigan * Jamie R McGuigan
* Jason Lawrence
* Jeff Moe * Jeff Moe
* Josh Daniels * Josh Daniels
* Kaile Riser * Kaile Riser
* Kale Stedman * Kale Stedman
* Kazuhiro Ogura * Kazuhiro Ogura
* Lamin Kivelä
* Makespace Madrid * Makespace Madrid
* Marcus Ackermann * Marcus Ackermann
* Mark Qvist * Mark Qvist
@@ -45,6 +44,7 @@ thanks to everyone who contributed!
* Masayoshi Mitsui * Masayoshi Mitsui
* Michael Aumock * Michael Aumock
* Miles Flavel * Miles Flavel
* mitchell hirsch
* Mohammed khorakiwala * Mohammed khorakiwala
* Noe Ruiz * Noe Ruiz
* Patrick McGinnis * Patrick McGinnis
@@ -55,14 +55,13 @@ thanks to everyone who contributed!
* Roger Strolz * Roger Strolz
* Roy Cortes * Roy Cortes
* Samer Najia * Samer Najia
* SD3D
* SeeMeCNC
* Simon Hallam * Simon Hallam
* Stefan Krister * Stefan Krister
* Stephane Schittly * Stephane Schittly
* Sven Mueller * Sven Mueller
* Symbiotic Devices
* Thomas Hatley * Thomas Hatley
* Timeshell.ca * Timeshell.ca
* Trent Shumay * Trent Shumay
and 1098 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! and 1133 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+7
View File
@@ -198,6 +198,13 @@ Version checks
* ``branch``: Branch of the Bitbucket repository to check, defaults to * ``branch``: Branch of the Bitbucket repository to check, defaults to
``master`` if not set. ``master`` if not set.
* ``current``: Current commit hash. Will be updated automatically. * ``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 * ``git_commit``: Checks a local git repository for new commits on its
configured remote. Additional config parameters: configured remote. Additional config parameters:
+14
View File
@@ -909,6 +909,20 @@ Use the following settings to configure the server:
# Command to shut down the system OctoPrint is running on, defaults to being unset # Command to shut down the system OctoPrint is running on, defaults to being unset
systemShutdownCommand: sudo shutdown -h now 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 # Settings of when to display what disk space warning
diskspace: diskspace:
+8
View File
@@ -110,6 +110,14 @@ ClientClosed
* ``remoteAddress``: the remote address (IP) of the client that disconnected * ``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 Printer communication
--------------------- ---------------------
+6
View File
@@ -87,6 +87,9 @@ There are a few additional template variables available for the following specif
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. See * ``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. ``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 * ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above
for the structure to expect here. for the structure to expect here.
@@ -94,6 +97,9 @@ There are a few additional template variables available for the following specif
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled. * ``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. 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 * ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
for the structure to expect here. for the structure to expect here.
+1
View File
@@ -14,4 +14,5 @@ Internal Modules
server.rst server.rst
settings.rst settings.rst
slicing.rst slicing.rst
users.rst
util.rst util.rst
+9
View File
@@ -0,0 +1,9 @@
.. _sec-modules-users:
octoprint.users
---------------
.. automodule:: octoprint.users
:members:
+49 -9
View File
@@ -389,7 +389,7 @@ This describes actually four hooks:
* ``octoprint.comm.protocol.gcode.sending`` * ``octoprint.comm.protocol.gcode.sending``
* ``octoprint.comm.protocol.gcode.sent`` * ``octoprint.comm.protocol.gcode.sent``
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs) .. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, *args, **kwargs)
Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases
are the following: 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 * ``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 an empty ``return`` statement is used or just nothing is returned explicitly from the handler. Hence, the following
examples are all falling into this category: examples are all falling into this category and equivalent:
.. code-block:: python .. code-block:: python
@@ -451,21 +451,24 @@ This describes actually four hooks:
should use this option. 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"``. * 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. Handlers which wish to rewrite both the command and the command type should use this option.
* A list of any of the above to allow for expanding one command into * **"queuing" phase only**: A list of any of the above to allow for expanding one command into
many. The following example shows how any queued command could be turned into a sequence of a temperature query, 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 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): does not make a lot of sense to be quite honest):
.. code-block:: python .. code-block:: python
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs): def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
if gcode or not cmd.startswith("@foo"): if gcode or not cmd.startswith("@foo"):
return return
return [("M105", "temperature_poll"), return [("M105", "temperature_poll"), # 2-tuple, command & command type
("M110",), ("M110",), # 1-tuple, just the command
"M117 echo foo: {}".format(cmd)] "M117 echo foo: {}".format(cmd)] # string, just the command
__plugin_hooks__ = {
"octoprint.comm.protocol.gcode.queuing": rewrite_foo
}
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type`` 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. to one already in the queue will give an error.
@@ -488,6 +491,8 @@ This describes actually four hooks:
:param str cmd_type: Type of command, e.g. ``temperature_poll`` for temperature polling or ``sd_status_poll`` for SD :param str cmd_type: Type of command, e.g. ``temperature_poll`` for temperature polling or ``sd_status_poll`` for SD
printing status polling. 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 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. :return: None, 1-tuple, 2-tuple or string, see the description above for details.
.. _sec-plugins-hook-comm-protocol-gcode-received: .. _sec-plugins-hook-comm-protocol-gcode-received:
@@ -941,3 +946,38 @@ octoprint.ui.web.templatetypes
:param dict template_sorting: read-only dictionary of currently configured template sorting specifications :param dict template_sorting: read-only dictionary of currently configured template sorting specifications
:return: a list of 3-tuples (template type, rule, sorting spec) :return: a list of 3-tuples (template type, rule, sorting spec)
:rtype: list :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,6 +45,8 @@ An overview of these properties follows.
OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`. OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`.
``self._user_manager`` ``self._user_manager``
OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`. 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:: .. seealso::
+3 -2
View File
@@ -23,7 +23,7 @@ INSTALL_REQUIRES = [
# to some voodoo needed to get large streamed uploads and downloads # to some voodoo needed to get large streamed uploads and downloads
# to work that is probably not completely straightforward and therefore # to work that is probably not completely straightforward and therefore
# something for post-1.3.0-stable release # something for post-1.3.0-stable release
"sockjs-tornado>=1.0.2,<1.1", "sockjs-tornado>=1.0.3,<1.1",
"PyYAML>=3.10,<3.11", "PyYAML>=3.10,<3.11",
"Flask-Login>=0.2.2,<0.3", "Flask-Login>=0.2.2,<0.3",
"Flask-Principal>=0.3.5,<0.4", "Flask-Principal>=0.3.5,<0.4",
@@ -49,7 +49,8 @@ INSTALL_REQUIRES = [
"scandir>=1.3,<1.4", "scandir>=1.3,<1.4",
"websocket-client>=0.40,<0.41", "websocket-client>=0.40,<0.41",
"python-dateutil>=2.6,<2.7", "python-dateutil>=2.6,<2.7",
"wrapt>=1.10.10,<1.11" "wrapt>=1.10.10,<1.11",
"futures>=3.1.1,<3.2"
] ]
if sys.platform == "darwin": if sys.platform == "darwin":
+2 -1
View File
@@ -194,7 +194,8 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
"level": "DEBUG", "level": "DEBUG",
"formatter": "serial", "formatter": "serial",
"backupCount": 3, "backupCount": 3,
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log") "filename": os.path.join(settings.getBaseFolder("logs"), "serial.log"),
"delay": True
} }
}, },
"loggers": { "loggers": {
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env python2
# coding=utf-8
from __future__ import absolute_import, division, print_function
if __name__ == "__main__":
import octoprint
octoprint.main()
+2 -1
View File
@@ -135,9 +135,10 @@ from .plugins import plugin_commands
from .dev import dev_commands from .dev import dev_commands
from .client import client_commands from .client import client_commands
from .config import config_commands from .config import config_commands
from .analysis import analysis_commands
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection, @click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands]) sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands])
@standard_options() @standard_options()
@legacy_options @legacy_options
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False) @click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
+73
View File
@@ -0,0 +1,73 @@
# 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))
+47 -24
View File
@@ -9,7 +9,7 @@ import json
import octoprint_client import octoprint_client
from octoprint.cli import get_ctx_obj_option from octoprint.cli import get_ctx_obj_option, bulk_options
from octoprint import init_settings, FatalStartupError from octoprint import init_settings, FatalStartupError
@@ -23,43 +23,66 @@ class JsonStringParamType(click.ParamType):
self.fail("%s is not a valid json string" % value, param, ctx) 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() @click.group()
def client_commands(): def client_commands():
pass pass
@client_commands.group("client", context_settings=dict(ignore_unknown_options=True)) @client_commands.group("client", context_settings=dict(ignore_unknown_options=True))
@click.option("--apikey", "-a", type=click.STRING) @client_options
@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 @click.pass_context
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix): def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
"""Basic API client.""" """Basic API client."""
try: try:
settings = None
if not host or not port or not apikey: 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)) settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
if not host: ctx.obj.client = create_client(settings=settings,
host = settings.get(["server", "host"]) apikey=apikey,
host = host if host != "0.0.0.0" else "127.0.0.1" host=host,
if not port: port=port,
port = settings.getInt(["server", "port"]) httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
if not apikey:
apikey = settings.get(["api", "key"])
baseurl = octoprint_client.build_base_url(https=https,
httpuser=httpuser,
httppass=httppass,
host=host,
port=port,
prefix=prefix)
ctx.obj.client = octoprint_client.Client(baseurl, apikey)
except FatalStartupError as e: except FatalStartupError as e:
click.echo(e.message, err=True) click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True) click.echo("There was a fatal error initializing the client.", err=True)
+4 -2
View File
@@ -60,6 +60,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
# fetch registered hooks # fetch registered hooks
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands") 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 self._initialized = True
def list_commands(self, ctx): def list_commands(self, ctx):
@@ -88,14 +90,14 @@ class OctoPrintPluginCommands(click.MultiCommand):
continue continue
result[name + self.sep + command.name] = command result[name + self.sep + command.name] = command
except: except:
self._logger.exception("Error while retrieving cli commants for plugin {}".format(name)) self._logger.exception("Error while retrieving cli commands for plugin {}".format(name))
return result return result
@click.group() @click.group()
@pass_octoprint_ctx @pass_octoprint_ctx
def plugin_commands(obj): def plugin_commands(obj):
logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN) pass
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands) @plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
def plugins(): def plugins():
+35 -8
View File
@@ -27,9 +27,10 @@ def all_events():
class Events(object): class Events(object):
# application startup # server
STARTUP = "Startup" STARTUP = "Startup"
SHUTDOWN = "Shutdown" SHUTDOWN = "Shutdown"
CONNECTIVITY_CHANGED = "ConnectivityChanged"
# connect/disconnect to printer # connect/disconnect to printer
CONNECTING = "Connecting" CONNECTING = "Connecting"
@@ -53,10 +54,10 @@ class Events(object):
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished" METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated" METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
FILE_ADDED = "FileAdded", FILE_ADDED = "FileAdded"
FILE_REMOVED = "FileRemoved", FILE_REMOVED = "FileRemoved"
FOLDER_ADDED = "FolderAdded", FOLDER_ADDED = "FolderAdded"
FOLDER_REMOVED = "FolderRemoved", FOLDER_REMOVED = "FolderRemoved"
# SD Upload # SD Upload
TRANSFER_STARTED = "TransferStarted" TRANSFER_STARTED = "TransferStarted"
@@ -131,9 +132,11 @@ class EventManager(object):
self._registeredListeners = collections.defaultdict(list) self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__) self._logger = logging.getLogger(__name__)
self._startup_signaled = False
self._shutdown_signaled = False self._shutdown_signaled = False
self._queue = queue.Queue() self._queue = queue.Queue()
self._held_back = queue.Queue()
self._worker = threading.Thread(target=self._work) self._worker = threading.Thread(target=self._work)
self._worker.daemon = True self._worker.daemon = True
@@ -160,7 +163,8 @@ class EventManager(object):
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin, octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
"on_event", "on_event",
args=(event, payload)) args=(event, payload),
initialized=True)
self._logger.info("Event loop shut down") self._logger.info("Event loop shut down")
except: except:
self._logger.exception("Ooops, the event bus worker loop crashed") self._logger.exception("Ooops, the event bus worker loop crashed")
@@ -176,7 +180,30 @@ class EventManager(object):
payload being a payload object specific to the event. payload being a payload object specific to the event.
""" """
self._queue.put((event, payload)) 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))
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables": 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" # when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
@@ -184,7 +211,7 @@ class EventManager(object):
import copy import copy
legacy_payload = copy.deepcopy(payload) legacy_payload = copy.deepcopy(payload)
legacy_payload["type"] = "gcode" legacy_payload["type"] = "gcode"
self._queue.put((event, legacy_payload)) q.put((event, legacy_payload))
def subscribe(self, event, callback): def subscribe(self, event, callback):
""" """
+24 -1
View File
@@ -180,9 +180,12 @@ class FileManager(object):
import octoprint.settings import octoprint.settings
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml") self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
def initialize(self): def initialize(self, process_backlog=False):
self.reload_plugins() self.reload_plugins()
if process_backlog:
self.process_backlog()
def process_backlog(self):
def worker(): def worker():
self._logger.info("Adding backlog items from all storage types to analysis queue...".format(**locals())) 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(): for storage_type, storage_manager in self._storage_managers.items():
@@ -253,6 +256,26 @@ class FileManager(object):
def default_slicer(self): def default_slicer(self):
return self._slicing_manager.default_slicer 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, 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): 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) absolute_source_path = self.path_on_disk(source_location, source_path)
+2 -2
View File
@@ -324,8 +324,8 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
speedy = self._current.printer_profile["axes"]["y"]["speed"] speedy = self._current.printer_profile["axes"]["y"]["speed"]
offsets = self._current.printer_profile["extruder"]["offsets"] offsets = self._current.printer_profile["extruder"]["offsets"]
interpreter = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "util", "gcodeInterpreter.py")) command = [sys.executable, "-m", "octoprint", "analysis", "gcode",
command = [sys.executable, interpreter, "--speed-x={}".format(speedx), "--speed-y={}".format(speedy), "--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle), "--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines)] "--throttle-lines={}".format(throttle_lines)]
for offset in offsets[1:]: for offset in offsets[1:]:
+13
View File
@@ -135,3 +135,16 @@ def get_divider_line(c, message=None, length=78, indent=3):
return c * indent + " " + message + " " + c * (length - indent - 2 - len(message)) return c * indent + " " + message + " " + c * (length - indent - 2 - len(message))
else: else:
return c * indent + " " + message 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:]))
+6 -1
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) return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None): def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
""" """
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the 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 indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
@@ -213,6 +213,8 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception. 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 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. 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.
""" """
@@ -225,6 +227,9 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context) plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
for plugin in plugins: for plugin in plugins:
if initialized and not hasattr(plugin, "_identifier"):
continue
if hasattr(plugin, method): if hasattr(plugin, method):
try: try:
result = getattr(plugin, method)(*args, **kwargs) result = getattr(plugin, method)(*args, **kwargs)
@@ -28,7 +28,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin, octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin, octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin, octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin): octoprint.plugin.TemplatePlugin,
octoprint.plugin.EventHandlerPlugin):
def __init__(self): def __init__(self):
self._cached_channel_configs = None self._cached_channel_configs = None
@@ -210,6 +211,14 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
return NO_CONTENT 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 # Internal Tools
def _mark_read_until(self, channel, until): def _mark_read_until(self, channel, until):
@@ -266,6 +275,11 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
safe_key = self._slugify(key) safe_key = self._slugify(key)
return self._get_channel_configs(force=force).get(safe_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): def _fetch_all_channels(self, force=False):
"""Fetch all channel feeds from cache or network.""" """Fetch all channel feeds from cache or network."""
@@ -298,7 +312,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
if data is None: if data is None:
# cache not allowed or empty, fetch from network # cache not allowed or empty, fetch from network
data = self._get_channel_data_from_network(key, config) if self._connectivity_checker.online:
data = self._get_channel_data_from_network(key, config)
else:
self._logger.info("Looks like we are offline, can't fetch announcements for channel {} from network".format(key))
return data return data
@@ -40,7 +40,7 @@ $(function() {
}; };
self.toggleButtonCss = function(data) { self.toggleButtonCss = function(data) {
var icon = data.enabled ? "fa fa-circle" : "fa fa-circle-o"; var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off";
var disabled = (self.enableToggle(data)) ? "" : " disabled"; var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled; return icon + disabled;
@@ -317,7 +317,13 @@ $(function() {
self.announcementDialog = $("#plugin_announcements_dialog"); self.announcementDialog = $("#plugin_announcements_dialog");
self.announcementDialogContent = $("#plugin_announcements_dialog_content"); self.announcementDialogContent = $("#plugin_announcements_dialog_content");
self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs"); 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 // view model class, parameters for constructor, container to bind to
+54 -3
View File
@@ -25,6 +25,13 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
names = self._get_subwizard_attrs("_get_", "_wizard_name") names = self._get_subwizard_attrs("_get_", "_wizard_name")
additional = self._get_subwizard_attrs("_get_", "_additional_wizard_template_data") 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() result = list()
for key, method in required.items(): for key, method in required.items():
if not method(): if not method():
@@ -37,7 +44,11 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
if not name: if not name:
continue continue
config = dict(type="wizard", name=name, template="corewizard_{}_wizard.jinja2".format(key), div="wizard_plugin_corewizard_{}".format(key)) config = dict(type="wizard",
name=name,
template="corewizard_{}_wizard.jinja2".format(key),
div="wizard_plugin_corewizard_{}".format(key),
suffix="_{}".format(key))
if key in additional: if key in additional:
additional_result = additional[key]() additional_result = additional[key]()
if additional_result: if additional_result:
@@ -59,8 +70,16 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
#~~ WizardPlugin API #~~ WizardPlugin API
def is_wizard_required(self): def is_wizard_required(self):
methods = self._get_subwizard_attrs("_is_", "_wizard_required") required = self._get_subwizard_attrs("_is_", "_wizard_required")
return self._settings.global_get(["server", "firstRun"]) and any(map(lambda m: m(), methods.values())) firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
if not firstrun:
required = dict((key, value) for key, value in required.items()
if not firstrunonly.get(key, lambda: False)())
any_required = any(map(lambda m: m(), required.values()))
return any_required
def get_wizard_details(self): def get_wizard_details(self):
result = dict() result = dict()
@@ -71,8 +90,14 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
return result return result
def get_wizard_version(self):
return 1
#~~ ACL subwizard #~~ ACL subwizard
def _is_acl_wizard_firstrunonly(self):
return True
def _is_acl_wizard_required(self): def _is_acl_wizard_required(self):
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized() return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
@@ -114,6 +139,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
#~~ Webcam subwizard #~~ Webcam subwizard
def _is_webcam_wizard_firstrunonly(self):
return True
def _is_webcam_wizard_required(self): def _is_webcam_wizard_required(self):
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"]) webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
webcam_stream_url = self._settings.global_get(["webcam", "stream"]) webcam_stream_url = self._settings.global_get(["webcam", "stream"])
@@ -129,6 +157,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
#~~ Server commands subwizard #~~ Server commands subwizard
def _is_servercommands_wizard_firstrunonly(self):
return True
def _is_servercommands_wizard_required(self): def _is_servercommands_wizard_required(self):
system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"]) system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"])
system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"]) system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
@@ -142,8 +173,28 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
def _get_servercommands_wizard_name(self): def _get_servercommands_wizard_name(self):
return gettext("Server Commands") 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 #~~ Printer profile subwizard
def _is_printerprofile_wizard_firstrunonly(self):
return True
def _is_printerprofile_wizard_required(self): def _is_printerprofile_wizard_required(self):
return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1 return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
@@ -125,6 +125,88 @@ $(function() {
self.settingsViewModel = parameters[0]; 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) { function CoreWizardPrinterProfileViewModel(parameters) {
var self = this; var self = this;
@@ -172,6 +254,10 @@ $(function() {
CoreWizardServerCommandsViewModel, CoreWizardServerCommandsViewModel,
["settingsViewModel"], ["settingsViewModel"],
"#wizard_plugin_corewizard_servercommands" "#wizard_plugin_corewizard_servercommands"
], [
CoreWizardOnlineCheckViewModel,
["settingsViewModel"],
"#wizard_plugin_corewizard_onlinecheck"
], [ ], [
CoreWizardPrinterProfileViewModel, CoreWizardPrinterProfileViewModel,
["printerProfilesViewModel"], ["printerProfilesViewModel"],
@@ -0,0 +1,46 @@
<h3>{{ _('Configure the connectivity check') }}</h3>
{% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %}
<p>{% trans %}
If it is disabled OctoPrint will always assume to have a working connection to the internet.
If that should not actually be the case, server startups, update checks and the like might take longer.
{% endtrans %}</p>
<p>{% trans %}
OctoPrint comes preconfigured to perform the connectivity check every 15 minutes. You may change the value here.
{% endtrans %}</p>
<form class="form-horizontal" data-bind="with: settingsViewModel, enable: !setup(), css {disabled: setup()}">
{% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
</form>
<p>{% trans %}
OctoPrint comes preconfigured to utilize Google's DNS server <code>8.8.8.8</code>, port 53 for the connectivity check (if
it's enabled). If you have concerns about using that, define the IP and port of a different online server that you
trust and that has a high availability.
{% endtrans %}</p>
<form class="form-horizontal" data-bind="with: settingsViewModel, enable: !setup(), css {disabled: setup()}">
{% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %}
</form>
<p>{% trans %}
Finally, please decide on whether to enable or disable the connectivity check. You may change the configuration at
any time to a later date through Settings > Server right from within OctoPrint.
{% endtrans %}</p>
<div class="row-fluid">
<a href="#" class="btn span6" data-bind="click: function() { if(!setup()){disableOnlineCheck()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Connectivity Check') }}</a>
<a href="#" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enableOnlineCheck()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Enable Connectivity Check') }}</a>
</div>
<div class="onlinecheck_decision" style="display: none" data-bind="visible: setup()">
<div class="text-center" style="display: none" data-bind="visible: decision()">{% trans %}
Connectivity check is <strong class="text-success">enabled</strong>.
{% endtrans %}</div>
<div class="text-center" style="display: none" data-bind="visible: !decision()">{% trans %}
Connectivity check is <strong class="text-danger">disabled</strong>.
{% endtrans %}</div>
</div>
+35 -10
View File
@@ -36,7 +36,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin, octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin, octoprint.plugin.SettingsPlugin,
octoprint.plugin.StartupPlugin, octoprint.plugin.StartupPlugin,
octoprint.plugin.BlueprintPlugin): octoprint.plugin.BlueprintPlugin,
octoprint.plugin.EventHandlerPlugin):
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar") ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
@@ -100,13 +101,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._console_logger.propagate = False self._console_logger.propagate = False
# decouple repository fetching from server startup # decouple repository fetching from server startup
def fetch_data(): self._fetch_all_data(async=True)
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 ##~~ SettingsPlugin
@@ -197,6 +192,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
except Exception as e: except Exception as e:
self._logger.warn("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(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 ##~~ SimpleApiPlugin
def get_api_commands(self): def get_api_commands(self):
@@ -239,7 +242,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
additional_args=self._settings.get(["pip_args"]), additional_args=self._settings.get(["pip_args"]),
python=sys.executable python=sys.executable
), ),
safe_mode=safe_mode) safe_mode=safe_mode,
online=self._connectivity_checker.online)
def etag(): def etag():
import hashlib import hashlib
@@ -250,6 +254,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
hash.update(str(self._notices_available)) hash.update(str(self._notices_available))
hash.update(repr(self._notices)) hash.update(repr(self._notices))
hash.update(repr(safe_mode)) hash.update(repr(safe_mode))
hash.update(repr(self._connectivity_checker.online))
return hash.hexdigest() return hash.hexdigest()
def condition(): def condition():
@@ -679,6 +684,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable: elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable:
self._pending_disable.add(plugin.key) 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): def _fetch_repository_from_disk(self):
repo_data = None repo_data = None
if os.path.isfile(self._repository_cache_path): if os.path.isfile(self._repository_cache_path):
@@ -696,6 +713,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return self._refresh_repository(repo_data=repo_data) return self._refresh_repository(repo_data=repo_data)
def _fetch_repository_from_url(self): 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"]) repository_url = self._settings.get(["repository"])
try: try:
r = requests.get(repository_url, timeout=30) r = requests.get(repository_url, timeout=30)
@@ -758,13 +779,17 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
import json import json
with open(self._notices_cache_path) as f: with open(self._notices_cache_path) as f:
notice_data = json.load(f) notice_data = json.load(f)
self._logger.info("Loaded notices from disk, was still valid") self._logger.info("Loaded notice data from disk, was still valid")
except: except:
self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path)) self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path))
return self._refresh_notices(notice_data=notice_data) return self._refresh_notices(notice_data=notice_data)
def _fetch_notices_from_url(self): 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"]) notices_url = self._settings.get(["notices"])
try: try:
r = requests.get(notices_url, timeout=30) r = requests.get(notices_url, timeout=30)
@@ -174,6 +174,7 @@ $(function() {
self.pipPython = ko.observable(); self.pipPython = ko.observable();
self.safeMode = ko.observable(); self.safeMode = ko.observable();
self.online = ko.observable();
self.pipUseUserString = ko.pureComputed(function() { self.pipUseUserString = ko.pureComputed(function() {
return self.pipUseUser() ? "yes" : "no"; return self.pipUseUser() ? "yes" : "no";
@@ -234,7 +235,7 @@ $(function() {
}; };
self.enableRepoInstall = function(data) { self.enableRepoInstall = function(data) {
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data); return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && self.isCompatible(data);
}; };
self.invalidUrl = ko.pureComputed(function() { self.invalidUrl = ko.pureComputed(function() {
@@ -244,7 +245,7 @@ $(function() {
self.enableUrlInstall = ko.pureComputed(function() { self.enableUrlInstall = ko.pureComputed(function() {
var url = self.installUrl(); var url = self.installUrl();
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl(); return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && url !== undefined && url.trim() != "" && !self.invalidUrl();
}); });
self.invalidArchive = ko.pureComputed(function() { self.invalidArchive = ko.pureComputed(function() {
@@ -321,6 +322,7 @@ $(function() {
self._fromPipResponse(data.pip, options); self._fromPipResponse(data.pip, options);
self.safeMode(data.safe_mode || false); self.safeMode(data.safe_mode || false);
self.online(data.online !== undefined ? data.online : true);
}; };
self._fromPluginsResponse = function(data, options) { self._fromPluginsResponse = function(data, options) {
@@ -814,7 +816,7 @@ $(function() {
}; };
self.toggleButtonCss = function(data) { self.toggleButtonCss = function(data) {
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-circle-o" : "fa fa-circle"; var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on";
var disabled = (self.enableToggle(data)) ? "" : " disabled"; var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled; return icon + disabled;
@@ -1020,6 +1022,10 @@ $(function() {
self._closeAllNotifications(); self._closeAllNotifications();
}; };
self.onEventConnectivityChanged = function(payload) {
self.requestData({eval_notices: true});
};
self._closeAllNotifications = function() { self._closeAllNotifications = function() {
if (self.notifications) { if (self.notifications) {
_.each(self.notifications, function(notification) { _.each(self.notifications, function(notification) {
@@ -20,6 +20,13 @@
{% endtrans %}</div> {% endtrans %}</div>
{% endmacro %} {% 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_printing() }}
{{ pluginmanager_nopip() }} {{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }} {{ pluginmanager_safemode() }}
@@ -124,6 +131,7 @@
{{ pluginmanager_printing() }} {{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }} {{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }} {{ pluginmanager_safemode() }}
{{ pluginmanager_offline() }}
<h4 style="position: relative"> <h4 style="position: relative">
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }} {{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
<div class="dropdown pull-right"> <div class="dropdown pull-right">
+128 -58
View File
@@ -15,6 +15,9 @@ import time
import logging import logging
import logging.handlers import logging.handlers
import hashlib import hashlib
import traceback
from concurrent import futures
from . import version_checks, updaters, exceptions, util, cli from . import version_checks, updaters, exceptions, util, cli
@@ -34,7 +37,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint.plugin.AssetPlugin, octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin, octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin, octoprint.plugin.StartupPlugin,
octoprint.plugin.WizardPlugin): octoprint.plugin.WizardPlugin,
octoprint.plugin.EventHandlerPlugin):
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit") COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
@@ -44,7 +48,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._configured_checks = None self._configured_checks = None
self._refresh_configured_checks = False self._refresh_configured_checks = False
self._get_versions_mutex = threading.Lock() self._get_versions_mutex = threading.RLock()
self._get_versions_data = None
self._get_versions_data_ready = threading.Event()
self._version_cache = dict() self._version_cache = dict()
self._version_cache_ttl = 0 self._version_cache_ttl = 0
@@ -467,15 +473,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
def view(): def view():
try: try:
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force) 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", return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
information=information, information=information,
timestamp=self._version_cache_timestamp)) timestamp=self._version_cache_timestamp))
@@ -502,9 +499,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
hash.update(repr(data["information"])) hash.update(repr(data["information"]))
hash.update(str(data["available"])) hash.update(str(data["available"]))
hash.update(str(data["possible"])) hash.update(str(data["possible"]))
hash.update(str(data.get("online", None)))
hash.update(",".join(targets)) hash.update(",".join(targets))
hash.update(str(self._version_cache_timestamp)) hash.update(str(self._version_cache_timestamp))
hash.update(str(self._connectivity_checker.online))
return hash.hexdigest() return hash.hexdigest()
def condition(): def condition():
@@ -566,6 +565,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
checkout_folder = self._get_octoprint_checkout_folder(checks=checks) checkout_folder = self._get_octoprint_checkout_folder(checks=checks)
return check and "update_script" in check and not checkout_folder 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 #~~ Updater
def get_current_versions(self, check_targets=None, force=False): def get_current_versions(self, check_targets=None, force=False):
@@ -585,53 +595,91 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
information = dict() information = dict()
# we don't want to do the same work twice, so let's use a lock # we don't want to do the same work twice, so let's use a lock
with self._get_versions_mutex: if self._get_versions_mutex.acquire(False):
for target, check in checks.items(): self._get_versions_data_ready.clear()
if not target in check_targets: try:
continue futures_to_result = dict()
online = self._connectivity_checker.check_immediately()
self._logger.debug("Looks like we are {}".format("online" if online else "offline"))
if not check: with futures.ThreadPoolExecutor(max_workers=5) as executor:
continue for target, check in checks.items():
if not target in check_targets:
continue
try: if not check:
populated_check = self._populated_check(target, check) continue
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
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), target_information) try:
populated_check = self._populated_check(target, check)
future = executor.submit(self._get_current_version, target, populated_check, force=force)
futures_to_result[future] = (target, populated_check)
except exceptions.UnknownCheckType:
self._logger.warn("Unknown update check type for target {}: {}".format(target,
check.get("type",
"<n/a>")))
continue
except:
self._logger.exception("Could not check {} for updates".format(target))
continue
update_available = update_available or target_update_available for future in futures.as_completed(futures_to_result):
update_possible = update_possible or (target_update_possible and target_update_available)
local_name = target_information["local"]["name"] target, populated_check = futures_to_result[future]
local_value = target_information["local"]["value"] if future.exception() is not None:
self._logger.error("Could not check {} for updates, error: {!r}".format(target,
future.exception()))
continue
release_notes = None target_information, target_update_available, target_update_possible, target_online, target_error = future.result()
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: target_information = dict_merge(dict(local=dict(name="?", value="?"),
release_notes = release_notes.format(octoprint_version=VERSION, remote=dict(name="?", value="?",
target_name=target_information["remote"]["name"], release_notes=None),
target_version=target_information["remote"]["value"]) needs_online=True), target_information)
information[target] = dict(updateAvailable=target_update_available, update_available = update_available or target_update_available
updatePossible=target_update_possible, update_possible = update_possible or (target_update_possible and target_update_available)
information=target_information,
displayName=populated_check["displayName"], local_name = target_information["local"]["name"]
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION, local_name=local_name, local_value=local_value), local_value = target_information["local"]["value"]
check=populated_check,
releaseNotes=release_notes) release_notes = None
if target_information and target_information["remote"] and target_information["remote"][
"value"]:
if "release_notes" in populated_check and populated_check["release_notes"]:
release_notes = populated_check["release_notes"]
elif "release_notes" in target_information["remote"]:
release_notes = target_information["remote"]["release_notes"]
if release_notes:
release_notes = release_notes.format(octoprint_version=VERSION,
target_name=target_information["remote"]["name"],
target_version=target_information["remote"]["value"])
information[target] = dict(updateAvailable=target_update_available,
updatePossible=target_update_possible,
information=target_information,
displayName=populated_check["displayName"],
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION,
local_name=local_name,
local_value=local_value),
releaseNotes=release_notes,
online=target_online,
error=target_error)
if self._version_cache_dirty:
self._save_version_cache()
self._get_versions_data = information, update_available, update_possible
self._get_versions_data_ready.set()
finally:
self._get_versions_mutex.release()
else: # something's already in progress, let's wait for it to complete and use its result
self._get_versions_data_ready.wait()
information, update_available, update_possible = self._get_versions_data
if self._version_cache_dirty:
self._save_version_cache()
return information, update_available, update_possible return information, update_available, update_possible
def _get_check_hash(self, check): def _get_check_hash(self, check):
@@ -650,36 +698,50 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
hash.update(dict_to_sorted_repr(check)) hash.update(dict_to_sorted_repr(check))
return hash.hexdigest() return hash.hexdigest()
def _get_current_version(self, target, check, force=False): def _get_current_version(self, target, check, force=False, online=None):
""" """
Determines the current version information for one target based on its check configuration. Determines the current version information for one target based on its check configuration.
""" """
current_hash = self._get_check_hash(check) 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: if target in self._version_cache and not force:
data = self._version_cache[target] data = self._version_cache[target]
if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]: if data["hash"] == current_hash \
and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"] \
and data.get("online", None) == online:
# we also check that timestamp < now to not get confused too much by clock changes # we also check that timestamp < now to not get confused too much by clock changes
return data["information"], data["available"], data["possible"] return data["information"], data["available"], data["possible"], data["online"], data.get("error", None)
information = dict() information = dict()
update_available = False update_available = False
error = None
try: try:
version_checker = self._get_version_checker(target, check) version_checker = self._get_version_checker(target, check)
information, is_current = version_checker.get_latest(target, check) information, is_current = version_checker.get_latest(target, check, online=online)
if information is not None and not is_current: if information is not None and not is_current:
update_available = True update_available = True
except exceptions.CannotCheckOffline:
update_possible = False
information["needs_online"] = True
except exceptions.UnknownCheckType: except exceptions.UnknownCheckType:
self._logger.warn("Unknown check type %s for %s" % (check["type"], target)) self._logger.warn("Unknown check type %s for %s" % (check["type"], target))
update_possible = False 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: except:
self._logger.exception("Could not check %s for updates" % target) self._logger.exception("Could not check %s for updates" % target)
update_possible = False update_possible = False
error = "unknown"
else: else:
try: try:
updater = self._get_updater(target, check) updater = self._get_updater(target, check)
update_possible = updater.can_perform_update(target, check) update_possible = updater.can_perform_update(target, check, online=online)
except: except:
update_possible = False update_possible = False
@@ -687,9 +749,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
hash=current_hash, hash=current_hash,
information=information, information=information,
available=update_available, available=update_available,
possible=update_possible) possible=update_possible,
online=online,
error=error)
self._version_cache_dirty = True self._version_cache_dirty = True
return information, update_available, update_possible return information, update_available, update_possible, online, error
def perform_updates(self, check_targets=None, force=False): def perform_updates(self, check_targets=None, force=False):
""" """
@@ -801,7 +865,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._send_client_message("success", dict(results=target_results)) self._send_client_message("success", dict(results=target_results))
def _perform_update(self, target, check, force): def _perform_update(self, target, check, force):
information, update_available, update_possible = self._get_current_version(target, check) online = self._connectivity_checker.online
information, update_available, update_possible, _, _ = self._get_current_version(target, check, online=online)
if not update_available and not force: if not update_available and not force:
return False, None return False, None
@@ -824,7 +890,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if updater is None: if updater is None:
raise exceptions.UnknownUpdateType() raise exceptions.UnknownUpdateType()
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log) update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log, online=online)
target_result = ("success", update_result) target_result = ("success", update_result)
self._logger.info("Update of %s to %s successful!" % (target, target_version)) self._logger.info("Update of %s to %s successful!" % (target, target_version))
@@ -833,6 +899,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="Unknown update type")) self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="Unknown update type"))
return False, None 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: except Exception as e:
self._logger.exception("Update of %s can not be performed" % target) self._logger.exception("Update of %s can not be performed" % target)
if not "ignorable" in populated_check or not populated_check["ignorable"]: if not "ignorable" in populated_check or not populated_check["ignorable"]:
+31 -9
View File
@@ -9,12 +9,14 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
import click import click
import sys import sys
import requests.exceptions import requests.exceptions
import octoprint_client as client from octoprint.cli.client import create_client, client_options
@click.command("check") @click.command("check")
@click.option("--force", is_flag=True, help="Ignore the cache for the update 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) @click.argument("targets", nargs=-1)
def check_command(force, targets): def check_command(force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets):
""" """
Check for updates. Check for updates.
@@ -37,7 +39,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
if targets: if targets:
params["check"] = ",".join(targets) params["check"] = ",".join(targets)
client.init_client(cli_group.settings) client = create_client(settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
r = client.get("plugin/softwareupdate/check", params=params) r = client.get("plugin/softwareupdate/check", params=params)
try: try:
r.raise_for_status() r.raise_for_status()
@@ -58,10 +68,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
status_text = "Update available" status_text = "Update available"
else: else:
status_text = "Update available (manual)" status_text = "Update available (manual)"
line = "{}\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
info["information"]["local"]["name"], elif only_new:
info["information"]["remote"]["name"], continue
status_text)
line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
key,
info["information"]["local"]["name"],
info["information"]["remote"]["name"],
status_text)
if key == "octoprint": if key == "octoprint":
octoprint_line = line octoprint_line = line
else: else:
@@ -83,8 +98,9 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
@click.command("update") @click.command("update")
@click.option("--force", is_flag=True, help="Update even if already up to date") @click.option("--force", is_flag=True, help="Update even if already up to date")
@client_options
@click.argument("targets", nargs=-1) @click.argument("targets", nargs=-1)
def update_command(force, targets): def update_command(force, apikey, host, port, httpuser, httppass, https, prefix, targets):
""" """
Apply updates. Apply updates.
@@ -108,7 +124,13 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
if targets: if targets:
data["check"] = targets data["check"] = targets
client.init_client(cli_group.settings) client = create_client(apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
flags = dict( flags = dict(
waiting_for_restart=False, waiting_for_restart=False,
@@ -18,6 +18,20 @@ class UnknownUpdateType(Exception):
class UnknownCheckType(Exception): class UnknownCheckType(Exception):
pass 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): class UpdateError(Exception):
def __init__(self, message, data): def __init__(self, message, data):
self.message = message self.message = message
@@ -35,3 +49,8 @@ class RestartFailed(Exception):
class ConfigurationInvalid(Exception): class ConfigurationInvalid(Exception):
pass pass
class CannotCheckOffline(Exception):
pass
class CannotUpdateOffline(Exception):
pass
@@ -1 +1 @@
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block} td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
@@ -417,6 +417,42 @@ $(function() {
}); });
}; };
self.iconTitleForEntry = function(data) {
if (data.updatePossible) {
return "";
} else if (!data.online && data.information && data.information.needs_online) {
return gettext("No internet connection");
} else if (data.error) {
return self.errorTextForEntry(data);
} else {
return gettext("Update not possible");
}
};
self.errorTextForEntry = function(data) {
if (!data.error) {
return "";
}
switch (data.error) {
case "unknown_check": {
return gettext("Unknown update check, configuration ok?");
}
case "needs_online": {
return gettext("Cannot check for update, need online connection");
}
case "network": {
return gettext("Network error while checking for update");
}
case "unknown": {
return gettext("Unknown error while checking for update, please check the logs");
}
default: {
return "";
}
}
};
self._markNotificationAsSeen = function(data) { self._markNotificationAsSeen = function(data) {
if (!Modernizr.localstorage) if (!Modernizr.localstorage)
return false; return false;
@@ -607,6 +643,11 @@ $(function() {
return true; return true;
}; };
self.onEventConnectivityChanged = function(payload) {
if (!payload || !payload.new) return;
self.performCheck();
};
self.onDataUpdaterReconnect = function() { self.onDataUpdaterReconnect = function() {
if (self.waitingForRestart) { if (self.waitingForRestart) {
self.waitingForRestart = false; self.waitingForRestart = false;
@@ -2,6 +2,12 @@ td.settings_plugin_softwareupdate_column_update {
width: 16px; width: 16px;
} }
td.settings_plugin_softwareupdate_column_information {
.line {
display: block;
}
}
#settings_plugin_softwareupdate_workingdialog_output { #settings_plugin_softwareupdate_workingdialog_output {
font-size: 0.8em; font-size: 0.8em;
@@ -29,11 +29,12 @@
<span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" title="{{ _('Update available') }}"></i></span> <span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" title="{{ _('Update available') }}"></i></span>
</td> </td>
<td class="settings_plugin_softwareupdate_column_information"> <td class="settings_plugin_softwareupdate_column_information">
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br> <strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
<small class="muted"> <small class="muted">
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br> <span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span><br> <span class="line">{{ _('Available:') }} <span data-bind="text: information.remote.name"></span></span>
<span data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span> <span class="line" data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
<span class="line text-error" data-bind="visible: error, text: $root.errorTextForEntry($data)"></span>
</small> </small>
</td> </td>
</tr> </tr>
@@ -18,9 +18,9 @@ console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pi
_pip_callers = dict() _pip_callers = dict()
_pip_version_dependency_links = pkg_resources.parse_version("1.5") _pip_version_dependency_links = pkg_resources.parse_version("1.5")
def can_perform_update(target, check): def can_perform_update(target, check, online=True):
pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None) pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None)
return "pip" in check and pip_caller is not None and pip_caller.available return "pip" in check and pip_caller is not None and pip_caller.available and (online or check.get("offline", False))
def _get_pip_caller(command=None): def _get_pip_caller(command=None):
key = command key = command
@@ -35,11 +35,14 @@ def _get_pip_caller(command=None):
return _pip_callers[key] return _pip_callers[key]
def perform_update(target, check, target_version, log_cb=None): def perform_update(target, check, target_version, log_cb=None, online=True):
pip_command = None pip_command = None
if "pip_command" in check: if "pip_command" in check:
pip_command = check["pip_command"] 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) pip_caller = _get_pip_caller(command=pip_command)
if pip_caller is None: if pip_caller is None:
raise exceptions.UpdateError("Can't run pip", None) raise exceptions.UpdateError("Can't run pip", None)
@@ -6,9 +6,24 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
def can_perform_update(target, check): 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") return "python_updater" in check and check["python_updater"] is not None and hasattr(check["python_updater"], "perform_update") and (online or check.get("offline", False))
def perform_update(target, check, target_version, log_cb=None): def perform_update(target, check, target_version, log_cb=None, online=True):
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb) from ..exceptions import CannotUpdateOffline
if not online and not check("offline", False):
raise CannotUpdateOffline()
try:
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb, online=online)
except:
import inspect
args, _, _, _ = inspect.getargspec(check["python_updater"].perform_update)
if "online" not in args:
# old python_updater footprint, simply leave out the online parameter
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb)
# some other error, raise again
raise
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import sys import sys
import logging import logging
from ..exceptions import ConfigurationInvalid, UpdateError from ..exceptions import ConfigurationInvalid, UpdateError, CannotUpdateOffline
from octoprint.util.commandline import CommandlineCaller, CommandlineError from octoprint.util.commandline import CommandlineCaller, CommandlineError
@@ -36,7 +36,7 @@ def _get_caller(log_cb=None):
return caller return caller
def can_perform_update(target, check): def can_perform_update(target, check, online=True):
import os import os
script_configured = bool("update_script" in check and check["update_script"]) script_configured = bool("update_script" in check and check["update_script"])
@@ -47,12 +47,15 @@ def can_perform_update(target, check):
folder = check["checkout_folder"] folder = check["checkout_folder"]
folder_configured = bool(folder and os.path.isdir(folder)) folder_configured = bool(folder and os.path.isdir(folder))
return script_configured and folder_configured return script_configured and folder_configured and (online or check.get("offline", False))
def perform_update(target, check, target_version, log_cb=None): def perform_update(target, check, target_version, log_cb=None, online=True):
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.update_script") 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): if not can_perform_update(target, check):
raise ConfigurationInvalid("checkout_folder and update_folder are missing for update target %s, one is needed" % target) raise ConfigurationInvalid("checkout_folder and update_folder are missing for update target %s, one is needed" % target)
@@ -6,15 +6,26 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
import requests import requests
import logging import logging
import base64
from ..exceptions import ConfigurationInvalid
BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}" BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit") logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit")
def _get_latest_commit(user, repo, branch):
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch)) def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
from ..exceptions import NetworkError
url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch)
headers = {}
if api_user is not None and api_password is not None:
auth_value = base64.b64encode(b"{user}:{pw}".format(user=api_user, pw=api_password))
headers["authorization"] = "Basic {}".format(auth_value)
try:
r = requests.get(url, headers=headers, timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
if not r.status_code == requests.codes.ok: if not r.status_code == requests.codes.ok:
return None return None
@@ -26,24 +37,33 @@ def _get_latest_commit(user, repo, branch):
return reference["hash"] return reference["hash"]
def get_latest(target, check): def get_latest(target, check, online=True):
from ..exceptions import ConfigurationInvalid
if "user" not in check or "repo" not in check: 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) raise ConfigurationInvalid("Update configuration for %s of type bitbucket_commit needs all of user and repo" % target)
branch = "master" branch = "master"
if "branch" in check: if "branch" in check and check["branch"] is not None:
branch = check["branch"] branch = check["branch"]
current = None api_user = check.get("api_user")
if "current" in check: api_password = check.get("api_password")
current = check["current"]
remote_commit = _get_latest_commit(check["user"], check["repo"], branch) current = check.get("current")
information = dict( information = dict(
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current), local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
remote=dict(name="Commit {commit}".format(commit=remote_commit if remote_commit is not None else "unknown"), value=remote_commit) remote=dict(name="?", value="?"),
needs_online=not check.get("offline", False)
) )
if not online and information["needs_online"]:
return information, True
remote_commit = _get_latest_commit(check["user"], check["repo"], branch, api_user, api_password)
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
information["remote"] = dict(name=remote_name, value=remote_commit)
is_current = (current is not None and current == remote_commit) or remote_commit is None 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)) logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
@@ -8,14 +8,17 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging import logging
from ..exceptions import ConfigurationInvalid from ..exceptions import ConfigurationInvalid, CannotCheckOffline
from ..util import execute from ..util import execute
def get_latest(target, check): def get_latest(target, check, online=True):
command = check.get("command") command = check.get("command")
if command is None: if command is None:
raise ConfigurationInvalid("Update configuration for {} of type commandline needs command set and not None".format(target)) 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) returncode, stdout, stderr = execute(command, evaluate_returncode=False)
# We expect command line check commands to # We expect command line check commands to
@@ -47,38 +47,40 @@ def _git(args, cwd, hide_stderr=False):
return p.returncode, stdout return p.returncode, stdout
def get_latest(target, check): def get_latest(target, check, online=True):
checkout_folder = check.get("checkout_folder") checkout_folder = check.get("checkout_folder")
if checkout_folder is None: if checkout_folder is None:
raise ConfigurationInvalid("Update configuration for {} of type git_commit needs checkout_folder set and not None".format(target)) 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) returncode, local_commit = _git(["rev-parse", "@{0}"], checkout_folder)
if returncode != 0: if returncode != 0:
return None, True 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) returncode, remote_commit = _git(["rev-parse", "@{u}"], checkout_folder)
if returncode != 0: if returncode != 0:
return None, True return information, True
returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder) returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
if returncode != 0: if returncode != 0:
return None, True return information, True
if local_commit == remote_commit or remote_commit == base: if local_commit == remote_commit or remote_commit == base:
information = dict( information["remote"] = dict(name="Commit %s" % local_commit, value=local_commit)
local=dict(name="Commit %s" % local_commit, value=local_commit),
remote=dict(name="Commit %s" % local_commit, value=local_commit)
)
is_current = True is_current = True
else: else:
information = dict( information["remote"] = dict(name="Commit %s" % remote_commit, value=remote_commit)
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 is_current = local_commit == remote_commit
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.git_commit") logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.git_commit")
@@ -8,14 +8,17 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import requests import requests
import logging import logging
from ..exceptions import ConfigurationInvalid
BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{branch}" BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{branch}"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit") logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit")
def _get_latest_commit(user, repo, branch): def _get_latest_commit(user, repo, branch):
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=30) from ..exceptions import NetworkError
try:
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
from . import log_github_ratelimit from . import log_github_ratelimit
log_github_ratelimit(logger, r) log_github_ratelimit(logger, r)
@@ -30,7 +33,9 @@ def _get_latest_commit(user, repo, branch):
return reference["object"]["sha"] return reference["object"]["sha"]
def get_latest(target, check): def get_latest(target, check, online=True):
from ..exceptions import ConfigurationInvalid
user = check.get("user") user = check.get("user")
repo = check.get("repo") repo = check.get("repo")
@@ -41,16 +46,18 @@ def get_latest(target, check):
if "branch" in check and check["branch"] is not None: if "branch" in check and check["branch"] is not None:
branch = check["branch"] branch = check["branch"]
current = None current = check.get("current")
if "current" in check:
current = check["current"] information = dict(local=dict(name="Commit {commit}".format(commit=current if current is not None else "?"), value=current),
remote=dict(name="?", value="?"),
needs_online=not check.get("offline", False))
if not online and information["needs_online"]:
return information, True
remote_commit = _get_latest_commit(check["user"], check["repo"], branch) remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
information = dict( information["remote"] = dict(name=remote_name, value=remote_commit)
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 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)) logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
@@ -96,8 +96,14 @@ def _get_latest_release(user, repo, compare_type,
include_prerelease=False, include_prerelease=False,
commitish=None, commitish=None,
force_base=True): force_base=True):
from ..exceptions import NetworkError
nothing = None, None, None nothing = None, None, None
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=30)
try:
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
from . import log_github_ratelimit from . import log_github_ratelimit
log_github_ratelimit(logger, r) log_github_ratelimit(logger, r)
@@ -258,7 +264,7 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
return True return True
def get_latest(target, check, custom_compare=None): def get_latest(target, check, custom_compare=None, online=True):
from ..exceptions import ConfigurationInvalid from ..exceptions import ConfigurationInvalid
user = check.get("user", None) user = check.get("user", None)
@@ -267,6 +273,14 @@ def get_latest(target, check, custom_compare=None):
if user is None or repo is None or current is None: if user is None or repo is None or current is None:
raise ConfigurationInvalid("Update configuration for {} of type github_release needs all of user, repo and current set and not None".format(target)) 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) include_prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None) prerelease_channel = check.get("prerelease_channel", None)
@@ -290,10 +304,13 @@ def get_latest(target, check, custom_compare=None):
commitish=commitish, commitish=commitish,
force_base=force_base) force_base=force_base)
information =dict( if remote_name is None:
local=dict(name=current, value=current), if remote_tag is not None:
remote=dict(name=remote_name, value=remote_tag, release_notes=release_notes) remote_name = remote_tag
) else:
remote_name = "-"
information["remote"] = dict(name=remote_name, value=remote_tag, release_notes=release_notes)
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag)) logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
@@ -5,11 +5,24 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __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" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from ..exceptions import ConfigurationInvalid from ..exceptions import ConfigurationInvalid, CannotCheckOffline
def get_latest(target, check, full_data=False): def get_latest(target, check, full_data=False, online=True):
python_checker = check.get("python_checker") python_checker = check.get("python_checker")
if python_checker is None or not hasattr(python_checker, "get_latest"): 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)) raise ConfigurationInvalid("Update configuration for {} of type python_checker needs python_checker defined and have an attribute \"get_latest\"".format(target))
return check["python_checker"].get_latest(target, check, full_data=full_data) if not online and not check.get("offline", False):
raise CannotCheckOffline("{} isn't marked as 'offline' capable, but we are apparently offline right now".format(target))
try:
return check["python_checker"].get_latest(target, check, full_data=full_data, online=online)
except:
import inspect
args, _, _, _ = inspect.getargspec(check["python_checker"].get_latest)
if "online" not in args:
# old python_checker footprint, simply leave out the online parameter
return check["python_checker"].get_latest(target, check, full_data=full_data)
# some other error, raise again
raise
@@ -65,6 +65,9 @@ class VirtualPrinter(object):
self.currentExtruder = 0 self.currentExtruder = 0
self.extruderCount = settings().getInt(["devel", "virtualPrinter", "numExtruders"]) 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.sharedNozzle = settings().getBoolean(["devel", "virtualPrinter", "sharedNozzle"])
self.temperatureCount = (1 if self.sharedNozzle else self.extruderCount) self.temperatureCount = (1 if self.sharedNozzle else self.extruderCount)
@@ -1001,6 +1004,10 @@ class VirtualPrinter(object):
timeDiff = self.lastTempAt - time.time() timeDiff = self.lastTempAt - time.time()
self.lastTempAt = time.time() self.lastTempAt = time.time()
for i in range(len(self.temp)): 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: if abs(self.temp[i] - self.targetTemp[i]) > delta:
oldVal = self.temp[i] oldVal = self.temp[i]
self.temp[i] += math.copysign(timeDiff * 10, self.targetTemp[i] - self.temp[i]) self.temp[i] += math.copysign(timeDiff * 10, self.targetTemp[i] - self.temp[i])
+36 -15
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 (2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation
""" """
if progress is None or printTime is None or cleanedPrintTime is None: if progress is None or progress == 0 or printTime is None or cleanedPrintTime is None:
return None, None return None, None
dumbTotalPrintTime = printTime / progress dumbTotalPrintTime = printTime / progress
@@ -1000,7 +1000,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
with self._selectedFileMutex: with self._selectedFileMutex:
if self._selectedFile is not None: 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: if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_ERROR or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"]) def log_print():
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL,
self._selectedFile["filename"],
time.time(),
self._comm.getPrintTime(),
False,
self._printerProfileManager.get_current_or_default()["id"])
thread = threading.Thread(target=log_print)
thread.daemon = True
thread.start()
self._analysisQueue.resume() # printing done, put those cpu cycles to good use self._analysisQueue.resume() # printing done, put those cpu cycles to good use
elif state == comm.MachineCom.STATE_PRINTING: elif state == comm.MachineCom.STATE_PRINTING:
self._analysisQueue.pause() # do not analyse files while printing self._analysisQueue.pause() # do not analyse files while printing
@@ -1091,12 +1101,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
context=dict(event=payload), context=dict(event=payload),
must_be_set=False) must_be_set=False)
self._fileManager.log_print(payload["origin"], def log_print():
payload["path"], self._fileManager.log_print(payload["origin"],
time.time(), payload["path"],
payload["time"], time.time(),
True, payload["time"],
self._printerProfileManager.get_current_or_default()["id"]) True,
self._printerProfileManager.get_current_or_default()["id"])
thread = threading.Thread(target=log_print)
thread.daemon = True
thread.start()
else: else:
self._updateProgressData() self._updateProgressData()
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()}) self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
@@ -1119,13 +1135,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
context=dict(event=payload), context=dict(event=payload),
must_be_set=False) must_be_set=False)
self._fileManager.log_print(payload["origin"], def finalize():
payload["path"], self._fileManager.log_print(payload["origin"],
time.time(), payload["path"],
payload["time"], time.time(),
False, payload["time"],
self._printerProfileManager.get_current_or_default()["id"]) False,
eventManager().fire(Events.PRINT_FAILED, payload) self._printerProfileManager.get_current_or_default()["id"])
eventManager().fire(Events.PRINT_FAILED, payload)
thread = threading.Thread(target=finalize)
thread.daemon = True
thread.start()
def on_comm_print_job_paused(self): 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) payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None)
+135 -10
View File
@@ -7,9 +7,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import uuid import uuid
from sockjs.tornado import SockJSRouter from sockjs.tornado import SockJSRouter
from flask import Flask, g, request, session, Blueprint, Request, Response from flask import Flask, g, request, session, Blueprint, Request, Response, current_app
from flask.ext.login import LoginManager, current_user from flask.ext.login import LoginManager, current_user, session_protected, user_logged_out
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, AnonymousIdentity
from flask.ext.babel import Babel, gettext, ngettext from flask.ext.babel import Babel, gettext, ngettext
from flask.ext.assets import Environment, Bundle from flask.ext.assets import Environment, Bundle
from babel import Locale from babel import Locale
@@ -27,6 +27,11 @@ import atexit
import signal import signal
import base64 import base64
try:
import fcntl
except ImportError:
fcntl = None
SUCCESS = {} SUCCESS = {}
NO_CONTENT = ("", 204) NO_CONTENT = ("", 204)
NOT_MODIFIED = ("Not Modified", 304) NOT_MODIFIED = ("Not Modified", 304)
@@ -49,6 +54,7 @@ pluginManager = None
appSessionManager = None appSessionManager = None
pluginLifecycleManager = None pluginLifecycleManager = None
preemptiveCache = None preemptiveCache = None
connectivityChecker = None
principals = Principal(app) principals = Principal(app)
admin_permission = Permission(RoleNeed("admin")) admin_permission = Permission(RoleNeed("admin"))
@@ -96,6 +102,29 @@ def on_identity_loaded(sender, identity):
if user.is_admin(): if user.is_admin():
identity.provides.add(RoleNeed("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): def load_user(id):
if id == "_api": if id == "_api":
return users.ApiUser() return users.ApiUser()
@@ -160,6 +189,7 @@ class Server(object):
global appSessionManager global appSessionManager
global pluginLifecycleManager global pluginLifecycleManager
global preemptiveCache global preemptiveCache
global connectivityChecker
global debug global debug
global safe_mode global safe_mode
@@ -189,6 +219,16 @@ class Server(object):
# start the intermediary server # start the intermediary server
self._start_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 # then initialize the plugin manager
pluginManager.reload_plugins(startup=True, initialize_implementations=False) pluginManager.reload_plugins(startup=True, initialize_implementations=False)
@@ -205,6 +245,40 @@ class Server(object):
pluginLifecycleManager = LifecycleManager(pluginManager) pluginLifecycleManager = LifecycleManager(pluginManager)
preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml")) 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 # setup access control
userManagerName = self._settings.get(["accessControl", "userManager"]) userManagerName = self._settings.get(["accessControl", "userManager"])
try: try:
@@ -225,10 +299,33 @@ class Server(object):
file_manager=fileManager, file_manager=fileManager,
app_session_manager=appSessionManager, app_session_manager=appSessionManager,
plugin_lifecycle_manager=pluginLifecycleManager, plugin_lifecycle_manager=pluginLifecycleManager,
user_manager=userManager, preemptive_cache=preemptiveCache,
preemptive_cache=preemptiveCache connectivity_checker=connectivityChecker
) )
# create user manager instance
user_manager_factories = pluginManager.get_hooks("octoprint.users.factory")
for name, factory in user_manager_factories.items():
try:
userManager = factory(components, self._settings)
if userManager is not None:
self._logger.debug("Created user manager instance from factory {}".format(name))
break
except:
self._logger.exception("Error while creating user manager instance from factory {}".format(name))
else:
name = self._settings.get(["accessControl", "userManager"])
try:
clazz = octoprint.util.get_class(name)
userManager = clazz()
except:
self._logger.exception(
"Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name))
userManager = octoprint.users.FilebasedUserManager()
finally:
userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"])
components.update(dict(user_manager=userManager))
# create printer instance # create printer instance
printer_factories = pluginManager.get_hooks("octoprint.printer.factory") printer_factories = pluginManager.get_hooks("octoprint.printer.factory")
for name, factory in printer_factories.items(): for name, factory in printer_factories.items():
@@ -487,8 +584,13 @@ class Server(object):
self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=self._settings.getInt(["server", "maxSize"])) self._server = 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) self._server.listen(self._port, address=self._host)
### From now on it's ok to launch subprocesses again
eventManager.fire(events.Events.STARTUP) eventManager.fire(events.Events.STARTUP)
# analysis backlog
fileManager.process_backlog()
# auto connect # auto connect
if self._settings.getBoolean(["serial", "autoconnect"]): if self._settings.getBoolean(["serial", "autoconnect"]):
try: try:
@@ -1274,21 +1376,44 @@ class Server(object):
rules = map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules)) rules = map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))
self._intermediary_server = BaseHTTPServer.HTTPServer((host, port), lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs)) self._intermediary_server = BaseHTTPServer.HTTPServer((host, port),
lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs),
bind_and_activate=False)
thread = threading.Thread(target=self._intermediary_server.serve_forever) # 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.daemon = True thread.daemon = True
thread.start() thread.start()
self._logger.debug("Intermediary server started") self._logger.info("Intermediary server started")
def _stop_intermediary_server(self): def _stop_intermediary_server(self):
if self._intermediary_server is None: if self._intermediary_server is None:
return return
self._logger.debug("Shutting down intermediary server...") self._logger.info("Shutting down intermediary server...")
self._intermediary_server.shutdown() self._intermediary_server.shutdown()
self._intermediary_server.server_close() self._intermediary_server.server_close()
self._logger.debug("Intermediary server shut down") self._logger.info("Intermediary server shut down")
class LifecycleManager(object): class LifecycleManager(object):
def __init__(self, plugin_manager): def __init__(self, plugin_manager):
+5 -6
View File
@@ -222,22 +222,21 @@ def login():
@api.route("/logout", methods=["POST"]) @api.route("/logout", methods=["POST"])
@restricted_access @restricted_access
def logout(): def logout():
# Remove session keys set by Flask-Principal # logout from user manager...
for key in ('identity.id', 'identity.name', 'identity.auth_type'):
if key in session:
del session[key]
identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
_logout(current_user) _logout(current_user)
# ... and from flask login (and principal)
logout_user() logout_user()
return NO_CONTENT return NO_CONTENT
def _logout(user): def _logout(user):
if "usersession.id" in session: if "usersession.id" in session:
del session["usersession.id"] del session["usersession.id"]
octoprint.server.userManager.logout_user(user) octoprint.server.userManager.logout_user(user)
@api.route("/util/test", methods=["POST"]) @api.route("/util/test", methods=["POST"])
@restricted_access @restricted_access
@admin_permission.require(403) @admin_permission.require(403)
+12
View File
@@ -464,6 +464,7 @@ def gcodeFileCommand(filename, target):
valid_commands = { valid_commands = {
"select": [], "select": [],
"slice": [], "slice": [],
"analyse": [],
"copy": ["destination"], "copy": ["destination"],
"move": ["destination"] "move": ["destination"]
} }
@@ -616,6 +617,17 @@ def gcodeFileCommand(filename, target):
r.headers["Location"] = location r.headers["Location"] = location
return r 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": elif command == "copy" or command == "move":
# Copy and move are only possible on local storage # Copy and move are only possible on local storage
if not target in [FileDestinations.LOCAL]: if not target in [FileDestinations.LOCAL]:
+20
View File
@@ -154,6 +154,8 @@ def getSettings():
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]), "ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]), "disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]), "triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
"logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]),
"logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]),
"supportResendsWithoutOk": s.getBoolean(["serial", "supportResendsWithoutOk"]), "supportResendsWithoutOk": s.getBoolean(["serial", "supportResendsWithoutOk"]),
"maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]), "maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]),
"maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]), "maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]),
@@ -200,6 +202,12 @@ def getSettings():
"diskspace": { "diskspace": {
"warning": s.getInt(["server", "diskspace", "warning"]), "warning": s.getInt(["server", "diskspace", "warning"]),
"critical": s.getInt(["server", "diskspace", "critical"]) "critical": s.getInt(["server", "diskspace", "critical"])
},
"onlineCheck": {
"enabled": s.getBoolean(["server", "onlineCheck", "enabled"]),
"interval": int(s.getInt(["server", "onlineCheck", "interval"]) / 60),
"host": s.get(["server", "onlineCheck", "host"]),
"port": s.getInt(["server", "onlineCheck", "port"])
} }
} }
} }
@@ -365,6 +373,8 @@ def _saveSettings(data):
if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"]) if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"])
if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"]) 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 "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 "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 "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"]) if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"])
@@ -415,6 +425,16 @@ def _saveSettings(data):
if "diskspace" in data["server"]: if "diskspace" in data["server"]:
if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"]) 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 "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: if "plugins" in data:
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin): for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
+46 -16
View File
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import collections import collections
import logging import logging
import sarge import sarge
import threading
from flask import request, make_response, jsonify, url_for from flask import request, make_response, jsonify, url_for
from flask.ext.babel import gettext from flask.ext.babel import gettext
@@ -16,6 +17,7 @@ from octoprint.settings import settings as s
from octoprint.server import admin_permission, NO_CONTENT from octoprint.server import admin_permission, NO_CONTENT
from octoprint.server.api import api from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access, get_remote_address from octoprint.server.util.flask import restricted_access, get_remote_address
from octoprint.logging import prefix_multilines
@api.route("/system", methods=["POST"]) @api.route("/system", methods=["POST"])
@@ -74,38 +76,59 @@ def executeSystemCommand(source, command):
do_async = command_spec.get("async", False) do_async = command_spec.get("async", False)
do_ignore = command_spec.get("ignore", False) do_ignore = command_spec.get("ignore", False)
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"])) debug = command_spec.get("debug", False)
if logger.isEnabledFor(logging.DEBUG) or debug:
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
else:
logger.info("Performing command for {}:{}".format(source, command))
try: try:
if "before" in command_spec and callable(command_spec["before"]): if "before" in command_spec and callable(command_spec["before"]):
command_spec["before"]() command_spec["before"]()
except Exception as e: except Exception as e:
if not do_ignore: if not do_ignore:
error = "Command \"before\" failed: {}".format(str(e)) error = "Command \"before\" for {}:{} failed: {}".format(source, command, str(e))
logger.warn(error) logger.warn(error)
return make_response(error, 500) return make_response(error, 500)
try: try:
# we run this with shell=True since we have to trust whatever def execute():
# our admin configured as command and since we want to allow # we run this with shell=True since we have to trust whatever
# shell-alike handling here... # our admin configured as command and since we want to allow
p = sarge.run(command_spec["command"], # shell-alike handling here...
stdout=sarge.Capture(), p = sarge.run(command_spec["command"],
stderr=sarge.Capture(), stdout=sarge.Capture(),
shell=True, stderr=sarge.Capture(),
async=do_async) shell=True)
if not do_async:
if not do_ignore and p.returncode != 0: if not do_ignore and p.returncode != 0:
returncode = p.returncode returncode = p.returncode
stdout_text = p.stdout.text stdout_text = p.stdout.text
stderr_text = p.stderr.text stderr_text = p.stderr.text
error = "Command failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(returncode, stdout_text, stderr_text) error = "Command for {}:{} failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(source, command,
logger.warn(error) returncode,
return make_response(error, 500) stdout_text,
stderr_text)
logger.warn(prefix_multilines(error, prefix="! "))
if not do_async:
raise CommandFailed(error)
if do_async:
thread = threading.Thread(target=execute)
thread.daemon = True
thread.start()
else:
try:
execute()
except CommandFailed as exc:
return make_response(exc.error, 500)
except Exception as e: except Exception as e:
if not do_ignore: if not do_ignore:
error = "Command failed: {}".format(str(e)) error = "Command for {}:{} failed: {}".format(source, command, str(e))
logger.warn(error) logger.warn(error)
return make_response(error, 500) return make_response(error, 500)
@@ -164,7 +187,10 @@ def _get_core_command_specs():
for action, spec in commands.items(): for action, spec in commands.items():
if not spec["command"]: if not spec["command"]:
continue continue
spec.update(dict(action=action, source="core", async=True, ignore=True)) spec.update(dict(action=action,
source="core",
async=True,
debug=True))
available_commands[action] = spec available_commands[action] = spec
return available_commands return available_commands
@@ -202,3 +228,7 @@ def _get_custom_command_spec(action):
return available_actions[action] return available_actions[action]
class CommandFailed(Exception):
def __init__(self, error):
self.error = error
+5 -2
View File
@@ -455,9 +455,12 @@ class OctoPrintFlaskRequest(flask.Request):
We need this because cookies are not port-specific and we don't want to overwrite our 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 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. one who happens to listen on the same address albeit a different port or script root.
""" """
return "_P" + self.server_port result = "_P" + self.server_port
if self.script_root:
return result + "_R" + self.script_root.replace("/", "|")
return result
class OctoPrintFlaskResponse(flask.Response): class OctoPrintFlaskResponse(flask.Response):
+15 -1
View File
@@ -21,6 +21,7 @@ from octoprint.server import app, userManager, pluginManager, gettext, \
NOT_MODIFIED NOT_MODIFIED
from octoprint.settings import settings from octoprint.settings import settings
from octoprint.filemanager import get_all_extensions from octoprint.filemanager import get_all_extensions
from octoprint.util import to_unicode
import re import re
import base64 import base64
@@ -460,13 +461,26 @@ def _process_templates():
) )
# sorting orders # 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( template_sorting = dict(
navbar=dict(add="prepend", key=None), navbar=dict(add="prepend", key=None),
sidebar=dict(add="append", key="name"), sidebar=dict(add="append", key="name"),
tab=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), 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"), usersettings=dict(add="append", key="name"),
wizard=dict(add="append", key="name", key_extractor=lambda d, k: "0:{}".format(d[0]) if "mandatory" in d[1] and d[1]["mandatory"] else "1:{}".format(d[0])), wizard=dict(add="append", key="name", key_extractor=wizard_key_extractor),
about=dict(add="append", key="name"), about=dict(add="append", key="name"),
generic=dict(add="append", key=None) generic=dict(add="append", key=None)
) )
+9
View File
@@ -112,6 +112,8 @@ default_settings = {
"ignoreErrorsFromFirmware": False, "ignoreErrorsFromFirmware": False,
"logResends": True, "logResends": True,
"supportResendsWithoutOk": False, "supportResendsWithoutOk": False,
"logPositionOnPause": True,
"logPositionOnCancel": True,
# command specific flags # command specific flags
"triggerOkForM29": True "triggerOkForM29": True
@@ -146,6 +148,12 @@ default_settings = {
"systemRestartCommand": None, "systemRestartCommand": None,
"serverRestartCommand": None "serverRestartCommand": None
}, },
"onlineCheck": {
"enabled": None,
"interval": 15 * 60, # 15 min
"host": "8.8.8.8",
"port": 53
},
"diskspace": { "diskspace": {
"warning": 500 * 1024 * 1024, # 500 MB "warning": 500 * 1024 * 1024, # 500 MB
"critical": 200 * 1024 * 1024, # 200 MB "critical": 200 * 1024 * 1024, # 200 MB
@@ -342,6 +350,7 @@ default_settings = {
"okAfterResend": False, "okAfterResend": False,
"forceChecksum": False, "forceChecksum": False,
"numExtruders": 1, "numExtruders": 1,
"pinnedExtruders": None,
"includeCurrentToolInTemps": True, "includeCurrentToolInTemps": True,
"includeFilenameInOpened": True, "includeFilenameInOpened": True,
"hasBed": True, "hasBed": True,
+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
@@ -325,6 +325,11 @@ var doParse = function () {
extrude = false; extrude = false;
line = line.split(/[\(;]/)[0]; line = line.split(/[\(;]/)[0];
if (!line || line.trim() === "") {
// empty line, skip entirely
continue;
}
var addToModel = false; var addToModel = false;
var move = false; var move = false;
@@ -545,7 +550,7 @@ var doParse = function () {
} }
if (typeof(z) !== 'undefined' && z !== prevZ) { if (typeof(z) !== 'undefined' && z !== prevZ) {
if (z_heights[z]) { if (z_heights[z] !== undefined) {
layer = z_heights[z]; layer = z_heights[z];
} else { } else {
layer = model.length; layer = model.length;
@@ -44,15 +44,12 @@ GCODE.gCodeReader = (function(){
var prepareGCode = function(totalSize){ var prepareGCode = function(totalSize){
if(!lines)return; if(!lines)return;
gcode = []; gcode = [];
var i, tmp, byteCount; var i, byteCount;
byteCount = 0; byteCount = 0;
for(i=0;i<lines.length;i++){ for(i=0;i<lines.length;i++){
byteCount += lines[i].length + 1; // line length + \n byteCount += lines[i].length + 1; // line length + line ending
tmp = lines[i].indexOf(";"); gcode.push({line: lines[i], percentage: byteCount * 100 / totalSize});
if(tmp > 1 || tmp === -1) {
gcode.push({line: lines[i], percentage: byteCount * 100 / totalSize});
}
} }
lines = []; lines = [];
}; };
@@ -146,7 +143,7 @@ GCODE.gCodeReader = (function(){
this.clear(); this.clear();
var totalSize = reader.target.result.length; var totalSize = reader.target.result.length;
lines = reader.target.result.split(/\n/); lines = reader.target.result.split(/[\r\n]/g);
reader.target.result = null; reader.target.result = null;
prepareGCode(totalSize); prepareGCode(totalSize);
@@ -89,6 +89,10 @@
return this.issueEntryCommand(location, path, "select", data, opts); 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) { OctoPrintFilesClient.prototype.slice = function (location, path, parameters, opts) {
return this.issueEntryCommand(location, path, "slice", return this.issueEntryCommand(location, path, "slice",
parameters || {}, opts); parameters || {}, opts);
+3
View File
@@ -1000,10 +1000,13 @@ function setOnViewModelsIf(allViewModels, key, value, condition) {
} }
function callViewModels(allViewModels, method, callback) { function callViewModels(allViewModels, method, callback) {
if (!allViewModels) return;
callViewModelsIf(allViewModels, method, undefined, callback); callViewModelsIf(allViewModels, method, undefined, callback);
} }
function callViewModelsIf(allViewModels, method, condition, callback) { function callViewModelsIf(allViewModels, method, condition, callback) {
if (!allViewModels) return;
if (condition == undefined || !_.isFunction(condition)) { if (condition == undefined || !_.isFunction(condition)) {
condition = function() { return true; }; condition = function() { return true; };
} }
@@ -581,7 +581,7 @@ $(function() {
var additionalInfo = $(".additionalInfo", entryElement); var additionalInfo = $(".additionalInfo", entryElement);
additionalInfo.slideToggle("fast", function() { additionalInfo.slideToggle("fast", function() {
$(".toggleAdditionalData i", entryElement).toggleClass("icon-chevron-down icon-chevron-up"); $(".toggleAdditionalData i", entryElement).toggleClass("fa-chevron-down fa-chevron-up");
}); });
}; };
@@ -109,8 +109,7 @@ $(function() {
self.reader_sortLayers.subscribe(self.synchronizeOptions); self.reader_sortLayers.subscribe(self.synchronizeOptions);
self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions); self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions);
// subscribe to relevant printer settings... self._printerProfileUpdated = function() {
self.settings.printerProfiles.currentProfileData.subscribe(function() {
if (!self.enabled) return; if (!self.enabled) return;
var currentProfileData = self.settings.printerProfiles.currentProfileData(); var currentProfileData = self.settings.printerProfiles.currentProfileData();
@@ -146,6 +145,27 @@ $(function() {
} }
}); });
} }
};
// subscribe to relevant printer settings...
self.settings.printerProfiles.currentProfileData.subscribe(function() {
self._printerProfileUpdated();
if (self.settings.printerProfiles.currentProfileData()) {
if (self.settings.printerProfiles.currentProfileData().extruder) {
self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles.currentProfileData().extruder.sharedNozzle.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles.currentProfileData().extruder.offsets.subscribe(self._printerProfileUpdated);
}
if (self.settings.printerProfiles.currentProfileData().volume) {
self.settings.printerProfiles.currentProfileData().volume.width.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles.currentProfileData().volume.depth.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles.currentProfileData().volume.formFactor.subscribe(self._printerProfileUpdated);
}
if (self.settings.printerProfiles.currentProfileData().axes) {
self.settings.printerProfiles.currentProfileData().axes.x.inverted.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles.currentProfileData().axes.y.inverted.subscribe(self._printerProfileUpdated);
}
}
}); });
self.settings.feature_g90InfluencesExtruder.subscribe(function() { self.settings.feature_g90InfluencesExtruder.subscribe(function() {
@@ -194,11 +214,13 @@ $(function() {
currentProfileData = self.settings.printerProfiles.currentProfileData(); currentProfileData = self.settings.printerProfiles.currentProfileData();
} }
if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets() && !currentProfileData.extruder.sharedNozzle()) { if (currentProfileData && currentProfileData.extruder) {
var offsets = []; var offsets = [];
_.each(currentProfileData.extruder.offsets(), function(offset) { if (currentProfileData.extruder.offsets() && !currentProfileData.extruder.sharedNozzle()) {
offsets.push({x: offset[0], y: offset[1]}) _.each(currentProfileData.extruder.offsets(), function(offset) {
}); offsets.push({x: offset[0], y: offset[1]})
});
}
return offsets; return offsets;
} else { } else {
return undefined; return undefined;
@@ -225,14 +225,16 @@ $(function() {
var result = []; var result = [];
if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) { if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) {
for (var key in data.filament) { var keys = _.keys(data.filament);
if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) continue; keys.sort();
_.each(keys, function(key) {
if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) return;
result.push({ result.push({
name: ko.observable(gettext("Tool") + " " + key.substr("tool".length)), name: ko.observable(gettext("Tool") + " " + key.substr("tool".length)),
data: ko.observable(data.filament[key]) data: ko.observable(data.filament[key])
}); });
} });
} }
self.filament(result); self.filament(result);
}; };
@@ -173,6 +173,8 @@ $(function() {
self.serial_disconnectOnErrors = ko.observable(undefined); self.serial_disconnectOnErrors = ko.observable(undefined);
self.serial_triggerOkForM29 = ko.observable(undefined); self.serial_triggerOkForM29 = ko.observable(undefined);
self.serial_supportResendsWithoutOk = 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_maxTimeoutsIdle = ko.observable(undefined);
self.serial_maxTimeoutsPrinting = ko.observable(undefined); self.serial_maxTimeoutsPrinting = ko.observable(undefined);
self.serial_maxTimeoutsLong = ko.observable(undefined); self.serial_maxTimeoutsLong = ko.observable(undefined);
@@ -211,6 +213,11 @@ $(function() {
self.server_diskspace_warning_str = sizeObservable(self.server_diskspace_warning); self.server_diskspace_warning_str = sizeObservable(self.server_diskspace_warning);
self.server_diskspace_critical_str = sizeObservable(self.server_diskspace_critical); 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.settings = undefined;
self.lastReceivedSettings = undefined; self.lastReceivedSettings = undefined;
@@ -47,7 +47,18 @@ $(function() {
var callback = function() { var callback = function() {
OctoPrint.system.executeCommand(commandSpec.actionSource, commandSpec.action) OctoPrint.system.executeCommand(commandSpec.actionSource, commandSpec.action)
.done(function() { .done(function() {
new PNotify({title: "Success", text: _.sprintf(gettext("The command \"%(command)s\" executed successfully"), {command: commandSpec.name}), type: "success"}); var text;
if (commandSpec.async) {
text = gettext("The command \"%(command)s\" executed successfully");
} else {
text = gettext("The command \"%(command)s\" was triggered asychronously");
}
new PNotify({
title: "Success",
text: _.sprintf(text, {command: commandSpec.name}),
type: "success"
});
deferred.resolve(["success", arguments]); deferred.resolve(["success", arguments]);
}) })
.fail(function(jqXHR, textStatus, errorThrown) { .fail(function(jqXHR, textStatus, errorThrown) {
@@ -95,7 +95,7 @@ $(function() {
self._printerProfileUpdated = function() { self._printerProfileUpdated = function() {
var graphColors = ["red", "orange", "green", "brown", "purple"]; var graphColors = ["red", "orange", "green", "brown", "purple"];
var heaterOptions = {}; var heaterOptions = {};
var tools = self.tools(); var tools = [];
var color; var color;
// tools // tools
@@ -123,7 +123,7 @@ $(function() {
if (tools.length < 1 || !tools[0]) { if (tools.length < 1 || !tools[0]) {
tools[0] = self._createToolEntry(); tools[0] = self._createToolEntry();
} }
tools[0]["name"](gettext("Hotend")); tools[0]["name"](gettext("Tool"));
tools[0]["key"]("tool0"); tools[0]["key"]("tool0");
} }
@@ -147,6 +147,7 @@ $(function() {
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() { self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
self._printerProfileUpdated(); self._printerProfileUpdated();
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(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); self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated);
}); });
@@ -721,9 +722,7 @@ $(function() {
} }
}); });
} }
};
self.onStartup = function() {
self.changeOffsetDialog = $("#change_offset_dialog"); self.changeOffsetDialog = $("#change_offset_dialog");
}; };
@@ -272,6 +272,16 @@ $(function() {
} }
}; };
self.gotoTerminalCommand = function() {
// skip if user highlights text.
var sel = getSelection().toString();
if (sel) {
return;
}
$("#terminal-command").focus();
};
self.toggleAutoscroll = function() { self.toggleAutoscroll = function() {
self.autoscrollEnabled(!self.autoscrollEnabled()); self.autoscrollEnabled(!self.autoscrollEnabled());
}; };
@@ -192,9 +192,25 @@ $(function() {
self.onSettingsPreventRefresh = function() { self.onSettingsPreventRefresh = function() {
if (!self.finishing && self.isDialogActive() if (!self.finishing && self.isDialogActive()
&& hasDataChanged(self.settingsViewModel.getLocalData(), self.settingsViewModel.lastReceivedSettings)) { && 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 // we have local changes, show update dialog
self.settingsViewModel.settingsUpdatedDialog.modal("show"); if (preventSettingsRefreshDialog) {
return true; return false;
} else {
self.settingsViewModel.settingsUpdatedDialog.modal("show");
return true;
}
} }
return false; return false;
+5 -1
View File
@@ -687,7 +687,11 @@
if (!isActive) { if (!isActive) {
if ('ontouchstart' in document.documentElement) { if ('ontouchstart' in document.documentElement) {
// if mobile we we use a backdrop because click events don't delegate // if mobile we we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').insertBefore($(this)).on('click', clearMenus)
// 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
} }
$parent.toggleClass('open') $parent.toggleClass('open')
} }
+39 -10
View File
@@ -435,8 +435,11 @@ table {
} }
&.temperature_tool { &.temperature_tool {
width: 18%; width: 16%;
text-align: left; text-align: left;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
} }
&.temperature_actual { &.temperature_actual {
@@ -444,7 +447,7 @@ table {
} }
&.temperature_target { &.temperature_target {
width: 40%; width: 42%;
overflow: visible; overflow: visible;
} }
@@ -875,10 +878,6 @@ ul.dropdown-menu li a {
margin-bottom: 30px; margin-bottom: 30px;
} }
#terminal-sendpanel {
text-align: right;
}
} }
#settings_dialog { #settings_dialog {
@@ -1129,10 +1128,6 @@ textarea.block {
display: inline-block !important; display: inline-block !important;
} }
a.dropdown-sd {
padding-top: 4px !important;
}
.center { .center {
float: none; float: none;
margin-left: auto; margin-left: auto;
@@ -1295,6 +1290,40 @@ _::-webkit-full-page-media, _:future, :root .full-sized-box {
} }
} }
// block level inputs with add-ons
//
// LESS based on CSS from https://stackoverflow.com/a/17466199/2028598
//
// Note: do not use <button> for attached buttons, use <a class="btn add-on">...</a>
// instead
.input-append,
.input-prepend {
&.input-block-level {
display: table;
.add-on {
display: table-cell;
width: 1%; /* remove this if you want default bootstrap button width */
}
> input {
box-sizing: border-box; /* use bootstrap mixin or include vendor variants */
display: table; /* table-cell is not working well in Chrome for small widths */
min-height: inherit;
width: 100%;
}
}
}
.input-append.input-block-level > input {
border-right: 0;
}
.input-prepend.input-block-level > input {
border-left: 0;
}
.btn-input-dec, .btn-input-dec,
.btn-input-enc { .btn-input-enc {
//font-size: 80%; //font-size: 80%;
@@ -151,6 +151,18 @@
<input type="checkbox" data-bind="checked: serial_supportResendsWithoutOk" id="settings-supportResendsWithoutOk"> {{ _('Simulate an additional <code>ok</code> for resend requests') }} <input type="checkbox" data-bind="checked: serial_supportResendsWithoutOk" id="settings-supportResendsWithoutOk"> {{ _('Simulate an additional <code>ok</code> for resend requests') }}
</label> </label>
</div> </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.') }}"> <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> <label class="control-label" for="settings-serialMaxTimeoutsIdle">{{ _('Max. consecutive timeouts while idle') }}</label>
<div class="controls"> <div class="controls">
@@ -4,4 +4,10 @@
{% include "snippets/settings/server/serverCommandServerRestart.jinja2" %} {% include "snippets/settings/server/serverCommandServerRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %} {% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %} {% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
<h3>{{ _('Connectivity check') }}</h3>
{% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheck.jinja2" %}
</form> </form>
@@ -5,7 +5,7 @@
</div> </div>
<div class="modal-body"> <div class="modal-body">
<p data-bind="text: changingOffset.description"></p> <p data-bind="text: changingOffset.description"></p>
<form class="form-horizontal"> <form class="form-horizontal" data-bind="submit: confirmChangeOffset">
<div class="control-group"> <div class="control-group">
<label class="control-label">{{ _('Current Offset') }}</label> <label class="control-label">{{ _('Current Offset') }}</label>
<div class="controls"> <div class="controls">
@@ -29,6 +29,6 @@
</div> </div>
<div class="modal-footer"> <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" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="javascript:void(0)" class="btn btn-primary" data-bind="click: confirmChangeOffset">{{ _('Submit') }}</a> <a href="javascript:void(0)" class="btn btn-primary" data-bind="click: confirmChangeOffset">{{ _('Save') }}</a>
</div> </div>
</div> </div>
+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()}"> <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 }"> <form id="loginForm" data-bind="event: {'submit': loginState.prepareLogin }">
<label for="login_user">{{ _('Username') }}</label> <label for="login_user">{{ _('Username') }}</label>
<input type="text" id="login_user" name="username" data-bind="valueWithInit: loginState.loginUser" placeholder="{{ _('Username') }}" autocapitalize="none"> <input type="text" id="login_user" name="username" data-bind="valueWithInit: loginState.loginUser" placeholder="{{ _('Username') }}" autocapitalize="none" autocorrect="off">
<label for="login_pass">{{ _('Password') }}</label> <label for="login_pass">{{ _('Password') }}</label>
<input type="password" id="login_pass" name="password" data-bind="valueWithInit: loginState.loginPass" placeholder="{{ _('Password') }}"> <input type="password" id="login_pass" name="password" data-bind="valueWithInit: loginState.loginPass" placeholder="{{ _('Password') }}">
<label class="checkbox"> <label class="checkbox">
@@ -35,7 +35,7 @@
{% if enableSdSupport %} {% if enableSdSupport %}
<div class="sd-trigger accordion-heading-button btn-group"> <div class="sd-trigger accordion-heading-button btn-group">
<a class="dropdown-toggle dropdown-sd" data-toggle="dropdown" href="#" title="{{ _('SD Card operations') }}"> <a class="dropdown-toggle" data-toggle="dropdown" href="#" title="{{ _('SD Card operations') }}">
<span class="icon-sd-black-14"></span> <span class="icon-sd-black-14"></span>
</a> </a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
@@ -0,0 +1,18 @@
{% include "snippets/settings/server/serverOnlineCheckEnabled.jinja2" %}
<div data-bind="visible: server_onlineCheck_enabled">
<div class="control-group">
<div class="controls">
<p>{% trans %}
Define a check interval, a host and a port to check against. If you don't know what to set here, the
default values (using Google's DNS server) should work. If you have concerns about using
that, define the IP and port of a different online server that you trust and that has a high
availability.
{% endtrans %}</p>
</div>
</div>
{% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %}
</div>
@@ -0,0 +1,5 @@
<p>{% trans %}
If the connectivity check is enabled, OctoPrint will regularly check if it's connected to the internet.
This is <strong>useful to prevent resource intensive operations</strong> (such as checking for updates) if it's already
clear that they won't succeed anyhow.
{% endtrans %}</p>
@@ -0,0 +1,7 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: server_onlineCheck_enabled" id="settings-serverOnlineCheckEnabled"> {{ _('Enable regular connectivity check') }}
</label>
</div>
</div>
@@ -0,0 +1,6 @@
<div class="control-group" title="{{ _('Host against which to check for internet connectivity') }}">
<label class="control-label" for="settings-serverOnlineCheckHost">{{ _('Host IP') }}</label>
<div class="controls">
<input type="text" class="input-small" data-bind="value: server_onlineCheck_host" id="settings-serverOnlineCheckHost">
</div>
</div>
@@ -0,0 +1,9 @@
<div class="control-group" title="{{ _('Interval in which to check for internet connectivity') }}">
<label class="control-label" for="settings-serverOnlineCheckInterval">{{ _('Check interval') }}</label>
<div class="controls">
<span class="input-append">
<input type="number" min="1" step="1" class="input-mini" data-bind="value: server_onlineCheck_interval" id="settings-serverOnlineCheckInterval">
<span class="add-on">min</span>
</span>
</div>
</div>
@@ -0,0 +1,6 @@
<div class="control-group" title="{{ _('Port against which to check for internet connectivity') }}">
<label class="control-label" for="settings-serverOnlineCheckHost">{{ _('Port') }}</label>
<div class="controls">
<input type="number" min="1" max="65535" step="1" class="input-small" data-bind="value: server_onlineCheck_port" id="settings-serverOnlineCheckPort">
</div>
</div>
+1 -1
View File
@@ -130,7 +130,7 @@
</script> </script>
<script type="text/html" id="customControls_containerTemplate_collapsable"> <script type="text/html" id="customControls_containerTemplate_collapsable">
<div class="custom_section"> <div class="custom_section">
<h1 class="fa" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.custom_section', container: '> div' }"><i class="fa" data-bind="css: {'fa-caret-down': !collapsed, 'fa-caret-right': collapsed}"></i> <span data-bind="text: name"></span></h1> <h1 data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.custom_section', container: '> div' }"><i class="fa" data-bind="css: {'fa-caret-down': !collapsed, 'fa-caret-right': collapsed}"></i> <span data-bind="text: name"></span></h1>
<!-- ko template: { name: 'customControls_containerTemplate', data: $data } --><!-- /ko --> <!-- ko template: { name: 'customControls_containerTemplate', data: $data } --><!-- /ko -->
</div> </div>
</script> </script>
@@ -19,8 +19,8 @@
</table> </table>
<script type="text/html" id="temprow-template"> <script type="text/html" id="temprow-template">
<th class="temperature_tool" data-bind="text: name"></th> <th class="temperature_tool" data-bind="text: name, attr: {title: name}"></th>
<td class="temperature_actual" data-bind="html: formatTemperature(actual())"></td> <td class="temperature_actual" data-bind="html: formatTemperature(actual()), attr: {title: formatTemperature(actual())}"></td>
<td class="temperature_target"> <td class="temperature_target">
<form class="form-inline" style="margin:0" data-bind="submit: function(element) { $root.setTarget($data, element) }"> <form class="form-inline" style="margin:0" data-bind="submit: function(element) { $root.setTarget($data, element) }">
<div class="input-prepend input-append"> <div class="input-prepend input-append">
+8 -9
View File
@@ -1,9 +1,15 @@
<div class="terminal"> <div class="terminal">
<pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality()"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span></pre> <pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality(), click: function(){ gotoTerminalCommand(); }"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span></pre>
<pre id="terminal-output-lowfi" style="display: none" class="pre-scrollable" data-bind="text: plainLogOutput, visible: !fancyFunctionality()"></pre> <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-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-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 muted" data-bind="visible: !fancyFunctionality()" style="display: none">{{ _('For performance reasons only a limited amount of terminal functionality is enabled right now.') }}</small> <small class="pull-left text-warning" data-bind="visible: !fancyFunctionality()" style="display: none">{{ _('For performance reasons only a limited amount of terminal functionality is enabled right now.') }}</small>
</div> </div>
<div class="row-fluid"> <div class="row-fluid">
@@ -14,13 +20,6 @@
</label> </label>
</div> </div>
</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>
<div> <div>
@@ -116,7 +116,7 @@
</div> </div>
<div data-bind="visible: unrenderedListHelper.allSize"> <div data-bind="visible: unrenderedListHelper.allSize">
<div><small><a href="javascript:void(0)" class="fa muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Unrendered Timelapses') }}</a></small></div> <div><small><a href="javascript:void(0)" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Unrendered Timelapses') }}</a></small></div>
<div class="hide"> <div class="hide">
<div class="pull-left"> <div class="pull-left">
<div class="btn-group"> <div class="btn-group">
File diff suppressed because it is too large. Load diff
+166 -16
View File
@@ -735,22 +735,47 @@ def interface_addresses(family=None):
if not ifaddress["addr"].startswith("169.254."): if not ifaddress["addr"].startswith("169.254."):
yield ifaddress["addr"] yield ifaddress["addr"]
def address_for_client(host, port): def address_for_client(host, port, timeout=3.05):
""" """
Determines the address of the network interface on this host needed to connect to the indicated client host and port. 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(): for address in interface_addresses():
try: try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if server_reachable(host, port, timeout=timeout, proto="udp", source=address):
sock.bind((address, 0)) return address
sock.connect((host, port))
return address
except: except:
continue 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 @contextlib.contextmanager
def atomic_write(filename, mode="w+b", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777): def atomic_write(filename, mode="w+b", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777):
@@ -1046,7 +1071,7 @@ class InvariantContainer(object):
return self._data.__iter__() return self._data.__iter__()
class PrependQueue(queue.Queue): class PrependableQueue(queue.Queue):
def __init__(self, maxsize=0): def __init__(self, maxsize=0):
queue.Queue.__init__(self, maxsize=maxsize) queue.Queue.__init__(self, maxsize=maxsize)
@@ -1082,21 +1107,21 @@ class PrependQueue(queue.Queue):
self.queue.appendleft(item) self.queue.appendleft(item)
class TypedQueue(PrependQueue): class TypedQueue(PrependableQueue):
def __init__(self, maxsize=0): def __init__(self, maxsize=0):
PrependQueue.__init__(self, maxsize=maxsize) PrependableQueue.__init__(self, maxsize=maxsize)
self._lookup = set() self._lookup = set()
def put(self, item, item_type=None, *args, **kwargs): def put(self, item, item_type=None, *args, **kwargs):
PrependQueue.put(self, (item, item_type), *args, **kwargs) PrependableQueue.put(self, (item, item_type), *args, **kwargs)
def get(self, *args, **kwargs): def get(self, *args, **kwargs):
item, _ = PrependQueue.get(self, *args, **kwargs) item, _ = PrependableQueue.get(self, *args, **kwargs)
return item return item
def prepend(self, item, item_type=None, *args, **kwargs): def prepend(self, item, item_type=None, *args, **kwargs):
PrependQueue.prepend(self, (item, item_type), *args, **kwargs) PrependableQueue.prepend(self, (item, item_type), *args, **kwargs)
def _put(self, item): def _put(self, item):
_, item_type = item _, item_type = item
@@ -1106,10 +1131,10 @@ class TypedQueue(PrependQueue):
else: else:
self._lookup.add(item_type) self._lookup.add(item_type)
queue.Queue._put(self, item) PrependableQueue._put(self, item)
def _get(self): def _get(self):
item = PrependQueue._get(self) item = PrependableQueue._get(self)
_, item_type = item _, item_type = item
if item_type is not None: if item_type is not None:
@@ -1125,10 +1150,135 @@ class TypedQueue(PrependQueue):
else: else:
self._lookup.add(item_type) self._lookup.add(item_type)
PrependQueue._prepend(self, item) PrependableQueue._prepend(self, item)
class TypeAlreadyInQueue(Exception): class TypeAlreadyInQueue(Exception):
def __init__(self, t, *args, **kwargs): def __init__(self, t, *args, **kwargs):
Exception.__init__(self, *args, **kwargs) Exception.__init__(self, *args, **kwargs)
self.type = t self.type = t
class ConnectivityChecker(object):
"""
Regularly checks for online connectivity.
Tries to open a connection to the provided ``host`` and ``port`` every ``interval``
seconds and sets the ``online`` status accordingly.
"""
def __init__(self, interval, host, port, enabled=True, on_change=None):
self._interval = interval
self._host = host
self._port = port
self._enabled = enabled
self._on_change = on_change
self._logger = logging.getLogger(__name__ + ".connectivity_checker")
# we initialize the online flag to True if we are not enabled (we don't know any better
# but these days it's probably a sane default)
self._online = not self._enabled
self._check_worker = None
self._check_mutex = threading.RLock()
self._run()
@property
def online(self):
"""Current online status, True if online, False if offline."""
with self._check_mutex:
return self._online
@property
def host(self):
"""DNS host to query."""
with self._check_mutex:
return self._host
@host.setter
def host(self, value):
with self._check_mutex:
self._host = value
@property
def port(self):
"""DNS port to query."""
with self._check_mutex:
return self._port
@port.setter
def port(self, value):
with self._check_mutex:
self._port = value
@property
def interval(self):
"""Interval between consecutive automatic checks."""
return self._interval
@interval.setter
def interval(self, value):
self._interval = value
@property
def enabled(self):
"""Whether the check is enabled or not."""
return self._enabled
@enabled.setter
def enabled(self, value):
with self._check_mutex:
old_enabled = self._enabled
self._enabled = value
if not self._enabled:
if self._check_worker is not None:
self._check_worker.cancel()
old_value = self._online
self._online = True
if old_value != self._online:
self._trigger_change(old_value, self._online)
elif self._enabled and not old_enabled:
self._run()
def check_immediately(self):
"""Check immediately and return result."""
with self._check_mutex:
self._perform_check()
return self.online
def _run(self):
from octoprint.util import RepeatedTimer
if not self._enabled:
return
if self._check_worker is not None:
self._check_worker.cancel()
self._check_worker = RepeatedTimer(self._interval, self._perform_check,
run_first=True)
self._check_worker.start()
def _perform_check(self):
if not self._enabled:
return
with self._check_mutex:
self._logger.debug("Checking against {}:{} if we are online...".format(self._host, self._port))
old_value = self._online
self._online = server_reachable(self._host, port=self._port)
if old_value != self._online:
self._trigger_change(old_value, self._online)
def _trigger_change(self, old_value, new_value):
self._logger.info("Connectivity changed from {} to {}".format("online" if old_value else "offline",
"online" if new_value else "offline"))
if callable(self._on_change):
self._on_change(old_value, new_value)
+223 -115
View File
@@ -32,7 +32,7 @@ from octoprint.events import eventManager, Events
from octoprint.filemanager import valid_file_type from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations from octoprint.filemanager.destinations import FileDestinations
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \ from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \
to_unicode, bom_aware_open, TypedQueue, TypeAlreadyInQueue, chunks to_unicode, bom_aware_open, TypedQueue, PrependableQueue, TypeAlreadyInQueue, chunks
try: try:
import _winreg import _winreg
@@ -47,7 +47,7 @@ regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+" regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
regex_int_pattern = "\d+" regex_int_pattern = "\d+"
regex_command = re.compile("^\s*((?P<commandGM>[GM]\d+)|(?P<commandT>T)\d+|(?P<commandF>F)\d+)") regex_command = re.compile("^\s*((?P<codeGM>[GM]\d+)(\\.(?P<subcode>\d+))?|(?P<codeT>T)\d+|(?P<codeF>F)\d+)")
"""Regex for a GCODE command.""" """Regex for a GCODE command."""
regex_float = re.compile(regex_float_pattern) regex_float = re.compile(regex_float_pattern)
@@ -89,7 +89,7 @@ Groups will be as follows:
* ``size``: size of the file in bytes (int) * ``size``: size of the file in bytes (int)
""" """
regex_temp = re.compile("(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?" % (regex_positive_float_pattern, regex_positive_float_pattern)) regex_temp = re.compile("(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?" % (regex_float_pattern, regex_float_pattern))
"""Regex matching temperature entries in line. """Regex matching temperature entries in line.
Groups will be as follows: Groups will be as follows:
@@ -100,7 +100,7 @@ Groups will be as follows:
* ``target``: target temperature, if provided (float) * ``target``: target temperature, if provided (float)
""" """
regex_repetierTempExtr = re.compile("TargetExtr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern) regex_repetierTempExtr = re.compile("TargetExtr(?P<toolnum>\d+):(?P<target>%s)" % regex_float_pattern)
"""Regex for matching target temp reporting from Repetier. """Regex for matching target temp reporting from Repetier.
Groups will be as follows: Groups will be as follows:
@@ -110,7 +110,7 @@ Groups will be as follows:
* ``target``: new target temperature (float) * ``target``: new target temperature (float)
""" """
regex_repetierTempBed = re.compile("TargetBed:(?P<target>%s)" % regex_positive_float_pattern) regex_repetierTempBed = re.compile("TargetBed:(?P<target>%s)" % regex_float_pattern)
"""Regex for matching target temp reporting from Repetier for beds. """Regex for matching target temp reporting from Repetier for beds.
Groups will be as follows: Groups will be as follows:
@@ -422,7 +422,7 @@ class MachineCom(object):
self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"]) self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"])
self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send") self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
self._send_queue = TypedQueue() self._send_queue = SendQueue()
self._temperature_timer = None self._temperature_timer = None
self._sd_status_timer = None self._sd_status_timer = None
@@ -461,6 +461,9 @@ class MachineCom(object):
self._record_pause_data = False self._record_pause_data = False
self._record_cancel_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 # print job
self._currentFile = None self._currentFile = None
@@ -944,7 +947,10 @@ class MachineCom(object):
except: except:
pass pass
self.sendCommand("M400", on_sent=_on_M400_sent) if self._log_position_on_cancel:
self.sendCommand("M400", on_sent=_on_M400_sent)
else:
self._cancel_preparation_done()
def _pause_preparation_done(self): def _pause_preparation_done(self):
self._callback.on_comm_print_job_paused() self._callback.on_comm_print_job_paused()
@@ -991,7 +997,10 @@ class MachineCom(object):
self._record_pause_data = True self._record_pause_data = True
self.sendCommand("M114") self.sendCommand("M114")
self.sendCommand("M400", on_sent=_on_M400_sent) if self._log_position_on_pause:
self.sendCommand("M400", on_sent=_on_M400_sent)
else:
self._pause_preparation_done()
def getSdFiles(self): def getSdFiles(self):
return self._sdFiles return self._sdFiles
@@ -2068,6 +2077,7 @@ class MachineCom(object):
self._to_logfile_with_terminal("Got a resend request from the printer: requested line = {}, current line = {}".format(lineToResend, self._currentLine)) self._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._log_resends_rate_count += 1
self._send_queue.resend_active = True
return True return True
finally: finally:
if self._supportResendsWithoutOk: if self._supportResendsWithoutOk:
@@ -2096,7 +2106,7 @@ class MachineCom(object):
cmd = self._lastLines[-self._resendDelta] cmd = self._lastLines[-self._resendDelta]
lineNumber = self._currentLine - self._resendDelta lineNumber = self._currentLine - self._resendDelta
result = self._enqueue_for_sending(cmd, linenumber=lineNumber) result = self._enqueue_for_sending(cmd, linenumber=lineNumber, resend=True)
self._resendDelta -= 1 self._resendDelta -= 1
if self._resendDelta <= 0: if self._resendDelta <= 0:
@@ -2104,6 +2114,8 @@ class MachineCom(object):
self._lastResendNumber = None self._lastResendNumber = None
self._currentResendCount = 0 self._currentResendCount = 0
self._send_queue.resend_active = False
return result return result
def _sendCommand(self, cmd, cmd_type=None, on_sent=None): def _sendCommand(self, cmd, cmd_type=None, on_sent=None):
@@ -2112,20 +2124,20 @@ class MachineCom(object):
if self._serial is None: if self._serial is None:
return False return False
gcode = None gcode, subcode = gcode_and_subcode_for_cmd(cmd)
if not self.isStreaming(): if not self.isStreaming():
# trigger the "queuing" phase only if we are not streaming to sd right now # trigger the "queuing" phase only if we are not streaming to sd right now
results = self._process_command_phase("queuing", cmd, cmd_type, gcode=gcode) results = self._process_command_phase("queuing", cmd, command_type=cmd_type, gcode=gcode, subcode=subcode)
if not results: if not results:
# command is no more, return # command is no more, return
return False return False
else: else:
results = [(cmd, cmd_type, gcode)] results = [(cmd, cmd_type, gcode, subcode)]
# process helper # process helper
def process(cmd, cmd_type, gcode, on_sent=None): def process(cmd, cmd_type, gcode, subcode, on_sent=None):
if cmd is None: if cmd is None:
# no command, next entry # no command, next entry
return False return False
@@ -2138,7 +2150,7 @@ class MachineCom(object):
if self._enqueue_for_sending(cmd, command_type=cmd_type, on_sent=on_sent): if self._enqueue_for_sending(cmd, command_type=cmd_type, on_sent=on_sent):
if not self.isStreaming(): if not self.isStreaming():
# trigger the "queued" phase only if we are not streaming to sd right now # trigger the "queued" phase only if we are not streaming to sd right now
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode) self._process_command_phase("queued", cmd, cmd_type, gcode=gcode, subcode=subcode)
return True return True
else: else:
return False return False
@@ -2155,18 +2167,18 @@ class MachineCom(object):
enqueued_something = False enqueued_something = False
# process all but the last ... # process all but the last ...
for (cmd, cmd_type, gcode) in results: for (cmd, cmd_type, gcode, subcode) in results:
enqueued_something = process(cmd, cmd_type, gcode) or enqueued_something enqueued_something = process(cmd, cmd_type, gcode, subcode) or enqueued_something
# ... and then process the last one with the on_sent callback attached # ... and then process the last one with the on_sent callback attached
cmd, cmd_type, gcode = last_command cmd, cmd_type, gcode, subcode = last_command
enqueued_something = process(cmd, cmd_type, gcode, on_sent=on_sent) or enqueued_something enqueued_something = process(cmd, cmd_type, gcode, subcode, on_sent=on_sent) or enqueued_something
return enqueued_something return enqueued_something
##~~ send loop handling ##~~ send loop handling
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None): def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None, resend=False):
""" """
Enqueues a command and optional linenumber to use for it in the send queue. Enqueues a command and optional linenumber to use for it in the send queue.
@@ -2180,7 +2192,11 @@ class MachineCom(object):
""" """
try: try:
self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type) target = "send"
if resend:
target = "resend"
self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type, target=target)
return True return True
except TypeAlreadyInQueue as e: except TypeAlreadyInQueue as e:
self._logger.debug("Type already in send queue: " + e.type) self._logger.debug("Type already in send queue: " + e.type)
@@ -2188,7 +2204,7 @@ class MachineCom(object):
def _send_loop(self): def _send_loop(self):
""" """
The send loop is reponsible of sending commands in ``self._send_queue`` over the line, if it is cleared for The send loop is responsible of sending commands in ``self._send_queue`` over the line, if it is cleared for
sending (through received ``ok`` responses from the printer's firmware. sending (through received ``ok`` responses from the printer's firmware.
""" """
@@ -2216,7 +2232,7 @@ class MachineCom(object):
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not # 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 # 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 # at hand here and only clear our clear_to_send flag later if that's the case
gcode = gcode_command_for_cmd(command) gcode, subcode = gcode_and_subcode_for_cmd(command)
if linenumber is not None: if linenumber is not None:
# line number predetermined - this only happens for resends, so we'll use the number and # line number predetermined - this only happens for resends, so we'll use the number and
@@ -2226,7 +2242,7 @@ class MachineCom(object):
else: else:
if not processed: if not processed:
# trigger "sending" phase if we didn't so far # trigger "sending" phase if we didn't so far
results = self._process_command_phase("sending", command, command_type, gcode=gcode) results = self._process_command_phase("sending", command, command_type, gcode=gcode, subcode=subcode)
if not results: if not results:
# No, we are not going to send this, that was a last-minute bail. # No, we are not going to send this, that was a last-minute bail.
@@ -2239,20 +2255,14 @@ class MachineCom(object):
# and now let's fetch the next item from the queue # and now let's fetch the next item from the queue
continue continue
if len(results) > 1: # we explicitly throw away plugin hook results that try
# last command gets on_sent attached # to perform command expansion in the sending/sent phase,
last = results[-1] # so "results" really should only have more than one entry
self._send_queue.prepend((last[0], None, None, on_sent, True)) # at this point if our core code contains a bug
on_sent = None assert len(results) == 1
# middle gets prepended reversed (so order gets restored) # we only use the first (and only!) entry here
if len(results) > 2: command, _, gcode, subcode = results[0]
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() == "": if command.strip() == "":
self._logger.info("Refusing to send an empty line to the printer") self._logger.info("Refusing to send an empty line to the printer")
@@ -2280,7 +2290,7 @@ class MachineCom(object):
if on_sent is not None and callable(on_sent): if on_sent is not None and callable(on_sent):
# we have a sent callback for this specific command, let's execute it now # we have a sent callback for this specific command, let's execute it now
on_sent() on_sent()
self._process_command_phase("sent", command, command_type, gcode=gcode) self._process_command_phase("sent", command, command_type, gcode=gcode, subcode=subcode)
# we only need to use up a clear if the command we just sent was either a gcode command or if we also # 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 # require ack's for unknown commands
@@ -2308,10 +2318,10 @@ class MachineCom(object):
self._logger.exception("Caught an exception in the send loop") self._logger.exception("Caught an exception in the send loop")
self._log("Closing down send loop") self._log("Closing down send loop")
def _process_command_phase(self, phase, command, command_type=None, gcode=None): def _process_command_phase(self, phase, command, command_type=None, gcode=None, subcode=None):
if gcode is None: if gcode is None:
gcode = gcode_command_for_cmd(command) gcode, subcode = gcode_and_subcode_for_cmd(command)
results = [(command, command_type, gcode)] results = [(command, command_type, gcode, subcode)]
if (self.isStreaming() and self.isPrinting()) or phase not in ("queuing", "queued", "sending", "sent"): if (self.isStreaming() and self.isPrinting()) or phase not in ("queuing", "queued", "sending", "sent"):
return results return results
@@ -2319,14 +2329,20 @@ class MachineCom(object):
# send it through the phase specific handlers provided by plugins # send it through the phase specific handlers provided by plugins
for name, hook in self._gcode_hooks[phase].items(): for name, hook in self._gcode_hooks[phase].items():
new_results = [] new_results = []
for command, command_type, gcode in results: for command, command_type, gcode, subcode in results:
try: try:
hook_results = hook(self, phase, command, command_type, gcode) hook_results = hook(self, phase, command, command_type, gcode, subcode=subcode)
except: except:
self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals())) self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals()))
else: else:
normalized = _normalize_command_handler_result(command, command_type, gcode, hook_results) normalized = _normalize_command_handler_result(command, command_type, gcode, subcode, hook_results)
new_results += normalized
# make sure we don't allow multi entry results in anything but the queuing phase
if not phase in ("queuing",) and len(normalized) > 1:
self._logger.error("Error while processing hook {name} for phase {phase} and command {command}: Hook returned multi-entry result for phase {phase} and command {command}. That's not supported, if you need to do multi expansion of commands you need to do this in the queuing phase. Ignoring hook result and sending command as-is.".format(**locals()))
new_results.append((command, command_type, gcode, subcode))
else:
new_results += normalized
if not new_results: 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 # hook handler returned None or empty list for all commands, so we'll stop here and return a full out empty result
return [] return []
@@ -2335,15 +2351,15 @@ class MachineCom(object):
# if it's a gcode command send it through the specific handler if it exists # if it's a gcode command send it through the specific handler if it exists
new_results = [] new_results = []
modified = False modified = False
for command, command_type, gcode in results: for command, command_type, gcode, subcode in results:
if gcode is not None: if gcode is not None:
gcode_handler = "_gcode_" + gcode + "_" + phase gcode_handler = "_gcode_" + gcode + "_" + phase
if hasattr(self, gcode_handler): if hasattr(self, gcode_handler):
handler_results = getattr(self, gcode_handler)(command, cmd_type=command_type) handler_results = getattr(self, gcode_handler)(command, cmd_type=command_type, subcode=subcode)
new_results += _normalize_command_handler_result(command, command_type, gcode, handler_results) new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results)
modified = True modified = True
else: else:
new_results.append((command, command_type, gcode)) new_results.append((command, command_type, gcode, subcode))
modified = True modified = True
if modified: if modified:
if not new_results: if not new_results:
@@ -2356,9 +2372,9 @@ class MachineCom(object):
command_phase_handler = "_command_phase_" + phase command_phase_handler = "_command_phase_" + phase
if hasattr(self, command_phase_handler): if hasattr(self, command_phase_handler):
new_results = [] new_results = []
for command, command_type, gcode in results: for command, command_type, gcode, subcode in results:
handler_results = getattr(self, command_phase_handler)(command, cmd_type=command_type, gcode=gcode) 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, handler_results) new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results)
results = new_results results = new_results
# finally return whatever we resulted on # finally return whatever we resulted on
@@ -2444,7 +2460,7 @@ class MachineCom(object):
##~~ command handlers ##~~ command handlers
def _gcode_T_queuing(self, cmd, cmd_type=None): def _gcode_T_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
toolMatch = regexes_parameters["intT"].search(cmd) toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch: if toolMatch:
current_tool = self._currentTool current_tool = self._currentTool
@@ -2455,14 +2471,14 @@ class MachineCom(object):
return before + [cmd] + after return before + [cmd] + after
def _gcode_T_sent(self, cmd, cmd_type=None): def _gcode_T_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
toolMatch = regexes_parameters["intT"].search(cmd) toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch: if toolMatch:
old = self._currentTool old = self._currentTool
self._currentTool = int(toolMatch.group("value")) self._currentTool = int(toolMatch.group("value"))
eventManager().fire(Events.TOOL_CHANGE, dict(old=old, new=self._currentTool)) eventManager().fire(Events.TOOL_CHANGE, dict(old=old, new=self._currentTool))
def _gcode_G0_sent(self, cmd, cmd_type=None): def _gcode_G0_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
if "Z" in cmd or "F" in cmd: if "Z" in cmd or "F" in cmd:
# track Z # track Z
match = regexes_parameters["floatZ"].search(cmd) match = regexes_parameters["floatZ"].search(cmd)
@@ -2485,7 +2501,7 @@ class MachineCom(object):
pass pass
_gcode_G1_sent = _gcode_G0_sent _gcode_G1_sent = _gcode_G0_sent
def _gcode_G28_sent(self, cmd, cmd_type=None): def _gcode_G28_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
if "F" in cmd: if "F" in cmd:
match = regexes_parameters["floatF"].search(cmd) match = regexes_parameters["floatF"].search(cmd)
if match: if match:
@@ -2495,34 +2511,34 @@ class MachineCom(object):
except ValueError: except ValueError:
pass pass
def _gcode_M0_queuing(self, cmd, cmd_type=None): def _gcode_M0_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
self.setPause(True) 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. 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 _gcode_M1_queuing = _gcode_M0_queuing
def _gcode_M25_queuing(self, cmd, cmd_type=None): def _gcode_M25_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
# M25 while not printing from SD will be handled as pause. This way it can be used as another marker # 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. # for GCODE induced pausing. Send it to the printer anyway though.
if self.isPrinting() and not self.isSdPrinting(): if self.isPrinting() and not self.isSdPrinting():
self.setPause(True) self.setPause(True)
def _gcode_M28_sent(self, cmd, cmd_type=None): def _gcode_M28_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
if not self.isStreaming(): 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._log("Detected manual streaming. Disabling temperature polling. Finish writing with M29. Do NOT attempt to print while manually streaming!")
self._manualStreaming = True self._manualStreaming = True
def _gcode_M29_sent(self, cmd, cmd_type=None): def _gcode_M29_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
if self._manualStreaming: if self._manualStreaming:
self._log("Manual streaming done. Re-enabling temperature polling. All is well.") self._log("Manual streaming done. Re-enabling temperature polling. All is well.")
self._manualStreaming = False self._manualStreaming = False
def _gcode_M140_queuing(self, cmd, cmd_type=None): def _gcode_M140_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
if not self._printerProfileManager.get_current_or_default()["heatedBed"]: if not self._printerProfileManager.get_current_or_default()["heatedBed"]:
self._log("Warn: Not sending \"{}\", printer profile has no heated bed".format(cmd)) 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 return None, # Don't send bed commands if we don't have a heated bed
_gcode_M190_queuing = _gcode_M140_queuing _gcode_M190_queuing = _gcode_M140_queuing
def _gcode_M104_sent(self, cmd, cmd_type=None, wait=False, support_r=False): def _gcode_M104_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, wait=False, support_r=False, *args, **kwargs):
toolNum = self._currentTool toolNum = self._currentTool
toolMatch = regexes_parameters["intT"].search(cmd) toolMatch = regexes_parameters["intT"].search(cmd)
@@ -2545,7 +2561,7 @@ class MachineCom(object):
except ValueError: except ValueError:
pass pass
def _gcode_M140_sent(self, cmd, cmd_type=None, wait=False, support_r=False): def _gcode_M140_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, wait=False, support_r=False, *args, **kwargs):
match = regexes_parameters["floatS"].search(cmd) match = regexes_parameters["floatS"].search(cmd)
if not match and support_r: if not match and support_r:
match = regexes_parameters["floatR"].search(cmd) match = regexes_parameters["floatR"].search(cmd)
@@ -2558,24 +2574,24 @@ class MachineCom(object):
except ValueError: except ValueError:
pass pass
def _gcode_M109_sent(self, cmd, cmd_type=None): def _gcode_M109_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
self._heatupWaitStartTime = time.time() self._heatupWaitStartTime = time.time()
self._long_running_command = True self._long_running_command = True
self._heating = True self._heating = True
self._gcode_M104_sent(cmd, cmd_type, wait=True, support_r=True) self._gcode_M104_sent(cmd, cmd_type, wait=True, support_r=True)
def _gcode_M190_sent(self, cmd, cmd_type=None): def _gcode_M190_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
self._heatupWaitStartTime = time.time() self._heatupWaitStartTime = time.time()
self._long_running_command = True self._long_running_command = True
self._heating = True self._heating = True
self._gcode_M140_sent(cmd, cmd_type, wait=True, support_r=True) self._gcode_M140_sent(cmd, cmd_type, wait=True, support_r=True)
def _gcode_M116_sent(self, cmd, cmd_type=None): def _gcode_M116_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
self._heatupWaitStartTime = time.time() self._heatupWaitStartTime = time.time()
self._long_running_command = True self._long_running_command = True
self._heating = True self._heating = True
def _gcode_M155_sending(self, cmd, cmd_type=None): def _gcode_M155_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
match = regexes_parameters["intS"].search(cmd) match = regexes_parameters["intS"].search(cmd)
if match: if match:
try: try:
@@ -2585,7 +2601,7 @@ class MachineCom(object):
except: except:
pass pass
def _gcode_M110_sending(self, cmd, cmd_type=None): def _gcode_M110_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
newLineNumber = 0 newLineNumber = 0
match = regexes_parameters["intN"].search(cmd) match = regexes_parameters["intN"].search(cmd)
if match: if match:
@@ -2604,7 +2620,7 @@ class MachineCom(object):
self._lastLines.clear() self._lastLines.clear()
self._resendDelta = None self._resendDelta = None
def _gcode_M112_queuing(self, cmd, cmd_type=None): def _gcode_M112_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
# emergency stop, jump the queue with the M112 # emergency stop, jump the queue with the M112
self._do_send_without_checksum("M112") self._do_send_without_checksum("M112")
self._do_increment_and_send_with_checksum("M112") self._do_increment_and_send_with_checksum("M112")
@@ -2633,7 +2649,7 @@ class MachineCom(object):
# I hope it got it the first time because as far as I can tell, there is no way to know # I hope it got it the first time because as far as I can tell, there is no way to know
return None, return None,
def _gcode_G4_sent(self, cmd, cmd_type=None): def _gcode_G4_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
# we are intending to dwell for a period of time, increase the timeout to match # we are intending to dwell for a period of time, increase the timeout to match
p_match = regexes_parameters["floatP"].search(cmd) p_match = regexes_parameters["floatP"].search(cmd)
s_match = regexes_parameters["floatS"].search(cmd) s_match = regexes_parameters["floatS"].search(cmd)
@@ -2649,7 +2665,7 @@ class MachineCom(object):
##~~ command phase handlers ##~~ command phase handlers
def _command_phase_sending(self, cmd, cmd_type=None, gcode=None): def _command_phase_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
if gcode is not None and gcode in self._long_running_commands: if gcode is not None and gcode in self._long_running_commands:
self._long_running_command = True self._long_running_command = True
@@ -2925,6 +2941,88 @@ class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
duration=duration) 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)) 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): def get_new_timeout(type, intervals):
now = time.time() now = time.time()
return now + intervals.get(type, 0.0) return now + intervals.get(type, 0.0)
@@ -3277,35 +3375,43 @@ def gcode_command_for_cmd(cmd):
Returns: Returns:
str or None: The GCODE command identifier if it could be parsed, or None if not. 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: if not cmd:
return None return None, None
gcode = regex_command.search(cmd) match = regex_command.search(cmd)
if not gcode: if not match:
return None return None, None
values = gcode.groupdict() values = match.groupdict()
if "commandGM" in values and values["commandGM"]: if "codeGM" in values and values["codeGM"]:
return values["commandGM"] gcode = values["codeGM"]
elif "commandT" in values and values["commandT"]: elif "codeT" in values and values["codeT"]:
return values["commandT"] gcode = values["codeT"]
elif settings().getBoolean(["feature", "supportFAsCommand"]) and "commandF" in values and values["commandF"]: elif settings().getBoolean(["feature", "supportFAsCommand"]) and "codeF" in values and values["codeF"]:
return values["commandF"] gcode = values["codeF"]
else: else:
# this should never happen # this should never happen
return None return None, None
return gcode, values.get("subcode", None)
def _normalize_command_handler_result(command, command_type, gcode, handler_results): def _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results):
""" """
Normalizes a command handler result. Normalizes a command handler result.
Handler results can be either ``None``, a single result entry or a list of result Handler results can be either ``None``, a single result entry or a list of result
entries. entries.
``None`` results are ignored, the provided ``command``, ``command_type`` ``None`` results are ignored, the provided ``command``, ``command_type``,
and ``gcode`` are returned in that case (as single-entry list with one ``gcode`` and ``subcode`` are returned in that case (as single-entry list with
3-tuple as entry). one 4-tuple as entry).
Single result entries are either: Single result entries are either:
@@ -3317,31 +3423,31 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
the normalized result. the normalized result.
The method returns a list of normalized result entries. Normalized result The method returns a list of normalized result entries. Normalized result
entries always are a 3-tuple consisting of ``command``, ``command_type`` entries always are a 4-tuple consisting of ``command``, ``command_type``,
and ``gcode``, the latter two being allowed to be ``None``. The list may ``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may
be empty in which case the command is to be suppressed. be empty in which case the command is to be suppressed.
Examples: Examples:
>>> _normalize_command_handler_result("M105", None, "M105", None) >>> _normalize_command_handler_result("M105", None, "M105", None, None)
[('M105', None, 'M105')] [('M105', None, 'M105', None)]
>>> _normalize_command_handler_result("M105", None, "M105", "M110") >>> _normalize_command_handler_result("M105", None, "M105", None, "M110")
[('M110', None, 'M110')] [('M110', None, 'M110', None)]
>>> _normalize_command_handler_result("M105", None, "M105", ["M110"]) >>> _normalize_command_handler_result("M105", None, "M105", None, ["M110"])
[('M110', None, 'M110')] [('M110', None, 'M110', None)]
>>> _normalize_command_handler_result("M105", None, "M105", ["M110", "M117 Foobar"]) >>> _normalize_command_handler_result("M105", None, "M105", None, ["M110", "M117 Foobar"])
[('M110', None, 'M110'), ('M117 Foobar', None, 'M117')] [('M110', None, 'M110', None), ('M117 Foobar', None, 'M117', None)]
>>> _normalize_command_handler_result("M105", None, "M105", [("M110",), "M117 Foobar"]) >>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), "M117 Foobar"])
[('M110', None, 'M110'), ('M117 Foobar', None, 'M117')] [('M110', None, 'M110', None), ('M117 Foobar', None, 'M117', None)]
>>> _normalize_command_handler_result("M105", None, "M105", [("M110", "lineno_reset"), "M117 Foobar"]) >>> _normalize_command_handler_result("M105", None, "M105", None, [("M110", "lineno_reset"), "M117 Foobar"])
[('M110', 'lineno_reset', 'M110'), ('M117 Foobar', None, 'M117')] [('M110', 'lineno_reset', 'M110', None), ('M117 Foobar', None, 'M117', None)]
>>> _normalize_command_handler_result("M105", None, "M105", []) >>> _normalize_command_handler_result("M105", None, "M105", None, [])
[] []
>>> _normalize_command_handler_result("M105", None, "M105", ["M110", None]) >>> _normalize_command_handler_result("M105", None, "M105", None, ["M110", None])
[('M110', None, 'M110')] [('M110', None, 'M110', None)]
>>> _normalize_command_handler_result("M105", None, "M105", [("M110",), (None, "ignored")]) >>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), (None, "ignored")])
[('M110', None, 'M110')] [('M110', None, 'M110', None)]
>>> _normalize_command_handler_result("M105", None, "M105", [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of unexpected", "length"), ("M110", "lineno_reset")]) >>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of unexpected", "length"), ("M110", "lineno_reset")])
[('M110', None, 'M110'), ('M117 Foobar', 'display_message', 'M117'), ('M110', 'lineno_reset', 'M110')] [('M110', None, 'M110', None), ('M117 Foobar', 'display_message', 'M117', None), ('M110', 'lineno_reset', 'M110', None)]
Arguments: Arguments:
command (str or None): The command for which the handler result was command (str or None): The command for which the handler result was
@@ -3350,16 +3456,18 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
result was generated result was generated
gcode (str or None): The GCODE for which the handler result was gcode (str or None): The GCODE for which the handler result was
generated 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 handler_results: The handler result(s) to normalized. Can be either
a single result entry or a list of result entries. a single result entry or a list of result entries.
Returns: Returns:
(list) - A list of normalized handler result entries, which are (list) - A list of normalized handler result entries, which are
3-tuples consisting of ``command``, ``command_type`` and 4-tuples consisting of ``command``, ``command_type``, ``gcode``
``gcode``, the latter two of which may be ``None``. and ``subcode``, the latter three of which may be ``None``.
""" """
original = (command, command_type, gcode) original = (command, command_type, gcode, subcode)
if handler_results is None: if handler_results is None:
# handler didn't return anything, we'll just continue # handler didn't return anything, we'll just continue
@@ -3380,8 +3488,8 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
if isinstance(handler_result, basestring): if isinstance(handler_result, basestring):
# entry is just a string, replace command with it # entry is just a string, replace command with it
command = handler_result command = handler_result
gcode = gcode_command_for_cmd(command) gcode, subcode = gcode_and_subcode_for_cmd(command)
result.append((command, command_type, gcode)) result.append((command, command_type, gcode, subcode))
elif isinstance(handler_result, tuple): elif isinstance(handler_result, tuple):
# entry is a tuple, extract command and command_type # entry is a tuple, extract command and command_type
@@ -3401,11 +3509,11 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
# command is None, ignore it and continue # command is None, ignore it and continue
continue continue
gcode = gcode_command_for_cmd(command) gcode, subcode = gcode_and_subcode_for_cmd(command)
result.append((command, command_type, gcode)) result.append((command, command_type, gcode, subcode))
# reset to original # reset to original
command, command_type, gcode = original command, command_type, gcode, subcode = original
return result return result
+10 -91
View File
@@ -222,7 +222,6 @@ class gcode(object):
lineNo = 0 lineNo = 0
readBytes = 0 readBytes = 0
pos = Vector3D(0.0, 0.0, 0.0) pos = Vector3D(0.0, 0.0, 0.0)
toolOffset = Vector3D(0.0, 0.0, 0.0)
currentE = [0.0] currentE = [0.0]
totalExtrusion = [0.0] totalExtrusion = [0.0]
maxExtrusion = [0.0] maxExtrusion = [0.0]
@@ -320,16 +319,16 @@ class gcode(object):
# Use new coordinates if provided. If not provided, use prior coordinates (minus tool offset) # Use new coordinates if provided. If not provided, use prior coordinates (minus tool offset)
# in absolute and 0.0 in relative mode. # in absolute and 0.0 in relative mode.
newPos = Vector3D(x if x is not None else (0.0 if relativeMode else pos.x - toolOffset.x), 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 - toolOffset.y), 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 - toolOffset.z)) z if z is not None else (0.0 if relativeMode else pos.z))
if relativeMode: if relativeMode:
# Relative mode: scale and add to current position # Relative mode: scale and add to current position
pos += newPos * scale pos += newPos * scale
else: else:
# Absolute mode: scale coordinates and apply tool offsets # Absolute mode: scale coordinates and apply tool offsets
pos = newPos * scale + toolOffset pos = newPos * scale
if f is not None and f != 0: if f is not None and f != 0:
feedrate = f feedrate = f
@@ -442,14 +441,16 @@ class gcode(object):
elif T is not None: elif T is not None:
if T > max_extruders: if T > max_extruders:
self._logger.warn("GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis" % T) self._logger.warn("GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis" % T)
elif T == currentExtruder:
pass
else: else:
toolOffset.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0 pos.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
toolOffset.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0 pos.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
currentExtruder = T currentExtruder = T
toolOffset.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0 pos.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
toolOffset.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0 pos.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
if len(currentE) <= currentExtruder: if len(currentE) <= currentExtruder:
for i in range(len(currentE), currentExtruder + 1): for i in range(len(currentE), currentExtruder + 1):
@@ -511,85 +512,3 @@ def getCodeFloat(line, code):
except: except:
return None 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")
+108 -103
View File
@@ -10,6 +10,7 @@ import sarge
import sys import sys
import logging import logging
import site import site
import threading
import pkg_resources import pkg_resources
@@ -17,6 +18,7 @@ from .commandline import CommandlineCaller, clean_ansi
from octoprint.util import to_unicode from octoprint.util import to_unicode
_cache = dict(version=dict(), setup=dict()) _cache = dict(version=dict(), setup=dict())
_cache_mutex = threading.RLock()
class UnknownPip(Exception): class UnknownPip(Exception):
pass pass
@@ -173,8 +175,6 @@ class PipCaller(CommandlineCaller):
self._logger.error("This version of pip is known to have bugs that make it incompatible with how it needs to be used by OctoPrint. Please upgrade your pip version.") self._logger.error("This version of pip is known to have bugs that make it incompatible with how it needs to be used by OctoPrint. Please upgrade your pip version.")
return return
self._logger.info("Version of pip is {}".format(version_segment))
# Now figure out if pip belongs to a virtual environment and if the # Now figure out if pip belongs to a virtual environment and if the
# default installation directory is writable. # default installation directory is writable.
# #
@@ -194,10 +194,6 @@ class PipCaller(CommandlineCaller):
self._logger.error("Cannot use pip") self._logger.error("Cannot use pip")
return return
self._logger.info("pip installs to {}, --user flag needed => {}, virtual env => {}".format(pip_install_dir,
"yes" if pip_user else "no",
"yes" if pip_virtual_env else "no"))
self._command = pip_command self._command = pip_command
self._version = pip_version self._version = pip_version
self._version_string = version_segment self._version_string = version_segment
@@ -251,122 +247,131 @@ class PipCaller(CommandlineCaller):
if isinstance(pip_command_str, list): if isinstance(pip_command_str, list):
pip_command_str = " ".join(pip_command_str) pip_command_str = " ".join(pip_command_str)
if not self.ignore_cache and pip_command_str in _cache["version"]: with _cache_mutex:
self._logger.debug("Using cached pip version information for {}".format(pip_command_str)) if not self.ignore_cache and pip_command_str in _cache["version"]:
return _cache["version"][pip_command_str] self._logger.debug("Using cached pip version information for {}".format(pip_command_str))
return _cache["version"][pip_command_str]
sarge_command = self.to_sarge_command(pip_command, "--version") sarge_command = self.to_sarge_command(pip_command, "--version")
p = sarge.run(sarge_command, stdout=sarge.Capture(), stderr=sarge.Capture()) p = sarge.run(sarge_command, stdout=sarge.Capture(), stderr=sarge.Capture())
if p.returncode != 0: if p.returncode != 0:
self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text)) self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
return None, None return None, None
output = PipCaller._preprocess(p.stdout.text) output = PipCaller._preprocess(p.stdout.text)
# output should look something like this: # output should look something like this:
# #
# pip <version> from <path> (<python version>) # pip <version> from <path> (<python version>)
# #
# we'll just split on whitespace and then try to use the second entry # we'll just split on whitespace and then try to use the second entry
if not output.startswith("pip"): if not output.startswith("pip"):
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output)) self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
split_output = map(lambda x: x.strip(), output.split()) split_output = map(lambda x: x.strip(), output.split())
if len(split_output) < 2: if len(split_output) < 2:
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output)) self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
version_segment = split_output[1] version_segment = split_output[1]
try: try:
pip_version = pkg_resources.parse_version(version_segment) pip_version = pkg_resources.parse_version(version_segment)
except: except:
self._logger.exception("Error while trying to parse version string from pip command") self._logger.exception("Error while trying to parse version string from pip command")
return None, None return None, None
result = pip_version, version_segment self._logger.info("Version of pip is {}".format(version_segment))
_cache["version"][pip_command_str] = result
return result result = pip_version, version_segment
_cache["version"][pip_command_str] = result
return result
def _check_pip_setup(self, pip_command): def _check_pip_setup(self, pip_command):
pip_command_str = pip_command pip_command_str = pip_command
if isinstance(pip_command_str, list): if isinstance(pip_command_str, list):
pip_command_str = " ".join(pip_command_str) pip_command_str = " ".join(pip_command_str)
if not self.ignore_cache and pip_command_str in _cache["setup"]: with _cache_mutex:
self._logger.debug("Using cached pip setup information for {}".format(pip_command_str)) if not self.ignore_cache and pip_command_str in _cache["setup"]:
return _cache["setup"][pip_command_str] self._logger.debug("Using cached pip setup information for {}".format(pip_command_str))
return _cache["setup"][pip_command_str]
# This is horribly ugly and I'm sorry... # This is horribly ugly and I'm sorry...
# #
# While we can figure out the install directory, if that's writable and if a virtual environment # While we can figure out the install directory, if that's writable and if a virtual environment
# is active for pip that belongs to our sys.executable python instance by just checking some # is active for pip that belongs to our sys.executable python instance by just checking some
# variables, we can't for stuff like third party software we allow to update via the software # variables, we can't for stuff like third party software we allow to update via the software
# update plugin. # update plugin.
# #
# What we do instead for these situations is try to install (and of course uninstall) the # What we do instead for these situations is try to install (and of course uninstall) the
# testballoon dummy package, which collects that information for us. For pip <= 7 we could # testballoon dummy package, which collects that information for us. For pip <= 7 we could
# have the testballoon provide us with the info needed through stdout, if pip was called # have the testballoon provide us with the info needed through stdout, if pip was called
# with --verbose anything printed to stdout within setup.py would be output. Pip 8 managed # with --verbose anything printed to stdout within setup.py would be output. Pip 8 managed
# to break this mechanism. Any (!) output within setup.py appears to be suppressed now, and # to break this mechanism. Any (!) output within setup.py appears to be suppressed now, and
# no combination of --log and multiple --verbose or -v arguments could get it to bring the # no combination of --log and multiple --verbose or -v arguments could get it to bring the
# output back. # output back.
# #
# So here's what we do now instead. Our sarge call sets an environment variable # So here's what we do now instead. Our sarge call sets an environment variable
# "TESTBALLOON_OUTPUT" that points to a temporary file. If the testballoon sees that # "TESTBALLOON_OUTPUT" that points to a temporary file. If the testballoon sees that
# variable set, it opens the file and writes to it the output it so far printed on stdout. # variable set, it opens the file and writes to it the output it so far printed on stdout.
# We then open the file and read in the data that way. # We then open the file and read in the data that way.
# #
# Yeah, I'm not happy with that either. But as long as there's no way to otherwise figure # Yeah, I'm not happy with that either. But as long as there's no way to otherwise figure
# out for a generic pip command whether OctoPrint can even install anything with that # out for a generic pip command whether OctoPrint can even install anything with that
# and if so how, well, that's how we'll have to do things. # and if so how, well, that's how we'll have to do things.
import os import os
testballoon = os.path.join(os.path.realpath(os.path.dirname(__file__)), "piptestballoon") testballoon = os.path.join(os.path.realpath(os.path.dirname(__file__)), "piptestballoon")
from octoprint.util import temppath from octoprint.util import temppath
with temppath() as testballoon_output_file: with temppath() as testballoon_output_file:
sarge_command = self.to_sarge_command(pip_command, "install", ".") sarge_command = self.to_sarge_command(pip_command, "install", ".")
try: try:
# our testballoon is no real package, so this command will fail - that's ok though, # our testballoon is no real package, so this command will fail - that's ok though,
# we only need the output produced within the pip environment # we only need the output produced within the pip environment
sarge.run(sarge_command, sarge.run(sarge_command,
stdout=sarge.Capture(), stdout=sarge.Capture(),
stderr=sarge.Capture(), stderr=sarge.Capture(),
cwd=testballoon, cwd=testballoon,
env=dict(TESTBALLOON_OUTPUT=testballoon_output_file)) env=dict(TESTBALLOON_OUTPUT=testballoon_output_file))
except: except:
self._logger.exception("Error while trying to install testballoon to figure out pip setup") self._logger.exception("Error while trying to install testballoon to figure out pip setup")
return False, False, False, None
data = dict()
with open(testballoon_output_file) as f:
for line in f:
key, value = line.split("=", 2)
data[key] = value
install_dir_str = data.get("PIP_INSTALL_DIR", None)
virtual_env_str = data.get("PIP_VIRTUAL_ENV", None)
writable_str = data.get("PIP_WRITABLE", None)
if install_dir_str is not None and virtual_env_str is not None and writable_str is not None:
install_dir = install_dir_str.strip()
virtual_env = virtual_env_str.strip() == "True"
writable = writable_str.strip() == "True"
can_use_user_flag = not virtual_env and site.ENABLE_USER_SITE
ok = writable or can_use_user_flag
user_flag = not writable and can_use_user_flag
self._logger.info("pip installs to {}, --user flag needed => {}, "
"virtual env => {}".format(install_dir,
"yes" if user_flag else "no",
"yes" if virtual_env else "no"))
# ok, enable user flag, virtual env yes/no, installation dir
result = ok, user_flag, virtual_env, install_dir
_cache["setup"][pip_command_str] = result
return result
else:
self._logger.debug("Could not detect desired output from testballoon install, got this instead: {!r}".format(data))
return False, False, False, None return False, False, False, None
data = dict()
with open(testballoon_output_file) as f:
for line in f:
key, value = line.split("=", 2)
data[key] = value
install_dir_str = data.get("PIP_INSTALL_DIR", None)
virtual_env_str = data.get("PIP_VIRTUAL_ENV", None)
writable_str = data.get("PIP_WRITABLE", None)
if install_dir_str is not None and virtual_env_str is not None and writable_str is not None:
install_dir = install_dir_str.strip()
virtual_env = virtual_env_str.strip() == "True"
writable = writable_str.strip() == "True"
can_use_user_flag = not virtual_env and site.ENABLE_USER_SITE
# ok, enable user flag, virtual env yes/no, installation dir
result = writable or can_use_user_flag, \
not writable and can_use_user_flag, \
virtual_env, \
install_dir
_cache["setup"][pip_command_str] = result
return result
else:
self._logger.debug("Could not detect desired output from testballoon install, got this instead: {!r}".format(data))
return False, False, False, None
def _preprocess_lines(self, *lines): def _preprocess_lines(self, *lines):
return map(self._preprocess, lines) return map(self._preprocess, lines)
+41
View File
@@ -0,0 +1,41 @@
# 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 sys
try:
import fcntl
except ImportError:
fcntl = None
# set_close_exec
if fcntl is not None and hasattr(fcntl, "FD_CLOEXEC"):
def set_close_exec(handle):
flags = fcntl.fcntl(handle, fcntl.F_GETFD)
flags |= fcntl.FD_CLOEXEC
fcntl.fcntl(handle, fcntl.F_SETFD, flags)
elif sys.platform == "win32":
def set_close_exec(handle):
import ctypes
import ctypes.wintypes
# see https://msdn.microsoft.com/en-us/library/ms724935(v=vs.85).aspx
SetHandleInformation = ctypes.windll.kernel32.SetHandleInformation
SetHandleInformation.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)
SetHandleInformation.restype = ctypes.c_bool
HANDLE_FLAG_INHERIT = 0x00000001
result = SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0)
if not result:
raise ctypes.GetLastError()
else:
def set_close_exec(handle):
# no-op
pass
+10 -1
View File
@@ -530,6 +530,13 @@ class OctoPrintFlaskRequestTest(unittest.TestCase):
def test_cookie_suffix(self): def test_cookie_suffix(self):
request = OctoPrintFlaskRequest(standard_environ) request = OctoPrintFlaskRequest(standard_environ)
self.assertEquals("_P5000", request.cookie_suffix) self.assertEquals("_P5000", request.cookie_suffix)
def test_cookie_suffix_with_root(self):
script_root_environ = dict(standard_environ)
script_root_environ["SCRIPT_NAME"] = "/path/to/octoprint"
request = OctoPrintFlaskRequest(script_root_environ)
self.assertEquals("_P5000_R|path|to|octoprint", request.cookie_suffix)
def test_cookies(self): def test_cookies(self):
environ = dict(standard_environ) environ = dict(standard_environ)
@@ -561,8 +568,10 @@ class OctoPrintFlaskResponseTest(unittest.TestCase):
def test_cookie_set_and_delete(self, path, scriptroot): def test_cookie_set_and_delete(self, path, scriptroot):
environ = dict(standard_environ) environ = dict(standard_environ)
expected_suffix = "_P5000"
if scriptroot is not None: if scriptroot is not None:
environ.update(dict(SCRIPT_NAME=scriptroot)) environ.update(dict(SCRIPT_NAME=scriptroot))
expected_suffix += "_R" + scriptroot.replace("/", "|")
request = OctoPrintFlaskRequest(environ) request = OctoPrintFlaskRequest(environ)
@@ -586,7 +595,7 @@ class OctoPrintFlaskResponseTest(unittest.TestCase):
response.set_cookie("some_key", "some_value", **kwargs) response.set_cookie("some_key", "some_value", **kwargs)
# set_cookie should have key and path values adjusted # set_cookie should have key and path values adjusted
set_cookie_mock.assert_called_once_with(response, "some_key_P5000", "some_value", path=expected_path_set) set_cookie_mock.assert_called_once_with(response, "some_key" + expected_suffix, "some_value", path=expected_path_set)
# test delete_cookie # test delete_cookie
with mock.patch("flask.Response.set_cookie") as set_cookie_mock: with mock.patch("flask.Response.set_cookie") as set_cookie_mock:
+21 -1
View File
@@ -198,12 +198,32 @@ class TestCommHelpers(unittest.TestCase):
result = gcode_command_for_cmd(cmd) result = gcode_command_for_cmd(cmd)
self.assertEqual(expected, result) self.assertEqual(expected, result)
@data(
("G0 X0", "G0", None),
("M105", "M105", None),
("T2", "T", None),
("M80.1", "M80", "1"),
("G28.2", "G28", "2"),
("T0.3", "T", None),
("M80.nosubcode", "M80", None),
(None, None, None),
("No match", None, None)
)
@unpack
def test_gcode_and_subcode_for_cmd(self, cmd, expected_gcode, expected_subcode):
from octoprint.util.comm import gcode_and_subcode_for_cmd
actual_gcode, actual_subcode = gcode_and_subcode_for_cmd(cmd)
self.assertEqual(expected_gcode, actual_gcode)
self.assertEqual(expected_subcode, actual_subcode)
@data( @data(
("T:23.0 B:60.0", 0, dict(T0=(23.0, None), B=(60.0, None)), 0), ("T:23.0 B:60.0", 0, dict(T0=(23.0, None), B=(60.0, None)), 0),
("T:23.0 B:60.0", 1, dict(T1=(23.0, None), B=(60.0, None)), 1), ("T:23.0 B:60.0", 1, dict(T1=(23.0, None), B=(60.0, None)), 1),
("T:23.0/220.0 B:60.0/70.0", 0, dict(T0=(23.0, 220.0), B=(60.0, 70.0)), 0), ("T:23.0/220.0 B:60.0/70.0", 0, dict(T0=(23.0, 220.0), B=(60.0, 70.0)), 0),
("ok T:23.0/220.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 0, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2), ("ok T:23.0/220.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 0, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2),
("ok T:50.2/210.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 1, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2) ("ok T:50.2/210.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 1, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2),
("ok T:-55.7/0 T0:-55.7/0 T1:150.0/210.0", 0, dict(T0=(-55.7, 0), T1=(150.0, 210.0)), 1),
("ok T:150.0/210.0 T0:-55.7/0 T1:150.0/210.0", 1, dict(T0=(-55.7, 0), T1=(150.0, 210.0)), 1)
) )
@unpack @unpack
def test_process_temperature_line(self, line, current, expected_result, expected_max): def test_process_temperature_line(self, line, current, expected_result, expected_max):
Binary file not shown.
File diff suppressed because it is too large. Load diff
+888 -520
View File
File diff suppressed because it is too large. Load diff