Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f5d03d054 | ||
|
|
558a8957f9 | ||
|
|
8d2681ae3f | ||
|
|
0de6718af3 | ||
|
|
229f3a2744 | ||
|
|
c00b3de40c | ||
|
|
3d3c93c67d | ||
|
|
1e84f2ee6e | ||
|
|
4541148aa5 | ||
|
|
e8a4750379 | ||
|
|
1d0657a8eb | ||
|
|
65377b396f | ||
|
|
a66e6b603f | ||
|
|
528e99898f | ||
|
|
8beedce98f | ||
|
|
69412d0b8b | ||
|
|
23744cdba9 | ||
|
|
0f53c1aaa6 | ||
|
|
462ab5aa37 | ||
|
|
01b221ab30 | ||
|
|
d37a6a9114 | ||
|
|
9875617046 | ||
|
|
daeb3dbc91 | ||
|
|
ccf77a5dae | ||
|
|
6cc3846512 | ||
|
|
4ed0ed5f99 | ||
|
|
5c39e9a8a3 | ||
|
|
5b910b557e | ||
|
|
4a0d91315c | ||
|
|
1b9bfc6d04 | ||
|
|
def5fd4ad3 | ||
|
|
9ed5e37fc8 | ||
|
|
5424d42b60 | ||
|
|
8ff1834442 | ||
|
|
ec04364b47 | ||
|
|
2fc3819afd | ||
|
|
a24beb25a3 | ||
|
|
07bbbff038 | ||
|
|
c9c2946db2 | ||
|
|
8034a4bb98 | ||
|
|
a88cd9fcfc | ||
|
|
59e4394cdd | ||
|
|
d991eab87e | ||
|
|
71581c9c93 | ||
|
|
7489d2da80 | ||
|
|
7c1bb5c115 | ||
|
|
b8278b6a93 | ||
|
|
7709150a2b | ||
|
|
fc06c91ae8 | ||
|
|
2564820d16 | ||
|
|
f83625acba | ||
|
|
97bf331307 | ||
|
|
e4d34f4130 | ||
|
|
b68ee4df98 | ||
|
|
0d13c3b439 | ||
|
|
1a75dcd5ee | ||
|
|
d1cb8ca98a | ||
|
|
f1a1b851ee | ||
|
|
07382d3918 | ||
|
|
ec12e52865 | ||
|
|
d5a73b8b4f | ||
|
|
b87348be3b | ||
|
|
0ad057cdbb | ||
|
|
1a5f4e0b9f | ||
|
|
f688786fd5 | ||
|
|
a58b167bed | ||
|
|
83a08cd927 | ||
|
|
c194cabdcf | ||
|
|
174ffdf06f | ||
|
|
7ae6240de2 | ||
|
|
f9253adf72 | ||
|
|
d52462b9f5 | ||
|
|
cc5f119f1b | ||
|
|
a8ff23abe4 | ||
|
|
e6c4e0a808 | ||
|
|
58835cfd8e | ||
|
|
e04bdb3571 | ||
|
|
06f7abdb2d | ||
|
|
2429ebc1a2 | ||
|
|
c6b8b1725a | ||
|
|
4a67762ead | ||
|
|
0a9475661f | ||
|
|
2c6fb68544 | ||
|
|
b4215c885c | ||
|
|
c8273785cd | ||
|
|
5446dc645c | ||
|
|
fac83e91f2 | ||
|
|
153ebc3692 | ||
|
|
b74a5db4d8 | ||
|
|
47a3e0340e | ||
|
|
1c57769af3 | ||
|
|
bc82a18a03 | ||
|
|
6976ac9edd | ||
|
|
d28e0988fb | ||
|
|
2952b2622e | ||
|
|
e847b355cd | ||
|
|
970880dee6 | ||
|
|
4689a405a3 | ||
|
|
fae27c77b5 | ||
|
|
3f0bfa0fc8 | ||
|
|
35cf623f81 | ||
|
|
7abd35196e | ||
|
|
21e342ff8a | ||
|
|
6114ee4f32 | ||
|
|
5ac934bcc4 | ||
|
|
fd1016695f | ||
|
|
728172136a | ||
|
|
d3cc96523e | ||
|
|
7e2382fed4 | ||
|
|
7fb2745f8f |
No files matched your search
+83
-42
@@ -1,8 +1,8 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.3.0rc1 (2016-10-19)
|
||||
## 1.3.0 (2016-12-08)
|
||||
|
||||
### New Features
|
||||
### Features
|
||||
|
||||
* You can now create folders in the file list, upload files into said folders and thus better manage your projects' files.
|
||||
* New wizard dialog for system setups that can also be extended by plugins. Replaces the first run dialog for setting up access control and can also be triggered in other cases than only the first run, e.g. if plugins necessitate user input to function properly. Added wizards to help configuring the following components in OctoPrint on first run: access control, webcam URLs & ffmpeg path, server commands (restart, shutdown, reboot), printer profile. Also extended the bundled Cura plugin to add a wizard for its first setup to adjust path and import a slicing profile, and the bundled Software Update plugin to ask the user for details regarding the OctoPrint update configuration. Also see below.
|
||||
@@ -13,17 +13,27 @@
|
||||
* New features within the plugin system:
|
||||
* Plugins may now give hints in which order various hooks or mixin methods should be called by optionally providing an integer value that will be used for sorting the callbacks prior to execution.
|
||||
* Plugins may now define configuration overlays to be applied on top of the default configuration but before ``config.yaml``.
|
||||
* New mixin ``UiPlugin` for plugins that want to provide an alternative web interface delivered by the server.
|
||||
* New mixin `UiPlugin` for plugins that want to provide an alternative web interface delivered by the server.
|
||||
* New mixin ``WizardPlugin`` for plugins that want to provide wizard components to OctoPrint's new wizard dialog.
|
||||
* New hook ``octoprint.cli.commands`` for registering a command with the new OctoPrint CLI
|
||||
* New hook ``octoprint.comm.protocol.gcode.received`` for receiving messages from the printer
|
||||
* New hook ``octoprint.printer.factory`` for providing a custom factory to contruct the global ``PrinterInterface`` implementation.
|
||||
* New ``TemplatePlugin`` template type: ``wizard``
|
||||
* New Javascript client library for utilizing the server's API, can be reused by `UiPlugin`s.
|
||||
* OctoPrint will now track the current print head position on pause and cancel and provide it as new template variables ``pause_position``/``cancel_position`` for the relevant GCODE scripts. This will allow more intelligent pause codes that park the print head at a rest position during pause and move it back to the exact position it was before the pause on resume ([Example](https://gist.github.com/foosel/1c09e269b1c0bb7a471c20eef50c8d3e)). Note that this is NOT enabled by default and for now will necessitate adjusting the pause and resume GCODE scripts yourself since position tracking with multiple extruders or when printing from SD is currently not fool proof thanks to firmware limitations regarding reliable tracking of the various ``E`` values and the currently selected tool ``T``. In order to fully implement this feature, the following improvements were also done:
|
||||
* New ``PositionUpdated`` event when OctoPrint receives a response to an ``M114`` position query.
|
||||
* Extended ``PrintPaused`` and ``PrintCancelled`` events with position data from ``M114`` position query on print interruption/end.
|
||||
* Added (optional) firmware auto detection. If enabled (which it is by default), OctoPrint will now send an ``M115`` to the printer on initial connection in order to try to figure out what kind of firmware it is. For FIRMWARE_NAME values containing "repetier" (case insensitive), all Repetier-specific flags will be set on the comm layer. For FIRMWARE_NAME values containing "reprapfirmware" (also case insensitive), all RepRapFirmware-specific flags will be set on the comm layer. For now no other handling will be performed.
|
||||
* Added safe mode flag ``--safe`` and config setting ``startOnceInSafeMode`` that disables all third party plugins when active. The config setting will automatically be removed from `config.yaml` after the server has started through successfully.
|
||||
* Added ``octoprint config`` CLI that allows easier manipulation of config.yaml entries from the command line. Example: ``octoprint config set --bool server.startOnceInSafeMode true``
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#1048](https://github.com/foosel/OctoPrint/issues/1048) - Added "Last print time" to extended file information (see also [#1522](https://github.com/foosel/OctoPrint/pull/1522))
|
||||
* [#1422](https://github.com/foosel/OctoPrint/issues/1422) - Added option for post roll for timed timelapse to duplicate last frame instead of capturing new frames. That makes for a faster render at the cost of a still frame at the end of the rendered video. See also [#1553](https://github.com/foosel/OctoPrint/pull/1553).
|
||||
* [#1551](https://github.com/foosel/OctoPrint/issues/1551) - Allow to define a custom bounding box for valid printer head movements in the printer profile, to make print dimension check more flexible.
|
||||
* [#1583](https://github.com/foosel/OctoPrint/pull/1583) - Strip invalid `pip` arguments from `pip uninstall` commands, if provided by the user as additional pip arguments.
|
||||
* [#1593](https://github.com/foosel/OctoPrint/issues/1593) - Automatically migrate old manual system commands for restarting OctoPrint and rebooting or shutting down the server to the new system wide configuration settings. Make a backup copy of the old `config.yaml` before doing so in case a manual rollback is required.
|
||||
* New central configuration option for commands to restart OctoPrint and to restart and shut down the system OctoPrint is running on. This allows plugins (like the Software Update Plugin or the Plugin Manager) and core functionality to perform these common administrative tasks without the user needing to define everything redundantly.
|
||||
* `pip` helper now adjusts `pip install` parameters corresponding to detected `pip` version:
|
||||
* Removes `--process-dependency-links` when it's not needed
|
||||
@@ -53,6 +63,9 @@
|
||||
* Renamed ``GcodeFilesViewModel`` to ``FilesViewModel`` - plugin authors should accordingly update their dependencies from ``gcodeFilesViewModel`` to ``filesViewModel``. Using the old name still works, but will log a warning and stop working with 1.4.x.
|
||||
* Make sure ``volume.depth`` for circular beds is forced to ``volume.width`` in printer profiles
|
||||
* Support for `M116`
|
||||
* Support ``M114`` responses without whitespace between coordinates (protocol consistency - who needs it?).
|
||||
* `M600` is now marked as a long running command by default.
|
||||
* Don't focus files in the file list after deleting a file - made the list too jumpy.
|
||||
* Cura plugin: "Test" button to check if path to cura engine is valid.
|
||||
* Cura plugin: Wizard component for configuring the path to the CuraEngine binary and for importing the first slicing profile
|
||||
* GCODE viewer: Added Layer Up/Down buttons (see also [#1306] (https://github.com/foosel/OctoPrint/pull/1306))
|
||||
@@ -65,76 +78,91 @@
|
||||
* Plugin Manager: Track managable vs not managable plugins
|
||||
* Plugin Manager: Allow hiding plugins from Plugin Manager via ``config.yaml``.
|
||||
* Plugin Manager: Limit upload dialog for plugin archives to .zip, .tar.gz, .tgz and .tar extensions.
|
||||
* Plugin Manager: Allow closing of all notifications and close them automatically on detected server disconnect. No need to keep a "Restart needed" message around if a restart is in progress.
|
||||
* Software Update plugin: More verbose output for logged in administrators. Will now log the update commands and their output similar to the Plugin Manager install and uninstall dialog.
|
||||
* Software Update plugin: CLI for checking for and applying updates
|
||||
* Software Update plugin: Wizard component for configuring OctoPrint's update mechanism
|
||||
* Software Update plugin: "busy" spinner on check buttons while already checking for updates.
|
||||
* Software Update plugin: Prevent update notification when wizard is open.
|
||||
* Plugin Manager / Software Update plugin: The "There's a new version of pip" message during plugin installs and software updates is no longer displayed like an error.
|
||||
* Plugin Manager / Software Update plugin: The "busy" dialog can no longer be closed accidentally.
|
||||
* Timelapse: Better (& earlier) reporting to the user when something's up with the snapshot URL causing issues with capturing timelapse frames and hence making it impossible to render a timelapse movie on print completion.
|
||||
* Virtual printer: Usage screen for the ``!!DEBUG`` commands on ``!!DEBUG", ``!!DEBUG:help`` or ``!!DEBUG:?``
|
||||
* Virtual printer: Usage screen for the ``!!DEBUG`` commands on ``!!DEBUG``, ``!!DEBUG:help`` or ``!!DEBUG:?``
|
||||
* Updated frontend dependencies (possibly relevant for plugin authors):
|
||||
* Bootstrap to 2.3.2
|
||||
* JQuery to 2.2.4
|
||||
* Lodash to 3.10.1
|
||||
* SockJS to 1.1.1
|
||||
* Better error resilience against errors in UI components.
|
||||
* Various improvements in the GCODE interpreter which performs the GCODE analysis
|
||||
* Various adjustments towards Python 3 compatibility (still a work in progress though, see also [#1411](https://github.com/foosel/OctoPrint/pull/1411), [#1412](https://github.com/foosel/OctoPrint/pull/1412), [#1413](https://github.com/foosel/OctoPrint/pull/1413), [#1414](https://github.com/foosel/OctoPrint/pull/1414))
|
||||
* Various code refactorings
|
||||
* Various small UI improvements
|
||||
* Various documentation improvements
|
||||
|
||||
### Bug Fixes
|
||||
### Bug fixes
|
||||
|
||||
* [#1047](https://github.com/foosel/OctoPrint/issues/1047) - Fixed 90 degree webcam rotation for iOS Safari.
|
||||
* [#1148](https://github.com/foosel/OctoPrint/issues/1148) - Fixed retraction z hop setting for Z-triggered timelapses. Was not correctly propagated to the backend and hence not taking effect.
|
||||
* [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Invalidate ``/api/settings`` cache on change of the user's login state (include user roles into ETag calculation).
|
||||
* [#1586](https://github.com/foosel/OctoPrint/issues/1586) - Fixed incompatibility of update script and command line helper with non-ASCII output from called commands.
|
||||
* [#1588](https://github.com/foosel/OctoPrint/issues/1588) - Fixed feedback controls again.
|
||||
* [#1599](https://github.com/foosel/OctoPrint/issues/1599) - Properly handle exceptions that arise within the update script during runtime.
|
||||
* It's not possible anymore to select files that are not machinecode files (e.g. GCODE) for printing on the file API.
|
||||
* Changes to a user's personal settings via the UI now propagate across sessions.
|
||||
* Improved compatibility of webcam rotation CSS across newer browsers (see also [#1436](https://github.com/foosel/OctoPrint/pull/1436))
|
||||
* Fix for system menu not getting properly reloaded after entries changed
|
||||
* Invalidate ``/api/settings`` cache on change of the currently enabled plugins (by including plugin names into ETag calculation) and/or on change of the current effective config.
|
||||
* Fix for `/api/settings` not being properly invalidated for plugin settings that do not have a representation in `config.yaml` but are only added at runtime (and hence are not captured by `config.effective`).
|
||||
* Invalidate ``/api/timelapse`` cache on change of the current timelapse configuration.
|
||||
* Fixed an issue causing the version number not to be properly extracted from ``sdist`` tarballs generated under Windows.
|
||||
* Get rid of double scroll bar in printer profile editor.
|
||||
* Fixed tracking of current byte position in file being streamed from disk. Turns out that ``self._handle.tell`` lied to us thanks to line buffering.
|
||||
* Fixed select & print not working anymore for SD files thanks to a timing issue.
|
||||
* Fixed ``PrintFailed`` event payload (was still missing new folder relevant data).
|
||||
* Fixed premature parse stop on ``M114`` and ``M115`` responses with ``ok``-prefix.
|
||||
* Make sure `?l10n` request parameter gets also propagated to API calls as `X-Locale` header in case of locale sensitive API responses.
|
||||
* Fix language mixture due to cached template configs including localized strings; cache per locale.
|
||||
* Only insert divider in system menu after core commands if there are custom commands.
|
||||
* Fix update of webcam stream URL not being applied due to caching.
|
||||
* Fixed a rare race condition causing the new "The settings changed, reload?" popup to show up even when the settings change originated in the same client instance.
|
||||
* Fixed a bunch of missing translations.
|
||||
* Pinned Tornado version to 4.0.2. Former version requirement was able to pull in a beta version causing issues with websockets due to a bug in `permessage-deflate` handling. The Tornado requirement needs an update, but we'll leave it at 4.0.2 for 1.3.0 since we'll need to do some migration work for compatibility with anything newer. Potentially related to [#1523](https://github.com/foosel/OctoPrint/issues/1523).
|
||||
* Fix a rare race condition in the command line helper and the update script that could cause the code to hang due to waiting on an event that would never be set.
|
||||
* Fix issue with handling new settings substructures when they are compared to existing settings data in order to find the structural diff.
|
||||
* Fix for the temperature graph not displaying the data history on site reload.
|
||||
|
||||
### Changes from `maintenance` not yet released as part of a stable release
|
||||
### More information
|
||||
|
||||
#### Improvements
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.2.18...1.3.0)
|
||||
* Release Candidates:
|
||||
* [1.3.0rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc1)
|
||||
* [1.3.0rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc2)
|
||||
* [1.3.0rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc3)
|
||||
|
||||
* Allow arbitrary frame rates for creating timelapses. Before, the entered fps value was also directly used as frame rate for the actual video, which could cause problems with any frame rates not specified in the MPEG2 standard. Now OctoPrint will use a standard frame rate for the rendered video and render the timelapse stills into the finished movie with the configured frame rate.
|
||||
* Limit Cura profile importer to `.ini` files and clarified the supported versions
|
||||
* Add support for the `R` parameter for `M109` and `M190`
|
||||
|
||||
#### Bug fixes
|
||||
|
||||
* [#1541](https://github.com/foosel/OctoPrint/issues/1541) - Fix selecting the printer profile to use by default
|
||||
* [#1543](https://github.com/foosel/OctoPrint/issues/1543) - Fix target temperature propagation from communication layer
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.3.0rc1))
|
||||
|
||||
## 1.2.17rc4 (2016-10-17)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* Properly handle empty JS file list from plugins. Solves a 500 on OctoPrint instances without any third party plugins installed generated during web asset bundling introduced in 1.2.17rc2.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.17rc3...1.2.17rc4))
|
||||
|
||||
## 1.2.17rc3 (2016-10-13)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* Fixed a wrong order in loading JS files on the client introduced in 1.2.17rc2 to make the UI more resilient against broken plugin JS.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.17rc2...1.2.17rc3))
|
||||
|
||||
## 1.2.17rc2 (2016-10-13)
|
||||
## 1.2.18 (2016-11-30)
|
||||
|
||||
### Improvements
|
||||
|
||||
* Improved the `serial.log` logging handler to roll over serial log on new connections to the printer instead of continuously appending to the same file. Please note that `serial.log` is a debugging tool only and should *not* be left enabled unless you are trying to troubleshoot something in your printer communication.
|
||||
* Split JS/CSS/LESS asset bundles according into asset bundles for core + bundled plugins ("packed_core.{js|css|less}") and third party plugins ("packed_plugins.{js|css|less}"). That will allow the core UI to still function properly even if an installed third party plugin produces invalid JS and therefore causes a parser error for the whole plugin JS file. See [#1544](https://github.com/foosel/OctoPrint/issues/1544) for an example of such a situation.
|
||||
* Allow arbitrary frame rates for creating timelapses. Before, the entered fps value was also directly used as frame rate for the actual video, which could cause problems with any frame rates not specified in the MPEG2 standard. Now OctoPrint will use a standard frame rate for the rendered video and render the timelapse stills into the finished movie with the configured frame rate.
|
||||
* Limited Cura profile importer to `.ini` files and clarified the supported versions
|
||||
* Add support for the `R` parameter for `M109` and `M190`
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* Fixed a bug causing the update of OctoPrint to not work under certain circumstances: If 1.2.16 was installed and the settings were *never* saved via the "Settings" dialog's "Save", the update of OctoPrint would fail due to a `KeyError` in the updater. Reason is a renamed property, properly switched to when saving the settings.
|
||||
* Fixed the logging subsystem to not properly clean up after itself.
|
||||
* [#1541](https://github.com/foosel/OctoPrint/issues/1541) - Fix selecting the printer profile to use by default
|
||||
* [#1543](https://github.com/foosel/OctoPrint/issues/1543) - Fix target temperature propagation from communication layer
|
||||
* [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Fix issue with restricted settings getting parsed to the wrong data structure in the frontend if loaded anonymously first.
|
||||
* [#1571](https://github.com/foosel/OctoPrint/issues/1571) - Fix parsing of port number from HTTP Host header for IPv6 addresses
|
||||
* Fix issue with settings restriction causing internal settings defaults to be changed.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.17rc1...1.2.17rc2))
|
||||
### More information
|
||||
|
||||
## 1.2.17rc1 (2016-10-06)
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.2.17...1.2.18)
|
||||
* Release Candidates:
|
||||
* [1.2.18rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.18rc1)
|
||||
|
||||
## 1.2.17 (2016-11-08)
|
||||
|
||||
### Improvements
|
||||
|
||||
@@ -142,6 +170,8 @@
|
||||
* Log full stack trace on socket connection errors when debug logging for `octoprint.server.util.sockjs` is enabled
|
||||
* ``SettingsPlugin``s may now mark configuration paths as restricted so that they are not returned on the REST API
|
||||
* Updated LESS.js version
|
||||
* Improved the `serial.log` logging handler to roll over serial log on new connections to the printer instead of continuously appending to the same file. Please note that `serial.log` is a debugging tool only and should *not* be left enabled unless you are trying to troubleshoot something in your printer communication.
|
||||
* Split JS/CSS/LESS asset bundles according into asset bundles for core + bundled plugins ("packed_core.{js|css|less}") and third party plugins ("packed_plugins.{js|css|less}"). That will allow the core UI to still function properly even if an installed third party plugin produces invalid JS and therefore causes a parser error for the whole plugin JS file. See [#1544](https://github.com/foosel/OctoPrint/issues/1544) for an example of such a situation.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
@@ -150,8 +180,19 @@
|
||||
* Fixed issue causing ``remember_me`` cookie not to be deleted properly on logout
|
||||
* Fixed broken filter toggling on ``ItemListHelper`` class used for various lists throughout the web interface
|
||||
* Fixed an issue with the preliminary page never reporting that the server is now up if the page generated during preliminary caching had no cache headers set (e.g. because it contained the first run setup wizard)
|
||||
* Fixed a bug causing the update of OctoPrint to not work under certain circumstances: If 1.2.16 was installed and the settings were *never* saved via the "Settings" dialog's "Save", the update of OctoPrint would fail due to a `KeyError` in the updater. Reason is a renamed property, properly switched to when saving the settings.
|
||||
* Fixed the logging subsystem to properly clean up after itself.
|
||||
* Fixed a wrong order in loading JS files on the client introduced in 1.2.17rc2 to make the UI more resilient against broken plugin JS.
|
||||
* Properly handle empty JS file list from plugins. Solves a 500 on OctoPrint instances without any third party plugins installed generated during web asset bundling introduced in 1.2.17rc2.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.2.17rc1))
|
||||
### More information
|
||||
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.2.17)
|
||||
* Release Candidates:
|
||||
* [1.2.17rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc1)
|
||||
* [1.2.17rc2](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc2)
|
||||
* [1.2.17rc3](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc3)
|
||||
* [1.2.17rc4](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc4)
|
||||
|
||||
## 1.2.16 (2016-09-23)
|
||||
|
||||
|
||||
+4
-10
@@ -14,7 +14,6 @@ thanks to everyone who contributed!
|
||||
* Bart Zudell
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brad Mooneyham
|
||||
* Brent Fiegle
|
||||
* Brian E. Tyler
|
||||
* Charles Mitchell
|
||||
@@ -33,28 +32,22 @@ thanks to everyone who contributed!
|
||||
* Gary Deen
|
||||
* Gary N McKinney
|
||||
* George Robles
|
||||
* Gregor Lütolf
|
||||
* J. Eckert
|
||||
* Jamie van Dyke
|
||||
* Jason Galarneau
|
||||
* Joe Korzeniewski
|
||||
* Josh Daniels
|
||||
* Joshua David Gregory
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Korneel Bullens
|
||||
* Lamin Kivelä
|
||||
* M Khorakiwala
|
||||
* Makespace Madrid
|
||||
* Mark Lane
|
||||
* Marcus Ackermann
|
||||
* Mark Qvist
|
||||
* Mark Walker
|
||||
* Masayoshi Mitsui
|
||||
* Michael Aumock
|
||||
* Michael McDargh Sr
|
||||
* Miles Flavel
|
||||
* NateTheApe3DPrints
|
||||
* Nikolai Langer
|
||||
* Noe Ruiz
|
||||
* Patrick McGinnis
|
||||
* Peter Grace
|
||||
@@ -69,10 +62,11 @@ thanks to everyone who contributed!
|
||||
* Shane Ekerbicer
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Stephane Schittly
|
||||
* Steven Pearson
|
||||
* Sven Mueller
|
||||
* Terrance Shaw
|
||||
* Thomas Hatley
|
||||
* Trent Shumay
|
||||
|
||||
and 963 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 972 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
+50
-12
@@ -308,6 +308,17 @@ PrintCancelled
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``position``: the print head position at the time of cancelling, if available
|
||||
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.e``: e coordinate (of currently selected extruder), as reported back from the firmware through `M114`
|
||||
* ``position.t``: last tool selected *through OctoPrint* (note that if you did change the printer's selected
|
||||
tool outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will NOT
|
||||
be accurate)
|
||||
* ``position.f``: last feedrate for move commands **sent through OctoPrint** (note that if you modified the
|
||||
feedrate outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will
|
||||
NOT be accurate)
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
@@ -324,6 +335,17 @@ PrintPaused
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``position``: the print head position at the time of pausing, if available
|
||||
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
|
||||
* ``position.e``: e coordinate (of currently selected extruder), as reported back from the firmware through `M114`
|
||||
* ``position.t``: last tool selected *through OctoPrint* (note that if you did change the printer's selected
|
||||
tool outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will NOT
|
||||
be accurate)
|
||||
* ``position.f``: last feedrate for move commands **sent through OctoPrint** (note that if you modified the
|
||||
feedrate outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will
|
||||
NOT be accurate)
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
@@ -352,37 +374,53 @@ GCODE processing
|
||||
----------------
|
||||
|
||||
PowerOn
|
||||
The GCode has turned on the printer power via M80
|
||||
An ``M80`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
|
||||
|
||||
PowerOff
|
||||
The GCODE has turned on the printer power via M81
|
||||
An ``M81`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
|
||||
|
||||
Home
|
||||
The head has gone home via G28
|
||||
A ``G28`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
|
||||
|
||||
ZChange
|
||||
The printer's Z-Height has changed (new layer)
|
||||
The printer's Z-Height has changed (new layer) through a ``G0`` or ``G1`` that was sent to the printer through OctoPrint
|
||||
(not triggered when printing from SD!)
|
||||
|
||||
Paused
|
||||
The print has been paused
|
||||
Dwell
|
||||
A ``G4`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
|
||||
|
||||
Waiting
|
||||
The print is paused due to a gcode wait command
|
||||
One of the following commands was sent to the printer through OctoPrint (not triggered when printing from SD!):
|
||||
``M0``, ``M1``, ``M226``
|
||||
|
||||
Cooling
|
||||
The GCODE has enabled the platform cooler via M245
|
||||
An ``M245`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
|
||||
|
||||
Alert
|
||||
The GCODE has issued a user alert (beep) via M300
|
||||
An ``M300`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
|
||||
|
||||
Conveyor
|
||||
The GCODE has enabled the conveyor belt via M240
|
||||
An ``M240`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
|
||||
|
||||
Eject
|
||||
The GCODE has enabled the part ejector via M40
|
||||
An ``M40`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
|
||||
|
||||
EStop
|
||||
The GCODE has issued a panic stop via M112
|
||||
An ``M112`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
|
||||
|
||||
PositionUpdate
|
||||
The response to an ``M114`` was received by OctoPrint. The payload contains the current position information
|
||||
parsed from the response and (in the case of the selected tool ``t`` and the current feedrate ``f``) tracked
|
||||
by OctoPrint.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``x``: x coordinate, parsed from response
|
||||
* ``y``: y coordinate, parsed from response
|
||||
* ``z``: z coordinate, parsed from response
|
||||
* ``e``: e coordinate, parsed from response
|
||||
* ``t``: last tool selected *through OctoPrint*
|
||||
* ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint*
|
||||
|
||||
Timelapses
|
||||
----------
|
||||
|
||||
@@ -60,9 +60,36 @@ All GCODE scripts have access to the following template variables through the te
|
||||
|
||||
* ``printer_profile``: The currently selected Printer Profile, including
|
||||
information such as the extruder count, the build volume size, the filament diameter etc.
|
||||
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!)
|
||||
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
|
||||
and ``script.name`` respectively.
|
||||
|
||||
There are a couple of additional template variables available for the following specific scripts:
|
||||
|
||||
* ``afterPrintPaused`` and ``beforePrintResumed``
|
||||
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists
|
||||
of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool
|
||||
``t`` taken from commands sent through OctoPrint.
|
||||
* ``afterPrintCancelled``
|
||||
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
|
||||
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
|
||||
current tool ``t`` taken from commands sent through OctoPrint.
|
||||
|
||||
.. warning::
|
||||
|
||||
Note that current firmware implementations only report back one ``E`` value, the current extrusion value for the current
|
||||
extruder. Retrieving all ``E`` values by cycling through all extruders on pause and cancel is something OctoPrint
|
||||
currently does NOT do since it would simply take too long. That means that if you want to write a ``beforePrintResumed``
|
||||
script that basically resets everything back to the point when the printer was paused *and* you are running with
|
||||
multiple extruders, you'll have to find some other way to have your ``E`` values set correctly for all your available
|
||||
extruders - the data available in ``pause_position`` will *not* suffice. Additionally, most firmwares don't report
|
||||
the currently selected tool in the ``M114`` response, meaning that the only way OctoPrint can keep track of that is
|
||||
by tracking it itself. Same goes for the current feed rate ``F``. So if you are printing from SD, this data will be
|
||||
*wrong*. This is also the reason why OctoPrint currently doesn't bundle a more sophisticated pause and resume script
|
||||
that would actually move the print head out of the way and pause and back to the original position on resume - it
|
||||
might cause issues for the multitude of users out there with multi-extruder setups or for people printing from the
|
||||
printer's SD, thanks to the lack of information the firmware provides.
|
||||
|
||||
The :ref:`predefined GCODE scripts <sec-features-gcode_scripts-predefined>` are also called with the following additional
|
||||
template variables:
|
||||
|
||||
|
||||
@@ -14,6 +14,10 @@
|
||||
``OctoPrint.options.baseurl``
|
||||
The base URL of the OctoPrint API
|
||||
|
||||
``OctoPrint.options.locale``
|
||||
The locale to set in ``X-Locale`` headers on API requests. Useful for API
|
||||
endpoints that might return localized content.
|
||||
|
||||
.. js:data:: OctoPrint.plugins
|
||||
|
||||
Registration of client library components provided by plugins.
|
||||
@@ -251,14 +255,18 @@
|
||||
|
||||
**Example:**
|
||||
|
||||
Uploading a file from a file input element, updating a label with the current upload progress.
|
||||
Uploading a file to ``some/path`` on the blueprint of plugin ``myplugin``, from a file input element,
|
||||
updating a label with the current upload progress.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
var fileInput = $("#my-file-input");
|
||||
var progressOutput = $("#progress-output");
|
||||
|
||||
OctoPrint.upload("/plugins/myplugin/some/path", fileInput, "myfilename.dat", {"somekey": "somevalue"})
|
||||
OctoPrint.upload(OctoPrint.getBlueprintUrl("myplugin") + "some/path",
|
||||
fileInput,
|
||||
"myfilename.dat",
|
||||
{"somekey": "somevalue"})
|
||||
.progress(function(data) {
|
||||
if (data.total) {
|
||||
var percentage = Math.round(data.loaded * 100 / data.total);
|
||||
@@ -273,7 +281,7 @@
|
||||
progressOutput.text("Uploaded!");
|
||||
});
|
||||
|
||||
:param string url: The URL to ``POST`` the upload to
|
||||
:param string url: URL to which to POST the upload, relative to base url or absolute
|
||||
:param object file: The file to object, see description for details
|
||||
:param string filename: An optional file name to use for the upload
|
||||
:param object additional: An optional object of additional key/value pairs to set on the uploaded form data
|
||||
|
||||
@@ -5,7 +5,8 @@ JavaScript Client Library
|
||||
#########################
|
||||
|
||||
The JS Client Library provides an interface to all of OctoPrint's API, including the SockJS based socket to send
|
||||
push messages from the server to connected clients. It is available as packed web asset file at ``/static/webassets/packed_client.js`` or as individual
|
||||
push messages from the server to connected clients. It is available as packed web
|
||||
asset file at ``/static/webassets/packed_client.js`` or as individual
|
||||
component files at ``/static/js/app/client/<component>.js`` relative to your
|
||||
OctoPrint instance's base URL (e.g. ``http://octopi.local/static/webassets/packed_client.js``).
|
||||
|
||||
@@ -27,10 +28,18 @@ correct URL prefix:
|
||||
<script type="text/javascript" src="{{ url_for("static", filename="webassets/packed_client.js") }}"></script>
|
||||
|
||||
<!--
|
||||
individual components
|
||||
individual components (do not forget base!)
|
||||
-->
|
||||
<script type="text/javascript" src="{{ url_for("static", filename="js/app/client/<component>.js") }}"></script>
|
||||
|
||||
Regardless of which way you use to include the library, you'll also need to make sure you included JQuery and lodash,
|
||||
because the library depends on those to be available (as ``$`` and ``_``). You can embed those like this:
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
|
||||
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
|
||||
|
||||
Note that all components depend on the ``base`` component to be present, so if you are only including a select
|
||||
number of components, make sure to at the very least include that one to be able to utilize the client.
|
||||
|
||||
|
||||
@@ -16,7 +16,10 @@ import octoprint_setuptools
|
||||
INSTALL_REQUIRES = [
|
||||
"flask>=0.9,<0.11",
|
||||
"werkzeug>=0.8.3,<0.9",
|
||||
"tornado>=4.0.2,<4.1",
|
||||
"tornado==4.0.2", # pinned for now, we need to migrate to a newer tornado, but due
|
||||
# to some voodoo needed to get large streamed uploads and downloads
|
||||
# to work that is probably not completely straightforward and therefore
|
||||
# something for post-1.3.0-stable release
|
||||
"sockjs-tornado>=1.0.2,<1.1",
|
||||
"PyYAML>=3.10,<3.11",
|
||||
"Flask-Login>=0.2.2,<0.3",
|
||||
|
||||
+99
-13
@@ -18,10 +18,6 @@ __revision__ = versions.get('full-revisionid', versions.get('full', None))
|
||||
del versions
|
||||
del get_versions
|
||||
|
||||
#~~ sane logging defaults
|
||||
|
||||
log.basicConfig()
|
||||
|
||||
#~~ try to ensure a sound SSL environment
|
||||
|
||||
urllib3_ssl = True
|
||||
@@ -61,10 +57,21 @@ class FatalStartupError(BaseException):
|
||||
|
||||
def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
logging_config=None, debug=False, verbosity=0, uncaught_logger=None,
|
||||
uncaught_handler=None, after_settings=None, after_logging=None):
|
||||
uncaught_handler=None, safe_mode=False, after_preinit_logging=None,
|
||||
after_settings=None, after_logging=None, after_safe_mode=None):
|
||||
kwargs = dict()
|
||||
|
||||
logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler)
|
||||
kwargs["logger"] = logger
|
||||
kwargs["recorder"] = recorder
|
||||
|
||||
if callable(after_preinit_logging):
|
||||
after_preinit_logging(**kwargs)
|
||||
|
||||
settings = init_settings(basedir, configfile)
|
||||
kwargs["settings"] = settings
|
||||
if callable(after_settings):
|
||||
after_settings(settings)
|
||||
after_settings(**kwargs)
|
||||
|
||||
logger = init_logging(settings,
|
||||
use_logging_file=use_logging_file,
|
||||
@@ -74,11 +81,20 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
verbosity=verbosity,
|
||||
uncaught_logger=uncaught_logger,
|
||||
uncaught_handler=uncaught_handler)
|
||||
if callable(after_logging):
|
||||
after_logging(logger)
|
||||
kwargs["logger"] = logger
|
||||
|
||||
plugin_manager = init_pluginsystem(settings)
|
||||
return settings, logger, plugin_manager
|
||||
if callable(after_logging):
|
||||
after_logging(**kwargs)
|
||||
|
||||
settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"])
|
||||
safe_mode = safe_mode or settings_safe_mode
|
||||
kwargs["safe_mode"] = safe_mode
|
||||
|
||||
if callable(after_safe_mode):
|
||||
after_safe_mode(**kwargs)
|
||||
|
||||
plugin_manager = init_pluginsystem(settings, safe_mode=safe_mode)
|
||||
return settings, logger, safe_mode, plugin_manager
|
||||
|
||||
|
||||
def init_settings(basedir, configfile):
|
||||
@@ -94,6 +110,45 @@ def init_settings(basedir, configfile):
|
||||
raise FatalStartupError(message)
|
||||
|
||||
|
||||
def preinit_logging(debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None):
|
||||
config = {
|
||||
"version": 1,
|
||||
"formatters": {
|
||||
"simple": {
|
||||
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
}
|
||||
},
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "simple",
|
||||
"stream": "ext://sys.stdout"
|
||||
}
|
||||
},
|
||||
"loggers": {
|
||||
"octoprint": {
|
||||
"level": "DEBUG" if debug else "INFO"
|
||||
},
|
||||
"octoprint.util": {
|
||||
"level": "INFO"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"level": "WARN",
|
||||
"handlers": ["console"]
|
||||
}
|
||||
}
|
||||
|
||||
logger = set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler)
|
||||
|
||||
from octoprint.logging.handlers import RecordingLogHandler
|
||||
recorder = RecordingLogHandler(level=log.DEBUG)
|
||||
log.getLogger().addHandler(recorder)
|
||||
|
||||
return logger, recorder
|
||||
|
||||
|
||||
def init_logging(settings, use_logging_file=True, logging_file=None, default_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None):
|
||||
"""Sets up logging."""
|
||||
|
||||
@@ -182,6 +237,11 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
|
||||
else:
|
||||
config = default_config
|
||||
|
||||
# configure logging globally
|
||||
return set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler)
|
||||
|
||||
|
||||
def set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler):
|
||||
# configure logging globally
|
||||
import logging.config as logconfig
|
||||
logconfig.dictConfig(config)
|
||||
@@ -207,19 +267,45 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
|
||||
if uncaught_handler is None:
|
||||
def exception_logger(exc_type, exc_value, exc_tb):
|
||||
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
|
||||
|
||||
uncaught_handler = exception_logger
|
||||
sys.excepthook = uncaught_handler
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
def init_pluginsystem(settings):
|
||||
def init_pluginsystem(settings, safe_mode=False):
|
||||
"""Initializes the plugin manager based on the settings."""
|
||||
|
||||
from octoprint.plugin import plugin_manager
|
||||
pm = plugin_manager(init=True, settings=settings)
|
||||
import os
|
||||
|
||||
logger = log.getLogger(__name__)
|
||||
|
||||
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True),
|
||||
settings.getBaseFolder("plugins")]
|
||||
plugin_entry_points = ["octoprint.plugin"]
|
||||
plugin_disabled_list = settings.get(["plugins", "_disabled"])
|
||||
|
||||
plugin_validators = []
|
||||
if safe_mode:
|
||||
def validator(phase, plugin_info):
|
||||
if phase == "after_load":
|
||||
setattr(plugin_info, "safe_mode_victim", not plugin_info.bundled)
|
||||
setattr(plugin_info, "safe_mode_enabled", False)
|
||||
elif phase == "before_enable":
|
||||
if not plugin_info.bundled:
|
||||
setattr(plugin_info, "safe_mode_enabled", True)
|
||||
return False
|
||||
return True
|
||||
plugin_validators.append(validator)
|
||||
|
||||
from octoprint.plugin import plugin_manager
|
||||
pm = plugin_manager(init=True,
|
||||
plugin_folders=plugin_folders,
|
||||
plugin_entry_points=plugin_entry_points,
|
||||
plugin_disabled_list=plugin_disabled_list,
|
||||
plugin_validators=plugin_validators)
|
||||
|
||||
settings_overlays = dict()
|
||||
disabled_from_overlays = dict()
|
||||
|
||||
|
||||
@@ -13,10 +13,11 @@ import octoprint
|
||||
class OctoPrintContext(object):
|
||||
"""Custom context wrapping the standard options."""
|
||||
|
||||
def __init__(self, configfile=None, basedir=None, verbosity=0):
|
||||
def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False):
|
||||
self.configfile = configfile
|
||||
self.basedir = basedir
|
||||
self.verbosity = verbosity
|
||||
self.safe_mode = safe_mode
|
||||
|
||||
pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True)
|
||||
"""Decorator to pass in the :class:`OctoPrintContext` instance."""
|
||||
@@ -95,6 +96,8 @@ def standard_options(hidden=False):
|
||||
help="Specify the config file to use."),
|
||||
factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
|
||||
help="Increase logging verbosity"),
|
||||
factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
|
||||
help="Enable safe mode; disables all third party plugins")
|
||||
]
|
||||
|
||||
return bulk_options(options)
|
||||
@@ -120,9 +123,10 @@ from .server import server_commands
|
||||
from .plugins import plugin_commands
|
||||
from .dev import dev_commands
|
||||
from .client import client_commands
|
||||
from .config import config_commands
|
||||
|
||||
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
|
||||
sources=[server_commands, plugin_commands, dev_commands, client_commands])
|
||||
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands])
|
||||
@standard_options()
|
||||
@legacy_options
|
||||
@click.version_option(version=octoprint.__version__)
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
# 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import click
|
||||
import logging
|
||||
|
||||
from octoprint import init_settings, FatalStartupError
|
||||
from octoprint.cli import pass_octoprint_ctx, standard_options, bulk_options
|
||||
|
||||
import yaml
|
||||
import json
|
||||
import pprint
|
||||
|
||||
def _to_settings_path(path):
|
||||
if not isinstance(path, (list, tuple)):
|
||||
path = filter(lambda x: x, map(lambda x: x.strip(), path.split(".")))
|
||||
return path
|
||||
|
||||
def _set_helper(settings, path, value, data_type=None):
|
||||
path = _to_settings_path(path)
|
||||
|
||||
method = settings.set
|
||||
if data_type is not None:
|
||||
name = None
|
||||
if data_type == bool:
|
||||
name = "setBoolean"
|
||||
elif data_type == float:
|
||||
name = "setFloat"
|
||||
elif data_type == int:
|
||||
name = "setInt"
|
||||
|
||||
if name is not None:
|
||||
method = getattr(settings, name)
|
||||
|
||||
method(path, value)
|
||||
settings.save()
|
||||
|
||||
#~~ "octoprint config" commands
|
||||
|
||||
@click.group()
|
||||
def config_commands():
|
||||
pass
|
||||
|
||||
@config_commands.group(name="config")
|
||||
@pass_octoprint_ctx
|
||||
@click.pass_context
|
||||
def config(ctx, obj):
|
||||
"""Basic config manipulation."""
|
||||
logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN)
|
||||
try:
|
||||
obj.settings = init_settings(obj.basedir, obj.configfile)
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error initializing the client.", err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
|
||||
@config.command(name="set")
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.argument("value", type=click.STRING)
|
||||
@click.option("--bool", "as_bool", is_flag=True,
|
||||
help="Interpret value as bool")
|
||||
@click.option("--float", "as_float", is_flag=True,
|
||||
help="Interpret value as float")
|
||||
@click.option("--int", "as_int", is_flag=True,
|
||||
help="Interpret value as int")
|
||||
@click.option("--json", "as_json", is_flag=True,
|
||||
help="Parse value from json")
|
||||
@pass_octoprint_ctx
|
||||
@click.pass_context
|
||||
def set_command(ctx, obj, path, value, as_bool, as_float, as_int, as_json):
|
||||
"""Sets a config path to the provided value."""
|
||||
if as_json:
|
||||
try:
|
||||
value = json.loads(value)
|
||||
except Exception as e:
|
||||
click.echo(e.message, err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
data_type = None
|
||||
if as_bool:
|
||||
data_type = bool
|
||||
elif as_float:
|
||||
data_type = float
|
||||
elif as_int:
|
||||
data_type = int
|
||||
|
||||
_set_helper(obj.settings, path, value, data_type=data_type)
|
||||
|
||||
|
||||
@config.command(name="remove")
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("path", type=click.STRING)
|
||||
@pass_octoprint_ctx
|
||||
def remove_command(obj, path):
|
||||
"""Removes a config path."""
|
||||
_set_helper(obj.settings, path, None)
|
||||
|
||||
|
||||
@config.command(name="append_value")
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.argument("value", type=click.STRING)
|
||||
@click.option("--json", "as_json", is_flag=True)
|
||||
@pass_octoprint_ctx
|
||||
@click.pass_context
|
||||
def append_value_command(ctx, obj, path, value, as_json=False):
|
||||
"""Appends value to list behind config path."""
|
||||
path = _to_settings_path(path)
|
||||
|
||||
if as_json:
|
||||
try:
|
||||
value = json.loads(value)
|
||||
except Exception as e:
|
||||
click.echo(e.message, err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
current = obj.settings.get(path)
|
||||
if current is None:
|
||||
current = []
|
||||
if not isinstance(current, list):
|
||||
click.echo("Cannot append to non-list value at given path", err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
current.append(value)
|
||||
_set_helper(obj.settings, path, current)
|
||||
|
||||
|
||||
@config.command(name="insert_value")
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.argument("index", type=click.INT)
|
||||
@click.argument("value", type=click.STRING)
|
||||
@click.option("--json", "as_json", is_flag=True)
|
||||
@pass_octoprint_ctx
|
||||
@click.pass_context
|
||||
def insert_value_command(ctx, obj, path, index, value, as_json=False):
|
||||
"""Inserts value at index of list behind config key."""
|
||||
path = _to_settings_path(path)
|
||||
|
||||
if as_json:
|
||||
try:
|
||||
value = json.loads(value)
|
||||
except Exception as e:
|
||||
click.echo(e.message, err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
current = obj.settings.get(path)
|
||||
if current is None:
|
||||
current = []
|
||||
if not isinstance(current, list):
|
||||
click.echo("Cannot insert into non-list value at given path", err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
current.insert(index, value)
|
||||
_set_helper(obj.settings, path, current)
|
||||
|
||||
|
||||
@config.command(name="remove_value")
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.argument("value", type=click.STRING)
|
||||
@click.option("--json", "as_json", is_flag=True)
|
||||
@pass_octoprint_ctx
|
||||
@click.pass_context
|
||||
def remove_value_command(ctx, obj, path, value, as_json=False):
|
||||
"""Removes value from list at config path."""
|
||||
path = _to_settings_path(path)
|
||||
|
||||
if as_json:
|
||||
try:
|
||||
value = json.loads(value)
|
||||
except Exception as e:
|
||||
click.echo(e.message, err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
current = obj.settings.get(path)
|
||||
if current is None:
|
||||
current = []
|
||||
if not isinstance(current, list):
|
||||
click.echo("Cannot remove value from non-list value at given path", err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
if not value in current:
|
||||
click.echo("Value is not contained in list at given path")
|
||||
ctx.exit()
|
||||
|
||||
current.remove(value)
|
||||
_set_helper(obj.settings, path, current)
|
||||
|
||||
|
||||
@config.command(name="get")
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.option("--json", "as_json", is_flag=True,
|
||||
help="Output value formatted as JSON")
|
||||
@click.option("--yaml", "as_yaml", is_flag=True,
|
||||
help="Output value formatted as YAML")
|
||||
@click.option("--raw", "as_raw", is_flag=True,
|
||||
help="Output value as raw string representation")
|
||||
@standard_options(hidden=True)
|
||||
@pass_octoprint_ctx
|
||||
def get_command(obj, path, as_json=False, as_yaml=False, as_raw=False):
|
||||
"""Retrieves value from config path."""
|
||||
path = _to_settings_path(path)
|
||||
value = obj.settings.get(path, merged=True)
|
||||
|
||||
if as_json:
|
||||
output = json.dumps(value)
|
||||
elif as_yaml:
|
||||
output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
elif as_raw:
|
||||
output = value
|
||||
else:
|
||||
output = pprint.pformat(value)
|
||||
|
||||
click.echo(output)
|
||||
@@ -51,7 +51,7 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
from octoprint import init_settings, init_pluginsystem, FatalStartupError
|
||||
try:
|
||||
self.settings = init_settings(ctx.obj.basedir, ctx.obj.configfile)
|
||||
self.plugin_manager = init_pluginsystem(self.settings)
|
||||
self.plugin_manager = init_pluginsystem(self.settings, safe_mode=ctx.obj.safe_mode)
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error initializing the settings or the plugin system.", err=True)
|
||||
|
||||
+34
-15
@@ -11,13 +11,26 @@ import sys
|
||||
|
||||
from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options
|
||||
|
||||
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, octoprint_daemon = None):
|
||||
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode, octoprint_daemon=None):
|
||||
"""Initializes the environment and starts up the server."""
|
||||
|
||||
from octoprint import init_platform, __display_version__, FatalStartupError
|
||||
|
||||
def log_startup(_):
|
||||
logging.getLogger("octoprint.server").info("Starting OctoPrint {}".format(__display_version__))
|
||||
def log_startup(recorder=None, safe_mode=None, **kwargs):
|
||||
logger = logging.getLogger("octoprint.server")
|
||||
logger.info("Starting OctoPrint {}".format(__display_version__))
|
||||
if safe_mode:
|
||||
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
|
||||
|
||||
if recorder and len(recorder):
|
||||
logger.info("--- Logged during platform initialization: ---")
|
||||
|
||||
from octoprint.logging.handlers import CombinedLogHandler
|
||||
handler = CombinedLogHandler(*logging.getLogger().handlers)
|
||||
recorder.setTarget(handler)
|
||||
recorder.flush()
|
||||
|
||||
logger.info("----------------------------------------------")
|
||||
|
||||
from octoprint import urllib3_ssl
|
||||
if not urllib3_ssl:
|
||||
@@ -30,13 +43,14 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl")
|
||||
|
||||
try:
|
||||
settings, _, plugin_manager = init_platform(basedir,
|
||||
configfile,
|
||||
logging_file=logging_config,
|
||||
debug=debug,
|
||||
verbosity=verbosity,
|
||||
uncaught_logger=__name__,
|
||||
after_logging=log_startup)
|
||||
settings, _, safe_mode, plugin_manager = init_platform(basedir,
|
||||
configfile,
|
||||
logging_file=logging_config,
|
||||
debug=debug,
|
||||
verbosity=verbosity,
|
||||
uncaught_logger=__name__,
|
||||
safe_mode=safe_mode,
|
||||
after_safe_mode=log_startup)
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error starting up OctoPrint.", err=True)
|
||||
@@ -47,6 +61,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
host=host,
|
||||
port=port,
|
||||
debug=debug,
|
||||
safe_mode=safe_mode,
|
||||
allow_root=allow_root,
|
||||
octoprint_daemon=octoprint_daemon)
|
||||
octoprint_server.run()
|
||||
@@ -62,7 +77,7 @@ server_options = bulk_options([
|
||||
help="Specify the config file to use for configuring logging."),
|
||||
click.option("--iknowwhatimdoing", "allow_root", is_flag=True,
|
||||
help="Allow OctoPrint to run as user root."),
|
||||
click.option("--debug", is_flag=True, help="Enable debug mode"),
|
||||
click.option("--debug", is_flag=True, help="Enable debug mode.")
|
||||
])
|
||||
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
|
||||
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
|
||||
@@ -82,7 +97,7 @@ def server_commands(obj):
|
||||
def serve_command(obj, host, port, logging, allow_root, debug):
|
||||
"""Starts the OctoPrint server."""
|
||||
run_server(obj.basedir, obj.configfile, host, port, debug,
|
||||
allow_root, logging, obj.verbosity)
|
||||
allow_root, logging, obj.verbosity, obj.safe_mode)
|
||||
|
||||
|
||||
@server_commands.command(name="daemon")
|
||||
@@ -111,7 +126,7 @@ def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, c
|
||||
|
||||
from octoprint.daemon import Daemon
|
||||
class OctoPrintDaemon(Daemon):
|
||||
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity):
|
||||
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode):
|
||||
Daemon.__init__(self, pidfile)
|
||||
|
||||
self._basedir = basedir
|
||||
@@ -122,12 +137,16 @@ def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, c
|
||||
self._allow_root = allow_root
|
||||
self._logging_config = logging_config
|
||||
self._verbosity = verbosity
|
||||
self._safe_mode = safe_mode
|
||||
|
||||
def run(self):
|
||||
run_server(self._basedir, self._configfile, self._host, self._port, self._debug, self._allow_root, self._logging_config, self._verbosity, self)
|
||||
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
|
||||
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
|
||||
octoprint_daemon=self)
|
||||
|
||||
octoprint_daemon = OctoPrintDaemon(pid, octoprint_ctx.basedir, octoprint_ctx.configfile,
|
||||
host, port, debug, allow_root, logging, octoprint_ctx.verbosity)
|
||||
host, port, debug, allow_root, logging, octoprint_ctx.verbosity,
|
||||
octoprint_ctx.safe_mode)
|
||||
|
||||
if command == "start":
|
||||
octoprint_daemon.start()
|
||||
|
||||
@@ -78,6 +78,7 @@ class Events(object):
|
||||
CONVEYOR = "Conveyor"
|
||||
EJECT = "Eject"
|
||||
E_STOP = "EStop"
|
||||
POSITION_UPDATE = "PositionUpdate"
|
||||
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
|
||||
|
||||
# Timelapse
|
||||
|
||||
@@ -81,3 +81,56 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
|
||||
self.cleanupFiles()
|
||||
if not self.delay:
|
||||
self.stream = self._open()
|
||||
|
||||
class RecordingLogHandler(logging.Handler):
|
||||
def __init__(self, target=None, level=logging.NOTSET):
|
||||
logging.Handler.__init__(self, level=level)
|
||||
self._buffer = []
|
||||
self._target = target
|
||||
|
||||
def emit(self, record):
|
||||
self._buffer.append(record)
|
||||
|
||||
def setTarget(self, target):
|
||||
self._target = target
|
||||
|
||||
def flush(self):
|
||||
if not self._target:
|
||||
return
|
||||
|
||||
self.acquire()
|
||||
try:
|
||||
for record in self._buffer:
|
||||
self._target.handle(record)
|
||||
self._buffer = []
|
||||
finally:
|
||||
self.release()
|
||||
|
||||
def close(self):
|
||||
self.flush()
|
||||
self.acquire()
|
||||
try:
|
||||
self._buffer = []
|
||||
finally:
|
||||
self.release()
|
||||
|
||||
def __len__(self):
|
||||
return len(self._buffer)
|
||||
|
||||
|
||||
class CombinedLogHandler(logging.Handler):
|
||||
def __init__(self, *handlers):
|
||||
logging.Handler.__init__(self)
|
||||
self._handlers = handlers
|
||||
|
||||
def setHandlers(self, *handlers):
|
||||
self._handlers = handlers
|
||||
|
||||
def handle(self, record):
|
||||
self.acquire()
|
||||
try:
|
||||
if self._handlers:
|
||||
for handler in self._handlers:
|
||||
handler.handle(record)
|
||||
finally:
|
||||
self.release()
|
||||
@@ -42,9 +42,10 @@ def _validate_plugin(phase, plugin_info):
|
||||
if not "octoprint.accesscontrol.appkey" in hooks:
|
||||
hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps
|
||||
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
|
||||
return True
|
||||
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
|
||||
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None, settings=None):
|
||||
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
|
||||
"""
|
||||
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
|
||||
singleton.
|
||||
@@ -87,14 +88,6 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
|
||||
else:
|
||||
if init:
|
||||
if settings is None:
|
||||
settings = s()
|
||||
|
||||
if plugin_folders is None:
|
||||
plugin_folders = (
|
||||
settings.getBaseFolder("plugins"),
|
||||
(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")), True)
|
||||
)
|
||||
if plugin_types is None:
|
||||
plugin_types = [StartupPlugin,
|
||||
ShutdownPlugin,
|
||||
@@ -109,22 +102,17 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
ProgressPlugin,
|
||||
WizardPlugin,
|
||||
UiPlugin]
|
||||
if plugin_entry_points is None:
|
||||
plugin_entry_points = "octoprint.plugin"
|
||||
if plugin_disabled_list is None:
|
||||
plugin_disabled_list = settings.get(["plugins", "_disabled"])
|
||||
|
||||
if plugin_restart_needing_hooks is None:
|
||||
plugin_restart_needing_hooks = [
|
||||
"octoprint.server.http"
|
||||
]
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http"]
|
||||
|
||||
if plugin_obsolete_hooks is None:
|
||||
plugin_obsolete_hooks = [
|
||||
"octoprint.comm.protocol.gcode"
|
||||
]
|
||||
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
|
||||
|
||||
if plugin_validators is None:
|
||||
plugin_validators = [
|
||||
_validate_plugin
|
||||
]
|
||||
plugin_validators = [_validate_plugin]
|
||||
else:
|
||||
plugin_validators.append(_validate_plugin)
|
||||
|
||||
_instance = PluginManager(plugin_folders,
|
||||
plugin_types,
|
||||
@@ -145,7 +133,7 @@ def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_prepr
|
||||
|
||||
Arguments:
|
||||
plugin_key (string): The plugin identifier for which to create the settings instance.
|
||||
defaults (dict): The default settings for the plugin.
|
||||
defaults (dict): The default settings for the plugin, if different from get_settings_defaults.
|
||||
get_preprocessors (dict): The getter preprocessors for the plugin.
|
||||
set_preprocessors (dict): The setter preprocessors for the plugin.
|
||||
settings (octoprint.settings.Settings): The settings instance to use.
|
||||
@@ -180,13 +168,12 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
|
||||
return None
|
||||
|
||||
try:
|
||||
defaults = instance.get_settings_defaults()
|
||||
get_preprocessors, set_preprocessors = instance.get_settings_preprocessors()
|
||||
except:
|
||||
logging.getLogger(__name__).exception("Error while retrieving defaults or preprocessors for plugin {}".format(plugin_key))
|
||||
logging.getLogger(__name__).exception("Error while retrieving preprocessors for plugin {}".format(plugin_key))
|
||||
return None
|
||||
|
||||
return plugin_settings(plugin_key, defaults=defaults, 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):
|
||||
@@ -315,11 +302,12 @@ class PluginSettings(object):
|
||||
self.settings = settings
|
||||
self.plugin_key = plugin_key
|
||||
|
||||
if defaults is None:
|
||||
defaults = dict()
|
||||
self.defaults = dict(plugins=dict())
|
||||
self.defaults["plugins"][plugin_key] = defaults
|
||||
self.defaults["plugins"][plugin_key]["_config_version"] = None
|
||||
if defaults is not None:
|
||||
self.defaults = dict(plugins=dict())
|
||||
self.defaults["plugins"][plugin_key] = defaults
|
||||
self.defaults["plugins"][plugin_key]["_config_version"] = None
|
||||
else:
|
||||
self.defaults = None
|
||||
|
||||
if get_preprocessors is None:
|
||||
get_preprocessors = dict()
|
||||
@@ -345,14 +333,14 @@ class PluginSettings(object):
|
||||
return result
|
||||
|
||||
def add_getter_kwargs(kwargs):
|
||||
if not "defaults" in kwargs:
|
||||
if not "defaults" in kwargs and self.defaults is not None:
|
||||
kwargs.update(defaults=self.defaults)
|
||||
if not "preprocessors" in kwargs:
|
||||
kwargs.update(preprocessors=self.get_preprocessors)
|
||||
return kwargs
|
||||
|
||||
def add_setter_kwargs(kwargs):
|
||||
if not "defaults" in kwargs:
|
||||
if not "defaults" in kwargs and self.defaults is not None:
|
||||
kwargs.update(defaults=self.defaults)
|
||||
if not "preprocessors" in kwargs:
|
||||
kwargs.update(preprocessors=self.set_preprocessors)
|
||||
|
||||
@@ -149,6 +149,8 @@ class PluginInfo(object):
|
||||
self._license = license
|
||||
|
||||
def validate(self, phase, additional_validators=None):
|
||||
result = True
|
||||
|
||||
if phase == "before_load":
|
||||
# if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__
|
||||
if hasattr(self.instance, self.__class__.attr_init):
|
||||
@@ -183,7 +185,9 @@ class PluginInfo(object):
|
||||
|
||||
if additional_validators is not None:
|
||||
for validator in additional_validators:
|
||||
validator(phase, self)
|
||||
result = result and validator(phase, self)
|
||||
|
||||
return result
|
||||
|
||||
def __str__(self):
|
||||
if self.version:
|
||||
@@ -448,6 +452,12 @@ class PluginManager(object):
|
||||
|
||||
if logging_prefix is None:
|
||||
logging_prefix = ""
|
||||
if plugin_folders is None:
|
||||
plugin_folders = []
|
||||
if plugin_types is None:
|
||||
plugin_types = []
|
||||
if plugin_entry_points is None:
|
||||
plugin_entry_points = []
|
||||
if plugin_disabled_list is None:
|
||||
plugin_disabled_list = []
|
||||
|
||||
@@ -740,7 +750,9 @@ class PluginManager(object):
|
||||
plugin = self.plugins[name]
|
||||
|
||||
try:
|
||||
plugin.validate("before_load", additional_validators=self.plugin_validators)
|
||||
if not plugin.validate("before_load", additional_validators=self.plugin_validators):
|
||||
return
|
||||
|
||||
plugin.load()
|
||||
plugin.validate("after_load", additional_validators=self.plugin_validators)
|
||||
self.on_plugin_loaded(name, plugin)
|
||||
@@ -802,6 +814,9 @@ class PluginManager(object):
|
||||
raise PluginCantEnable(name, "Dependency on obsolete hooks detected, full functionality cannot be guaranteed")
|
||||
|
||||
try:
|
||||
if not plugin.validate("before_enable", additional_validators=self.plugin_validators):
|
||||
return False
|
||||
|
||||
plugin.enable()
|
||||
self._activate_plugin(name, plugin)
|
||||
except PluginLifecycleException as e:
|
||||
|
||||
@@ -1368,14 +1368,17 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
to retrieve the data in the correct format.
|
||||
|
||||
The default implementation will also replace any paths that have been restricted by your plugin through
|
||||
:func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with ``None`` values where necessary.
|
||||
:func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with either the provided
|
||||
default value (if one was provided), an empty dictionary (as fallback for restricted dictionaries), an
|
||||
empty list (as fallback for restricted lists) or ``None`` values where necessary.
|
||||
Make sure to do your own restriction if you decide to fully overload this method.
|
||||
|
||||
:return: the current settings of the plugin, as a dictionary
|
||||
"""
|
||||
from flask.ext.login import current_user
|
||||
import copy
|
||||
|
||||
data = self._settings.get_all_data()
|
||||
data = copy.deepcopy(self._settings.get_all_data(merged=True))
|
||||
if self.config_version_key in data:
|
||||
del data[self.config_version_key]
|
||||
|
||||
@@ -1397,8 +1400,25 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
node = node[entry]
|
||||
|
||||
key = path[-1]
|
||||
default_value_available = False
|
||||
default_value = None
|
||||
if isinstance(key, (list, tuple)):
|
||||
# key, default_value tuple
|
||||
key, default_value = key
|
||||
default_value_available = True
|
||||
|
||||
if key in node:
|
||||
node[key] = None
|
||||
if default_value_available:
|
||||
if callable(default_value):
|
||||
default_value = default_value()
|
||||
node[key] = default_value
|
||||
else:
|
||||
if isinstance(node[key], dict):
|
||||
node[key] = dict()
|
||||
elif isinstance(node[key], (list, tuple)):
|
||||
node[key] = []
|
||||
else:
|
||||
node[key] = None
|
||||
|
||||
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous(),
|
||||
admin=lambda: current_user is not None and not current_user.is_anonymous() and current_user.is_admin(),
|
||||
|
||||
@@ -71,7 +71,7 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.onWizardTabChange = function(current, next) {
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -13,19 +13,19 @@ to OctoPrint, you can also configure additional printer profiles under Settings
|
||||
<div class="tab-content scrollable">
|
||||
<!-- ko with: editor -->
|
||||
<div id="wizard_plugin_corewizard_printerprofile_general" class="tab-pane active">
|
||||
{% include '_snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
|
||||
{% include 'snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
|
||||
</div>
|
||||
|
||||
<div id="wizard_plugin_corewizard_printerprofile_buildvolume" class="tab-pane">
|
||||
{% include '_snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
|
||||
{% include 'snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
|
||||
</div>
|
||||
|
||||
<div id="wizard_plugin_corewizard_printerprofile_axes" class="tab-pane">
|
||||
{% include '_snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
|
||||
{% include 'snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
|
||||
</div>
|
||||
|
||||
<div id="wizard_plugin_corewizard_printerprofile_extruder" class="tab-pane">
|
||||
{% include '_snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
|
||||
{% include 'snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
|
||||
</div>
|
||||
<!-- /ko -->
|
||||
</div>
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
<h4>{{ _('OctoPrint related commands') }}</h4>
|
||||
|
||||
<form class="form-horizontal" data-bind="with: settingsViewModel">
|
||||
{% include "_snippets/settings/server/serverCommandServerRestart.jinja2" %}
|
||||
{% include "snippets/settings/server/serverCommandServerRestart.jinja2" %}
|
||||
</form>
|
||||
|
||||
<h4>{{ _('System related commands') }}</h4>
|
||||
|
||||
<form class="form-horizontal" data-bind="with: settingsViewModel">
|
||||
{% include "_snippets/settings/server/serverCommandSystemRestart.jinja2" %}
|
||||
{% include "_snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
|
||||
{% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %}
|
||||
{% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
|
||||
</form>
|
||||
@@ -26,8 +26,8 @@
|
||||
</p>{% endtrans %}
|
||||
|
||||
<form class="form-horizontal" data-bind="with: settingsViewModel">
|
||||
{% include "_snippets/settings/webcam/webcamStreamUrl.jinja2" %}
|
||||
{% include "_snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
|
||||
{% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %}
|
||||
{% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
|
||||
</form>
|
||||
|
||||
<h4>{{ _('Timelapse Recordings') }}</h4>
|
||||
@@ -38,5 +38,5 @@
|
||||
</p>{% endtrans %}
|
||||
|
||||
<form class="form-horizontal" data-bind="with: settingsViewModel">
|
||||
{% include "_snippets/settings/webcam/ffmpegPath.jinja2" %}
|
||||
{% include "snippets/settings/webcam/ffmpegPath.jinja2" %}
|
||||
</form>
|
||||
@@ -835,7 +835,7 @@ class Profile(object):
|
||||
return 1
|
||||
|
||||
def get_pos_x(self):
|
||||
if self._posX:
|
||||
if self._posX is not None:
|
||||
try:
|
||||
return int(float(self._posX))
|
||||
except ValueError:
|
||||
@@ -844,7 +844,7 @@ class Profile(object):
|
||||
return int(self.get_float("machine_width") / 2.0 ) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
|
||||
def get_pos_y(self):
|
||||
if self._posY:
|
||||
if self._posY is not None:
|
||||
try:
|
||||
return int(float(self._posY))
|
||||
except ValueError:
|
||||
|
||||
@@ -8,13 +8,13 @@
|
||||
{% endtrans %}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
{% include "_snippets/settings/cura/enginePath.jinja2" %}
|
||||
{% include "_snippets/settings/cura/engineLog.jinja2" %}
|
||||
{% include "snippets/settings/cura/enginePath.jinja2" %}
|
||||
{% include "snippets/settings/cura/engineLog.jinja2" %}
|
||||
</form>
|
||||
|
||||
<h4>{{ _('Profiles') }}</h4>
|
||||
|
||||
{% include "_snippets/settings/cura/profiles.jinja2" %}
|
||||
{% include "snippets/settings/cura/profiles.jinja2" %}
|
||||
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
|
||||
|
||||
@@ -22,4 +22,4 @@
|
||||
<small>{% trans %}For more information on configuration and usage please <a href="{{ plugin_cura_homepage }}" target="_blank">see the Plugin's homepage</a>.{% endtrans %}</small>
|
||||
</div>
|
||||
|
||||
{% include "_snippets/settings/cura/profileImporter.jinja2" %}
|
||||
{% include "snippets/settings/cura/profileImporter.jinja2" %}
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
<div style="margin-top: 1em">
|
||||
<form class="form-horizontal">
|
||||
{% include "_snippets/settings/cura/enginePath.jinja2" %}
|
||||
{% include "snippets/settings/cura/enginePath.jinja2" %}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
@@ -15,10 +15,11 @@
|
||||
<div data-bind="visible: unconfiguredSlicingProfile">
|
||||
<h3>{{ _('Set up a slicing profile') }}</h3>
|
||||
<p>{% trans %}You haven't imported a slicing profile to use for slicing with CuraEngine
|
||||
yet. You should do this now.{% endtrans %}</p>
|
||||
yet. If you plan on slicing from within OctoPrint then you should do this now.
|
||||
Otherwise just skip this step.{% endtrans %}</p>
|
||||
|
||||
<div>
|
||||
{% include "_snippets/settings/cura/profiles.jinja2" %}
|
||||
{% include "snippets/settings/cura/profiles.jinja2" %}
|
||||
</div>
|
||||
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -34,6 +34,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
|
||||
|
||||
pip_inapplicable_arguments = dict(uninstall=["--user"])
|
||||
|
||||
def __init__(self):
|
||||
self._pending_enable = set()
|
||||
self._pending_disable = set()
|
||||
@@ -180,6 +182,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if not admin_permission.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
|
||||
from octoprint.server import safe_mode
|
||||
|
||||
refresh_repository = request.values.get("refresh_repository", "false") in valid_boolean_trues
|
||||
if refresh_repository:
|
||||
self._repository_available = self._refresh_repository()
|
||||
@@ -200,7 +204,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
virtual_env=self._pip_caller.virtual_env,
|
||||
additional_args=self._settings.get(["pip_args"]),
|
||||
python=sys.executable
|
||||
))
|
||||
),
|
||||
safe_mode=safe_mode)
|
||||
|
||||
def etag():
|
||||
import hashlib
|
||||
@@ -208,6 +213,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
hash.update(repr(self._get_plugins()))
|
||||
hash.update(str(self._repository_available))
|
||||
hash.update(repr(self._repository_plugins))
|
||||
hash.update(repr(safe_mode))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
@@ -450,7 +456,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
|
||||
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
|
||||
needs_restart_api = needs_restart and not pending
|
||||
safe_mode_victim = getattr(plugin, "safe_mode_victim", False)
|
||||
needs_restart_api = (needs_restart or safe_mode_victim) and not pending
|
||||
needs_refresh_api = needs_refresh and not pending
|
||||
|
||||
try:
|
||||
@@ -482,8 +489,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version")
|
||||
|
||||
additional_args = self._settings.get(["pip_args"])
|
||||
if additional_args:
|
||||
args.append(additional_args)
|
||||
|
||||
if additional_args is not None:
|
||||
|
||||
inapplicable_arguments = self.__class__.pip_inapplicable_arguments.get(args[0], list())
|
||||
for inapplicable_argument in inapplicable_arguments:
|
||||
additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args)
|
||||
|
||||
if additional_args:
|
||||
args.append(additional_args)
|
||||
|
||||
return self._pip_caller.execute(*args)
|
||||
|
||||
@@ -514,12 +528,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._settings.global_set(["plugins", "_disabled"], disabled_list)
|
||||
self._settings.save(force=True)
|
||||
|
||||
if not needs_restart:
|
||||
if not needs_restart and not getattr(plugin, "safe_mode_victim", False):
|
||||
self._plugin_manager.enable_plugin(plugin.key)
|
||||
else:
|
||||
if plugin.key in self._pending_disable:
|
||||
self._pending_disable.remove(plugin.key)
|
||||
elif not plugin.enabled and plugin.key not in self._pending_enable:
|
||||
elif (not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_enable:
|
||||
self._pending_enable.add(plugin.key)
|
||||
|
||||
def _mark_plugin_disabled(self, plugin, needs_restart=False):
|
||||
@@ -529,12 +543,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._settings.global_set(["plugins", "_disabled"], disabled_list)
|
||||
self._settings.save(force=True)
|
||||
|
||||
if not needs_restart:
|
||||
if not needs_restart and not getattr(plugin, "safe_mode_victim", False):
|
||||
self._plugin_manager.disable_plugin(plugin.key)
|
||||
else:
|
||||
if plugin.key in self._pending_enable:
|
||||
self._pending_enable.remove(plugin.key)
|
||||
elif plugin.enabled 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)
|
||||
|
||||
def _fetch_repository_from_disk(self):
|
||||
@@ -688,8 +702,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
bundled=plugin.bundled,
|
||||
managable=plugin.managable,
|
||||
enabled=plugin.enabled,
|
||||
pending_enable=(not plugin.enabled and plugin.key in self._pending_enable),
|
||||
pending_disable=(plugin.enabled and plugin.key in self._pending_disable),
|
||||
safe_mode_victim=getattr(plugin, "safe_mode_victim", False),
|
||||
safe_mode_enabled=getattr(plugin, "safe_mode_enabled", False),
|
||||
pending_enable=(not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False) and plugin.key in self._pending_enable),
|
||||
pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key in self._pending_disable),
|
||||
pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")),
|
||||
pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")),
|
||||
origin=plugin.origin.type
|
||||
|
||||
@@ -155,6 +155,8 @@ $(function() {
|
||||
self.pipAdditionalArgs = ko.observable();
|
||||
self.pipPython = ko.observable();
|
||||
|
||||
self.safeMode = ko.observable();
|
||||
|
||||
self.pipUseUserString = ko.pureComputed(function() {
|
||||
return self.pipUseUser() ? "yes" : "no";
|
||||
});
|
||||
@@ -186,7 +188,8 @@ $(function() {
|
||||
});
|
||||
|
||||
self.enableToggle = function(data) {
|
||||
return self.enableManagement() && data.key != 'pluginmanager';
|
||||
var command = self._getToggleCommand(data);
|
||||
return self.enableManagement() && (command == "disable" || !data.safe_mode_victim || data.safe_mode_enabled) && data.key != 'pluginmanager';
|
||||
};
|
||||
|
||||
self.enableUninstall = function(data) {
|
||||
@@ -199,7 +202,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.enableRepoInstall = function(data) {
|
||||
return self.enableManagement() && self.pipAvailable() && self.isCompatible(data);
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data);
|
||||
};
|
||||
|
||||
self.invalidUrl = ko.pureComputed(function() {
|
||||
@@ -209,7 +212,7 @@ $(function() {
|
||||
|
||||
self.enableUrlInstall = ko.pureComputed(function() {
|
||||
var url = self.installUrl();
|
||||
return self.enableManagement() && self.pipAvailable() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
});
|
||||
|
||||
self.invalidArchive = ko.pureComputed(function() {
|
||||
@@ -219,7 +222,7 @@ $(function() {
|
||||
|
||||
self.enableArchiveInstall = ko.pureComputed(function() {
|
||||
var name = self.uploadFilename();
|
||||
return self.enableManagement() && self.pipAvailable() && name !== undefined && name.trim() != "" && !self.invalidArchive();
|
||||
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && name !== undefined && name.trim() != "" && !self.invalidArchive();
|
||||
});
|
||||
|
||||
self.uploadElement.fileupload({
|
||||
@@ -246,7 +249,7 @@ $(function() {
|
||||
done: function(e, data) {
|
||||
self._markDone();
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadFilename("");
|
||||
self.uploadFilename(undefined);
|
||||
},
|
||||
fail: function(e, data) {
|
||||
new PNotify({
|
||||
@@ -257,7 +260,7 @@ $(function() {
|
||||
});
|
||||
self._markDone();
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadFilename("");
|
||||
self.uploadFilename(undefined);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -278,6 +281,8 @@ $(function() {
|
||||
self._fromPluginsResponse(data.plugins);
|
||||
self._fromRepositoryResponse(data.repository);
|
||||
self._fromPipResponse(data.pip);
|
||||
|
||||
self.safeMode(data.safe_mode || false);
|
||||
};
|
||||
|
||||
self._fromPluginsResponse = function(data) {
|
||||
@@ -347,6 +352,7 @@ $(function() {
|
||||
};
|
||||
|
||||
if (self._getToggleCommand(data) == "enable") {
|
||||
if (data.safe_mode_victim && !data.safe_mode_enabled) return;
|
||||
OctoPrint.plugins.pluginmanager.enable(data.key)
|
||||
.done(onSuccess)
|
||||
.fail(onError);
|
||||
@@ -547,7 +553,7 @@ $(function() {
|
||||
title: titleSuccess,
|
||||
text: textRestart,
|
||||
buttons: {
|
||||
closer: false,
|
||||
closer: true,
|
||||
sticker: false
|
||||
},
|
||||
callbacks: {
|
||||
@@ -600,7 +606,7 @@ $(function() {
|
||||
}]
|
||||
},
|
||||
buttons: {
|
||||
closer: false,
|
||||
closer: true,
|
||||
sticker: false
|
||||
},
|
||||
callbacks: {
|
||||
@@ -640,8 +646,9 @@ $(function() {
|
||||
|
||||
self.loglines.removeAll();
|
||||
self.loglines.push({line: line, stream: "message"});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
|
||||
self.workingDialog.modal("show");
|
||||
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
};
|
||||
|
||||
self._markDone = function() {
|
||||
@@ -655,7 +662,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self._getToggleCommand = function(data) {
|
||||
return ((!data.enabled || data.pending_disable) && !data.pending_enable) ? "enable" : "disable";
|
||||
var disable = (data.enabled || data.pending_enable || (data.safe_mode_victim && data.safe_mode_enabled)) && !data.pending_disable;
|
||||
return disable ? "disable" : "enable";
|
||||
};
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
@@ -666,7 +674,16 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleButtonTitle = function(data) {
|
||||
return self._getToggleCommand(data) == "enable" ? gettext("Enable Plugin") : gettext("Disable Plugin");
|
||||
var command = self._getToggleCommand(data);
|
||||
if (command == "enable") {
|
||||
if (data.safe_mode_victim && !data.safe_mode_enabled) {
|
||||
return gettext("Disabled due to active safe mode");
|
||||
} else {
|
||||
return gettext("Enable Plugin");
|
||||
}
|
||||
} else {
|
||||
return gettext("Disable Plugin");
|
||||
}
|
||||
};
|
||||
|
||||
self.onBeforeBinding = function() {
|
||||
@@ -682,6 +699,10 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self._closeAllNotifications();
|
||||
};
|
||||
|
||||
self._closeAllNotifications = function() {
|
||||
if (self.notifications) {
|
||||
_.each(self.notifications, function(notification) {
|
||||
notification.remove();
|
||||
@@ -689,6 +710,11 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.onServerDisconnect = function() {
|
||||
self._closeAllNotifications();
|
||||
return true;
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.workingDialog = $("#settings_plugin_pluginmanager_workingdialog");
|
||||
self.workingOutput = $("#settings_plugin_pluginmanager_workingdialog_output");
|
||||
@@ -721,7 +747,7 @@ $(function() {
|
||||
|
||||
if (messageType == "loglines" && self.working()) {
|
||||
_.each(data.loglines, function(line) {
|
||||
self.loglines.push(line);
|
||||
self.loglines.push(self._preprocessLine(line));
|
||||
});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
} else if (messageType == "result") {
|
||||
@@ -836,6 +862,14 @@ $(function() {
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
|
||||
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
|
||||
self._preprocessLine = function(line) {
|
||||
if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
}
|
||||
return line;
|
||||
}
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
|
||||
@@ -13,8 +13,16 @@
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro pluginmanager_safemode() %}
|
||||
<div class="alert" data-bind="visible: safeMode">{% trans %}
|
||||
Safe mode is currently active. All third party plugins are disabled and cannot be
|
||||
enabled. Installation of plugin packages is disabled.
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||
@@ -32,7 +40,7 @@
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i class="icon-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="icon-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="icon-minus" data-bind="visible: pending_uninstall"></i></div>
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i class="icon-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="icon-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="icon-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="icon-medkit" data-bind="visible: safe_mode_victim"></i></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div data-bind="css: {muted: !enabled}">
|
||||
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
@@ -80,7 +88,6 @@
|
||||
|
||||
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3 data-bind="text: workingTitle"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
@@ -99,6 +106,7 @@
|
||||
<div class="modal-body">
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_safemode() }}
|
||||
<h4 style="position: relative">
|
||||
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
|
||||
<div class="dropdown pull-right">
|
||||
|
||||
@@ -794,9 +794,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
try:
|
||||
util.execute(restart_command)
|
||||
except exceptions.ScriptError as e:
|
||||
self._logger.exception("Error while restarting")
|
||||
self._logger.warn("Restart stdout:\n%s" % e.stdout)
|
||||
self._logger.warn("Restart stderr:\n%s" % e.stderr)
|
||||
self._logger.exception("Error while restarting via command {}".format(restart_command))
|
||||
self._logger.warn("Restart stdout:\n{}".format(e.stdout))
|
||||
self._logger.warn("Restart stderr:\n{}".format(e.stderr))
|
||||
raise exceptions.RestartFailed()
|
||||
|
||||
def _populated_check(self, target, check):
|
||||
@@ -882,7 +882,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
self._send_client_message("loglines", data=dict(loglines=[dict(line=line, stream=stream) for line in lines]))
|
||||
for line in lines:
|
||||
self._console_logger.debug(u"{prefix} {line}".format(**locals()))
|
||||
self._console_logger.debug(u"{} {}".format(prefix, line))
|
||||
|
||||
def _send_client_message(self, message_type, data=None):
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type=message_type, data=data))
|
||||
|
||||
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import errno
|
||||
import sys
|
||||
import traceback
|
||||
import time
|
||||
|
||||
def _log_call(*lines):
|
||||
_log(lines, prefix=">", stream="call")
|
||||
@@ -27,7 +29,9 @@ def _log(lines, prefix=None, stream=None):
|
||||
output_stream = sys.stderr
|
||||
|
||||
for line in lines:
|
||||
print(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")), file=output_stream)
|
||||
to_print = _to_str(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")),
|
||||
errors="replace")
|
||||
print(to_print, file=output_stream)
|
||||
|
||||
|
||||
def _to_unicode(s_or_u, encoding="utf-8", errors="strict"):
|
||||
@@ -38,6 +42,14 @@ def _to_unicode(s_or_u, encoding="utf-8", errors="strict"):
|
||||
return s_or_u
|
||||
|
||||
|
||||
def _to_str(s_or_u, encoding="utf-8", errors="strict"):
|
||||
"""Make sure ``s_or_u`` is a str."""
|
||||
if isinstance(s_or_u, unicode):
|
||||
return s_or_u.encode(encoding, errors=errors)
|
||||
else:
|
||||
return s_or_u
|
||||
|
||||
|
||||
def _execute(command, **kwargs):
|
||||
import sarge
|
||||
|
||||
@@ -51,39 +63,54 @@ def _execute(command, **kwargs):
|
||||
|
||||
try:
|
||||
p = sarge.run(command, **kwargs)
|
||||
p.wait_events()
|
||||
except Exception as e:
|
||||
import traceback
|
||||
exception_lines = traceback.format_exc()
|
||||
error = "Error while trying to run command {}: {}\n{}".format(joined_command, str(e), exception_lines)
|
||||
return None, "", error
|
||||
while len(p.commands) == 0:
|
||||
# somewhat ugly... we can't use wait_events because
|
||||
# the events might not be all set if an exception
|
||||
# by sarge is triggered within the async process
|
||||
# thread
|
||||
time.sleep(0.01)
|
||||
|
||||
# by now we should have a command, let's wait for its
|
||||
# process to have been prepared
|
||||
p.commands[0].process_ready.wait()
|
||||
|
||||
if not p.commands[0].process:
|
||||
# the process might have been set to None in case of any exception
|
||||
print("Error while trying to run command {}".format(joined_command), file=sys.stderr)
|
||||
return None, [], []
|
||||
except:
|
||||
print("Error while trying to run command {}".format(joined_command), file=sys.stderr)
|
||||
traceback.print_exc(file=sys.stderr)
|
||||
return None, [], []
|
||||
|
||||
all_stdout = []
|
||||
all_stderr = []
|
||||
try:
|
||||
while p.returncode is None:
|
||||
while p.commands[0].poll() is None:
|
||||
lines = p.stderr.readlines(timeout=0.5)
|
||||
if lines:
|
||||
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
|
||||
_log_stderr(*lines)
|
||||
all_stderr += list(lines)
|
||||
|
||||
lines = p.stdout.readlines(timeout=0.5)
|
||||
if lines:
|
||||
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
|
||||
_log_stdout(*lines)
|
||||
all_stdout += list(lines)
|
||||
|
||||
p.commands[0].poll()
|
||||
|
||||
finally:
|
||||
p.close()
|
||||
|
||||
lines = p.stderr.readlines()
|
||||
if lines:
|
||||
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
|
||||
_log_stderr(*lines)
|
||||
all_stderr += lines
|
||||
|
||||
lines = p.stdout.readlines()
|
||||
if lines:
|
||||
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
|
||||
_log_stdout(*lines)
|
||||
all_stdout += lines
|
||||
|
||||
@@ -97,27 +124,31 @@ def _get_git_executables():
|
||||
return GITS
|
||||
|
||||
|
||||
def _git(args, cwd, verbose=False, git_executable=None):
|
||||
def _git(args, cwd, git_executable=None):
|
||||
if git_executable is not None:
|
||||
commands = [git_executable]
|
||||
else:
|
||||
commands = _get_git_executables()
|
||||
|
||||
for c in commands:
|
||||
command = [c] + args
|
||||
try:
|
||||
return _execute([c] + args, cwd=cwd)
|
||||
return _execute(command, cwd=cwd)
|
||||
except EnvironmentError:
|
||||
e = sys.exc_info()[1]
|
||||
if e.errno == errno.ENOENT:
|
||||
continue
|
||||
if verbose:
|
||||
print("unable to run %s" % args[0])
|
||||
print(e)
|
||||
return None, None, None
|
||||
|
||||
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
|
||||
traceback.print_exc(file=sys.stderr)
|
||||
return None, [], []
|
||||
except:
|
||||
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
|
||||
traceback.print_exc(file=sys.stderr)
|
||||
return None, [], []
|
||||
else:
|
||||
if verbose:
|
||||
print("unable to find command, tried %s" % (commands,))
|
||||
return None, None, None
|
||||
print("Unable to find git command, tried {}".format(", ".join(commands)), file=sys.stderr)
|
||||
return None, [], []
|
||||
|
||||
|
||||
def _python(args, cwd, python_executable, sudo=False):
|
||||
@@ -127,31 +158,40 @@ def _python(args, cwd, python_executable, sudo=False):
|
||||
try:
|
||||
return _execute(command, cwd=cwd)
|
||||
except:
|
||||
return None, None, None
|
||||
import traceback
|
||||
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
|
||||
traceback.print_exc(file=sys.stderr)
|
||||
return None, [], []
|
||||
|
||||
|
||||
def _to_error(*lines):
|
||||
return u"".join(map(lambda x: _to_unicode(x, errors="replace"), lines))
|
||||
if len(lines) == 1:
|
||||
if isinstance(lines[0], (list, tuple)):
|
||||
lines = lines[0]
|
||||
elif not isinstance(lines[0], (str, unicode)):
|
||||
lines = [repr(lines[0]),]
|
||||
return u"\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines))
|
||||
|
||||
|
||||
def _rescue_changes(git_executable, folder):
|
||||
print(">>> Running: git diff --shortstat")
|
||||
returncode, stdout, stderr = _git(["diff", "--shortstat"], folder, git_executable=git_executable)
|
||||
if returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git diff\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
|
||||
if stdout and "".join(stdout).strip():
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git diff\" failed with returncode {}".format(returncode))
|
||||
if stdout and u"".join(stdout).strip():
|
||||
# we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch
|
||||
import time
|
||||
import os
|
||||
timestamp = time.strftime("%Y%m%d%H%M")
|
||||
patch = os.path.join(folder, "%s-preupdate.patch" % timestamp)
|
||||
patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp))
|
||||
|
||||
print(">>> Running: git diff and saving output to %s" % timestamp)
|
||||
print(">>> Running: git diff and saving output to {}".format(patch))
|
||||
returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable)
|
||||
if returncode != 0:
|
||||
raise RuntimeError("Could not update, installation directory was dirty and state could not be persisted as a patch to %s" % patch)
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError("Could not update, installation directory was dirty and state could not be persisted as a patch to {}".format(patch))
|
||||
|
||||
with open(patch, "wb") as f:
|
||||
import codecs
|
||||
with codecs.open(patch, "w", encoding="utf-8", errors="replace") as f:
|
||||
for line in stdout:
|
||||
f.write(line)
|
||||
|
||||
@@ -164,46 +204,45 @@ def update_source(git_executable, folder, target, force=False, branch=None):
|
||||
if _rescue_changes(git_executable, folder):
|
||||
print(">>> Running: git reset --hard")
|
||||
returncode, stdout, stderr = _git(["reset", "--hard"], folder, git_executable=git_executable)
|
||||
if returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode {}".format(returncode))
|
||||
|
||||
print(">>> Running: git clean -f -d -e *-preupdate.patch")
|
||||
returncode, stdout, stderr = _git(["clean", "-f", "-d", "-e", "*-preupdate.patch"], folder, git_executable=git_executable)
|
||||
if returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git clean -f\" failed with returcode %d: %s" % (returncode, _to_error(*stdout)))
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git clean -f\" failed with returncode {}".format(returncode))
|
||||
|
||||
print(">>> Running: git fetch")
|
||||
returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable)
|
||||
if returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git fetch\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
|
||||
print(stdout)
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git fetch\" failed with returncode {}".format(returncode))
|
||||
|
||||
if branch is not None and branch.strip() != "":
|
||||
print(">>> Running: git checkout {}".format(branch))
|
||||
returncode, stdout, stderr = _git(["checkout", branch], folder, git_executable=git_executable)
|
||||
if returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git checkout\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git checkout\" failed with returncode {}".format(returncode))
|
||||
|
||||
print(">>> Running: git pull")
|
||||
returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable)
|
||||
if returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git pull\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError("Could not update, \"git pull\" failed with returncode {}".format(returncode))
|
||||
|
||||
if force:
|
||||
reset_command = ["reset", "--hard"]
|
||||
reset_command += [target]
|
||||
|
||||
print(">>> Running: git %s" % " ".join(reset_command))
|
||||
print(">>> Running: git {}".format(" ".join(reset_command)))
|
||||
returncode, stdout, stderr = _git(reset_command, folder, git_executable=git_executable)
|
||||
if returncode != 0:
|
||||
raise RuntimeError("Error while updating, \"git %s\" failed with returncode %d: %s" % (" ".join(reset_command), returncode, _to_error(*stdout)))
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError("Error while updating, \"git {}\" failed with returncode {}".format(" ".join(reset_command), returncode))
|
||||
|
||||
|
||||
def install_source(python_executable, folder, user=False, sudo=False):
|
||||
print(">>> Running: python setup.py clean")
|
||||
returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable)
|
||||
if returncode != 0:
|
||||
print("\"python setup.py clean\" failed with returncode %d: %s" % (returncode, stdout))
|
||||
if returncode is None or returncode != 0:
|
||||
print("\"python setup.py clean\" failed with returncode {}".format(returncode))
|
||||
print("Continuing anyways")
|
||||
|
||||
print(">>> Running: python setup.py install")
|
||||
@@ -211,15 +250,14 @@ def install_source(python_executable, folder, user=False, sudo=False):
|
||||
if user:
|
||||
args.append("--user")
|
||||
returncode, stdout, stderr = _python(args, folder, python_executable, sudo=sudo)
|
||||
if returncode != 0:
|
||||
raise RuntimeError("Could not update, \"python setup.py install\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError("Could not update, \"python setup.py install\" failed with returncode {}".format(returncode))
|
||||
|
||||
|
||||
def parse_arguments():
|
||||
import argparse
|
||||
|
||||
boolean_trues = ["true", "yes", "1"]
|
||||
boolean_falses = ["false", "no", "0"]
|
||||
|
||||
parser = argparse.ArgumentParser(prog="update-octoprint.py")
|
||||
|
||||
|
||||
@@ -103,6 +103,8 @@ $(function() {
|
||||
self.workingOutput = undefined;
|
||||
self.loglines = ko.observableArray([]);
|
||||
|
||||
self.checking = ko.observable(false);
|
||||
|
||||
self.octoprintUnconfigured = ko.observable();
|
||||
self.octoprintUnreleased = ko.observable();
|
||||
|
||||
@@ -333,7 +335,7 @@ $(function() {
|
||||
};
|
||||
}
|
||||
|
||||
if (ignoreSeen || !self._hasNotificationBeenSeen(data.information)) {
|
||||
if ((ignoreSeen || !self._hasNotificationBeenSeen(data.information)) && !OctoPrint.coreui.wizardOpen) {
|
||||
self._showPopup(options, eventListeners);
|
||||
}
|
||||
} else if (data.status == "current") {
|
||||
@@ -351,9 +353,13 @@ $(function() {
|
||||
|
||||
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
|
||||
if (!self.loginState.isUser()) return;
|
||||
self.checking(true);
|
||||
OctoPrint.plugins.softwareupdate.check(force)
|
||||
.done(function(data) {
|
||||
self.fromCheckResponse(data, ignoreSeen, showIfNothingNew);
|
||||
})
|
||||
.always(function() {
|
||||
self.checking(false);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -454,7 +460,7 @@ $(function() {
|
||||
|
||||
self.working(true);
|
||||
self.workingTitle(title);
|
||||
self.workingDialog.modal("show");
|
||||
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
};
|
||||
|
||||
self._markWorking = function(title, line, stream) {
|
||||
@@ -482,7 +488,7 @@ $(function() {
|
||||
self.workingOutput.scrollTop(self.workingOutput[0].scrollHeight - self.workingOutput.height());
|
||||
};
|
||||
|
||||
self.onWizardTabChange = function(current, next) {
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (next && _.startsWith(next, "wizard_plugin_softwareupdate")) {
|
||||
// switching to the plugin wizard tab
|
||||
self._copyConfig();
|
||||
@@ -539,7 +545,7 @@ $(function() {
|
||||
case "loglines": {
|
||||
if (self.working()) {
|
||||
_.each(messageData.loglines, function(line) {
|
||||
self.loglines.push(line);
|
||||
self.loglines.push(self._preprocessLine(line));
|
||||
});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
}
|
||||
@@ -557,6 +563,7 @@ $(function() {
|
||||
self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
|
||||
self.loglines.push({line: text, stream: "message"});
|
||||
self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
self._updatePopup({
|
||||
text: text,
|
||||
hide: false,
|
||||
@@ -584,6 +591,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.loglines.push({line: text, stream: "message"});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
|
||||
self.waitingForRestart = true;
|
||||
self.restartTimeout = setTimeout(function() {
|
||||
@@ -694,6 +702,13 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
|
||||
self._preprocessLine = function(line) {
|
||||
if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
}
|
||||
return line;
|
||||
}
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -57,12 +57,12 @@
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }">{{ _('Check for update now') }}</button>
|
||||
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="icon-spinner icon-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }">{{ _('Force check for update (overrides cache used for update checks)') }}</button>
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="icon-spinner icon-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -74,9 +74,9 @@
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
{% include "_snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
|
||||
{% include "_snippets/plugins/softwareupdate/versionTracking.jinja2" %}
|
||||
{% include "_snippets/plugins/softwareupdate/releaseChannel.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/versionTracking.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/releaseChannel.jinja2" %}
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Version cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
@@ -96,7 +96,6 @@
|
||||
|
||||
<div id="settings_plugin_softwareupdate_workingdialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3 data-bind="text: workingTitle"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
</p>{% endtrans %}
|
||||
|
||||
<form class="form-horizontal">
|
||||
{% include "_snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
|
||||
{% include "_snippets/plugins/softwareupdate/versionTracking.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/versionTracking.jinja2" %}
|
||||
</form>
|
||||
|
||||
{% trans %}<p>
|
||||
|
||||
@@ -28,6 +28,7 @@ def _filter_out_latest(releases,
|
||||
>>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
|
||||
>>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance")
|
||||
>>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
|
||||
>>> release_1_2_18 = dict(name="1.2.18", tag_name="1.2.18", html_url="some_url", published_at="2016-12-13T12:00:00Z", prerelease=False, draft=False, target_commitish="master")
|
||||
>>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future")
|
||||
>>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1]
|
||||
>>> _filter_out_latest(releases, include_prerelease=False, prerelease_channel=None)
|
||||
@@ -44,6 +45,14 @@ def _filter_out_latest(releases,
|
||||
(None, None, None)
|
||||
>>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2])
|
||||
(None, None, None)
|
||||
>>> comparable_factory = _get_comparable_factory("python", force_base=True)
|
||||
>>> sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, prerelease_channel=None, sort_key=sort_key)
|
||||
('1.2.18', '1.2.18', 'some_url')
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/maintenance", sort_key=sort_key)
|
||||
('1.2.18', '1.2.18', 'some_url')
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/devel", sort_key=sort_key)
|
||||
('1.3.0rc1', '1.3.0rc1', 'some_url')
|
||||
"""
|
||||
|
||||
nothing = None, None, None
|
||||
|
||||
@@ -59,15 +59,17 @@ class VirtualPrinter(object):
|
||||
self.lastTempAt = time.time()
|
||||
self.bedTemp = 1.0
|
||||
self.bedTargetTemp = 1.0
|
||||
self.speeds = settings().get(["devel", "virtualPrinter", "movementSpeed"])
|
||||
|
||||
self._relative = True
|
||||
self._lastX = None
|
||||
self._lastY = None
|
||||
self._lastZ = None
|
||||
self._lastE = None
|
||||
self._lastX = 0.0
|
||||
self._lastY = 0.0
|
||||
self._lastZ = 0.0
|
||||
self._lastE = 0.0
|
||||
self._lastF = 200
|
||||
|
||||
self._unitModifier = 1
|
||||
self._feedrate_multiplier = 100
|
||||
self._flowrate_multiplier = 100
|
||||
|
||||
self._virtualSd = settings().getBaseFolder("virtualSd")
|
||||
self._sdCardReady = True
|
||||
@@ -92,6 +94,8 @@ class VirtualPrinter(object):
|
||||
|
||||
self._brokenM29 = settings().getBoolean(["devel", "virtualPrinter", "brokenM29"])
|
||||
|
||||
self._firmwareName = settings().get(["devel", "virtualPrinter", "firmwareName"])
|
||||
|
||||
self.currentLine = 0
|
||||
self.lastN = 0
|
||||
|
||||
@@ -317,7 +321,7 @@ class VirtualPrinter(object):
|
||||
def _gcode_M140(self, data):
|
||||
self._parseBedCommand(data)
|
||||
|
||||
def _gcode_M140(self, data):
|
||||
def _gcode_M190(self, data):
|
||||
self._parseBedCommand(data, wait=True, support_r=True)
|
||||
|
||||
def _gcode_M105(self, data):
|
||||
@@ -372,17 +376,27 @@ class VirtualPrinter(object):
|
||||
self._deleteSdFile(filename)
|
||||
|
||||
def _gcode_M114(self, data):
|
||||
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE, int(self._lastX*100), int(self.lastY*100), int(self.lastZ*100))
|
||||
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE, int(self._lastX*100), int(self._lastY*100), int(self._lastZ*100))
|
||||
if not self._okBeforeCommandOutput:
|
||||
output = "ok " + output
|
||||
self._send(output)
|
||||
return True
|
||||
|
||||
def _gcode_M115(self, data):
|
||||
output = "FIRMWARE_NAME:{} PROTOCOL_VERSION:1.0".format(self._firmwareName)
|
||||
self._send(output)
|
||||
|
||||
def _gcode_M117(self, data):
|
||||
# we'll just use this to echo a message, to allow playing around with pause triggers
|
||||
if self._echoOnM117:
|
||||
self._send("echo:%s" % re.search("M117\s+(.*)", data).group(1))
|
||||
|
||||
def _gcode_M220(self, data):
|
||||
self._feedrate_multiplier = float(re.search('S([0-9]+)', data).group(1))
|
||||
|
||||
def _gcode_M221(self, data):
|
||||
self._flowrate_multiplier = float(re.search('S([0-9]+)', data).group(1))
|
||||
|
||||
def _gcode_M400(self, data):
|
||||
self.buffered.join()
|
||||
|
||||
@@ -631,16 +645,18 @@ class VirtualPrinter(object):
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "includeCurrentToolInTemps"]):
|
||||
if includeTarget:
|
||||
output = "T:%.2f /%.2f %s @:64\n" % (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder] + 1, allTempsString)
|
||||
output = "T:%.2f /%.2f %s" % (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder] + 1, allTempsString)
|
||||
else:
|
||||
output = "T:%.2f %s @:64\n" % (self.temp[self.currentExtruder], allTempsString)
|
||||
output = "T:%.2f %s" % (self.temp[self.currentExtruder], allTempsString)
|
||||
else:
|
||||
output = "%s @:64\n" % allTempsString
|
||||
output = allTempsString
|
||||
else:
|
||||
if includeTarget:
|
||||
output = "T:%.2f /%.2f B:%.2f /%.2f @:64\n" % (self.temp[0], self.targetTemp[0], self.bedTemp, self.bedTargetTemp)
|
||||
output = "T:%.2f /%.2f B:%.2f /%.2f" % (self.temp[0], self.targetTemp[0], self.bedTemp, self.bedTargetTemp)
|
||||
else:
|
||||
output = "T:%.2f B:%.2f @:64\n" % (self.temp[0], self.bedTemp)
|
||||
output = "T:%.2f B:%.2f" % (self.temp[0], self.bedTemp)
|
||||
|
||||
output += " @:64\n"
|
||||
|
||||
if includeOk:
|
||||
output = "ok " + output
|
||||
@@ -696,46 +712,72 @@ class VirtualPrinter(object):
|
||||
matchY = re.search("Y([0-9.]+)", line)
|
||||
matchZ = re.search("Z([0-9.]+)", line)
|
||||
matchE = re.search("E([0-9.]+)", line)
|
||||
matchF = re.search("F([0-9.]+)", line)
|
||||
|
||||
duration = 0
|
||||
if matchF is not None:
|
||||
try:
|
||||
self._lastF = float(matchF.group(1))
|
||||
except:
|
||||
pass
|
||||
|
||||
speedXYZ = self._lastF * (self._feedrate_multiplier / 100.0)
|
||||
speedE = self._lastF * (self._flowrate_multiplier / 100.0)
|
||||
|
||||
if matchX is not None:
|
||||
try:
|
||||
x = float(matchX.group(1))
|
||||
if self._relative or self._lastX is None:
|
||||
duration = max(duration, x * self._unitModifier / float(self.speeds["x"]) * 60.0)
|
||||
duration = max(duration, x * self._unitModifier / speedXYZ * 60.0)
|
||||
else:
|
||||
duration = max(duration, (x - self._lastX) * self._unitModifier / float(self.speeds["x"]) * 60.0)
|
||||
self._lastX = x
|
||||
duration = max(duration, (x - self._lastX) * self._unitModifier / speedXYZ * 60.0)
|
||||
|
||||
if self._relative and self._lastX is not None:
|
||||
self._lastX += x
|
||||
else:
|
||||
self._lastX = x
|
||||
except:
|
||||
pass
|
||||
if matchY is not None:
|
||||
try:
|
||||
y = float(matchY.group(1))
|
||||
if self._relative or self._lastY is None:
|
||||
duration = max(duration, y * self._unitModifier / float(self.speeds["y"]) * 60.0)
|
||||
duration = max(duration, y * self._unitModifier / speedXYZ * 60.0)
|
||||
else:
|
||||
duration = max(duration, (y - self._lastY) * self._unitModifier / float(self.speeds["y"]) * 60.0)
|
||||
self._lastY = y
|
||||
duration = max(duration, (y - self._lastY) * self._unitModifier / speedXYZ * 60.0)
|
||||
|
||||
if self._relative and self._lastY is not None:
|
||||
self._lastY += y
|
||||
else:
|
||||
self._lastY = y
|
||||
except:
|
||||
pass
|
||||
if matchZ is not None:
|
||||
try:
|
||||
z = float(matchZ.group(1))
|
||||
if self._relative or self._lastZ is None:
|
||||
duration = max(duration, z * self._unitModifier / float(self.speeds["z"]) * 60.0)
|
||||
duration = max(duration, z * self._unitModifier / speedXYZ * 60.0)
|
||||
else:
|
||||
duration = max(duration, (z - self._lastZ) * self._unitModifier / float(self.speeds["z"]) * 60.0)
|
||||
self._lastZ = z
|
||||
duration = max(duration, (z - self._lastZ) * self._unitModifier / speedXYZ * 60.0)
|
||||
|
||||
if self._relative and self._lastZ is not None:
|
||||
self._lastZ += z
|
||||
else:
|
||||
self._lastZ = z
|
||||
except:
|
||||
pass
|
||||
if matchE is not None:
|
||||
try:
|
||||
e = float(matchE.group(1))
|
||||
if self._relative or self._lastE is None:
|
||||
duration = max(duration, e * self._unitModifier / float(self.speeds["e"]) * 60.0)
|
||||
duration = max(duration, e * self._unitModifier / speedE * 60.0)
|
||||
else:
|
||||
duration = max(duration, (e - self._lastE) * self._unitModifier / float(self.speeds["e"]) * 60.0)
|
||||
self._lastE = e
|
||||
duration = max(duration, (e - self._lastE) * self._unitModifier / speedE * 60.0)
|
||||
|
||||
if self._relative and self._lastE is not None:
|
||||
self._lastE += e
|
||||
else:
|
||||
self._lastE = e
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ class BedTypes(object):
|
||||
|
||||
@classmethod
|
||||
def values(cls):
|
||||
return [getattr(cls, name) for name in cls.__dict__ if not name.startswith("__")]
|
||||
return [getattr(cls, name) for name in cls.__dict__ if not (name.startswith("__") or name == "values")]
|
||||
|
||||
class BedOrigin(object):
|
||||
LOWERLEFT = "lowerleft"
|
||||
@@ -42,7 +42,7 @@ class BedOrigin(object):
|
||||
|
||||
@classmethod
|
||||
def values(cls):
|
||||
return [getattr(cls, name) for name in cls.__dict__ if not name.startswith("__")]
|
||||
return [getattr(cls, name) for name in cls.__dict__ if not (name.startswith("__") or name == "values")]
|
||||
|
||||
class PrinterProfileManager(object):
|
||||
"""
|
||||
@@ -88,6 +88,28 @@ class PrinterProfileManager(object):
|
||||
* - ``volume.origin``
|
||||
- ``string``
|
||||
- Location of gcode origin in the print volume, either ``lowerleft`` or ``center``
|
||||
* - ``volume.custom_box``
|
||||
- ``dict`` or ``False``
|
||||
- Custom boundary box overriding the default bounding box based on the provided width, depth, height and origin.
|
||||
If ``False``, the default boundary box will be used.
|
||||
* - ``volume.custom_box.x_min``
|
||||
- ``float``
|
||||
- Minimum valid X coordinate
|
||||
* - ``volume.custom_box.y_min``
|
||||
- ``float``
|
||||
- Minimum valid Y coordinate
|
||||
* - ``volume.custom_box.z_min``
|
||||
- ``float``
|
||||
- Minimum valid Z coordinate
|
||||
* - ``volume.custom_box.x_max``
|
||||
- ``float``
|
||||
- Maximum valid X coordinate
|
||||
* - ``volume.custom_box.y_max``
|
||||
- ``float``
|
||||
- Maximum valid Y coordinate
|
||||
* - ``volume.custom_box.z_max``
|
||||
- ``float``
|
||||
- Maximum valid Z coordinate
|
||||
* - ``heatedBed``
|
||||
- ``bool``
|
||||
- Whether the printer has a heated bed (``True``) or not (``False``)
|
||||
@@ -154,7 +176,8 @@ class PrinterProfileManager(object):
|
||||
depth = 200,
|
||||
height = 200,
|
||||
formFactor = BedTypes.RECTANGULAR,
|
||||
origin = BedOrigin.LOWERLEFT
|
||||
origin = BedOrigin.LOWERLEFT,
|
||||
custom_box = False
|
||||
),
|
||||
heatedBed = True,
|
||||
extruder=dict(
|
||||
@@ -391,11 +414,17 @@ class PrinterProfileManager(object):
|
||||
|
||||
def _migrate_profile(self, profile):
|
||||
# make sure profile format is up to date
|
||||
modified = False
|
||||
|
||||
if "volume" in profile and "formFactor" in profile["volume"] and not "origin" in profile["volume"]:
|
||||
profile["volume"]["origin"] = BedOrigin.CENTER if profile["volume"]["formFactor"] == BedTypes.CIRCULAR else BedOrigin.LOWERLEFT
|
||||
return True
|
||||
modified = True
|
||||
|
||||
return False
|
||||
if "volume" in profile and not "custom_box" in profile["volume"]:
|
||||
profile["volume"]["custom_box"] = False
|
||||
modified = True
|
||||
|
||||
return modified
|
||||
|
||||
def _ensure_valid_profile(self, profile):
|
||||
# ensure all keys are present
|
||||
@@ -458,6 +487,35 @@ class PrinterProfileManager(object):
|
||||
if profile["volume"]["formFactor"] == BedTypes.CIRCULAR:
|
||||
profile["volume"]["depth"] = profile["volume"]["width"]
|
||||
|
||||
# if we have a custom bounding box, validate it
|
||||
if profile["volume"]["custom_box"] and isinstance(profile["volume"]["custom_box"], dict):
|
||||
if not len(profile["volume"]["custom_box"]):
|
||||
profile["volume"]["custom_box"] = False
|
||||
|
||||
else:
|
||||
default_box = self._default_box_for_volume(profile["volume"])
|
||||
for prop, limiter in (("x_min", min), ("y_min", min), ("z_min", min),
|
||||
("x_max", max), ("y_max", max), ("z_max", max)):
|
||||
if prop not in profile["volume"]["custom_box"] or profile["volume"]["custom_box"][prop] is None:
|
||||
profile["volume"]["custom_box"][prop] = default_box[prop]
|
||||
else:
|
||||
value = profile["volume"]["custom_box"][prop]
|
||||
try:
|
||||
value = limiter(float(value), default_box[prop])
|
||||
profile["volume"]["custom_box"][prop] = value
|
||||
except:
|
||||
self._logger.warn("Profile has invalid value in volume.custom_box.{}: {!r}".format(prop, value))
|
||||
return False
|
||||
|
||||
# make sure we actually do have a custom box and not just the same values as the
|
||||
# default box
|
||||
for prop in profile["volume"]["custom_box"]:
|
||||
if profile["volume"]["custom_box"][prop] != default_box[prop]:
|
||||
break
|
||||
else:
|
||||
# exactly the same as the default box, remove custom box
|
||||
profile["volume"]["custom_box"] = False
|
||||
|
||||
# validate offsets
|
||||
offsets = []
|
||||
for offset in profile["extruder"]["offsets"]:
|
||||
@@ -474,3 +532,21 @@ class PrinterProfileManager(object):
|
||||
|
||||
return profile
|
||||
|
||||
@staticmethod
|
||||
def _default_box_for_volume(volume):
|
||||
if volume["origin"] == BedOrigin.CENTER:
|
||||
half_width = volume["width"] / 2.0
|
||||
half_depth = volume["depth"] / 2.0
|
||||
return dict(x_min=-half_width,
|
||||
x_max=half_width,
|
||||
y_min=-half_depth,
|
||||
y_max=half_depth,
|
||||
z_min=0.0,
|
||||
z_max=volume["height"])
|
||||
else:
|
||||
return dict(x_min=0.0,
|
||||
x_max=volume["width"],
|
||||
y_min=0.0,
|
||||
y_max=volume["depth"],
|
||||
z_min=0.0,
|
||||
z_max=volume["height"])
|
||||
@@ -393,7 +393,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
self._printAfterSelect = printAfterSelect
|
||||
self._posAfterSelect = pos
|
||||
self._comm.selectFile("/" + path if sd and not settings().getBoolean(["feature", "sdRelativePath"]) else path, sd)
|
||||
self._comm.selectFile("/" + path if sd else path, sd)
|
||||
self._setProgressData(completion=0)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
@@ -405,6 +405,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._setProgressData(completion=0)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def get_file_position(self):
|
||||
if self._comm is None:
|
||||
return None
|
||||
|
||||
if self._selectedFile is None:
|
||||
return None
|
||||
|
||||
return self._comm.getFilePosition()
|
||||
|
||||
def start_print(self, pos=None):
|
||||
"""
|
||||
Starts the currently loaded print job.
|
||||
@@ -478,12 +487,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
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"])
|
||||
payload = {
|
||||
"file": self._selectedFile["filename"],
|
||||
"origin": FileDestinations.LOCAL
|
||||
}
|
||||
if self._selectedFile["sd"]:
|
||||
payload["origin"] = FileDestinations.SDCARD
|
||||
payload = self._payload_for_print_job_event()
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
def get_state_string(self, state=None):
|
||||
@@ -754,7 +758,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
"""
|
||||
|
||||
if progress is None or printTime is None or cleanedPrintTime is None:
|
||||
return None
|
||||
return None, None
|
||||
|
||||
dumbTotalPrintTime = printTime / progress
|
||||
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
|
||||
@@ -956,6 +960,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
def on_comm_temperature_update(self, temp, bedTemp):
|
||||
self._addTemperatureData(copy.deepcopy(temp), copy.deepcopy(bedTemp))
|
||||
|
||||
def on_comm_position_update(self, position, reason=None):
|
||||
payload = dict(reason=reason)
|
||||
payload.update(position)
|
||||
eventManager().fire(Events.POSITION_UPDATE, payload)
|
||||
|
||||
def on_comm_state_change(self, state):
|
||||
"""
|
||||
Callback method for the comm object, called if the connection state changes.
|
||||
@@ -1063,7 +1072,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
def on_comm_print_job_cancelled(self):
|
||||
payload = self._payload_for_print_job_event()
|
||||
payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None)
|
||||
if payload:
|
||||
eventManager().fire(Events.PRINT_CANCELLED, payload)
|
||||
self.script("afterPrintCancelled",
|
||||
@@ -1071,7 +1080,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
must_be_set=False)
|
||||
|
||||
def on_comm_print_job_paused(self):
|
||||
payload = self._payload_for_print_job_event()
|
||||
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None)
|
||||
if payload:
|
||||
eventManager().fire(Events.PRINT_PAUSED, payload)
|
||||
self.script("afterPrintPaused",
|
||||
@@ -1117,7 +1126,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
except:
|
||||
self._logger.exception("Error while trying to persist print recovery data")
|
||||
|
||||
def _payload_for_print_job_event(self, location=None, print_job_file=None):
|
||||
def _payload_for_print_job_event(self, location=None, print_job_file=None, position=None):
|
||||
if print_job_file is None:
|
||||
selected_file = self._selectedFile
|
||||
if not selected_file:
|
||||
@@ -1142,13 +1151,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
_, name = self._fileManager.split_path(FileDestinations.LOCAL, path)
|
||||
origin = FileDestinations.LOCAL
|
||||
|
||||
return dict(name=name,
|
||||
path=path,
|
||||
origin=origin,
|
||||
result= dict(name=name,
|
||||
path=path,
|
||||
origin=origin,
|
||||
|
||||
# TODO deprecated, remove in 1.4.0
|
||||
file=full_path,
|
||||
filename=name)
|
||||
# TODO deprecated, remove in 1.4.0
|
||||
file=full_path,
|
||||
filename=name)
|
||||
|
||||
if position is not None:
|
||||
result["position"] = position
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class StateMonitor(object):
|
||||
|
||||
@@ -33,6 +33,7 @@ app = Flask("octoprint")
|
||||
assets = None
|
||||
babel = None
|
||||
debug = False
|
||||
safe_mode = False
|
||||
|
||||
printer = None
|
||||
printerProfileManager = None
|
||||
@@ -112,12 +113,13 @@ def load_user(id):
|
||||
|
||||
|
||||
class Server(object):
|
||||
def __init__(self, settings=None, plugin_manager=None, host="0.0.0.0", port=5000, debug=False, allow_root=False, octoprint_daemon=None):
|
||||
def __init__(self, settings=None, plugin_manager=None, host="0.0.0.0", port=5000, debug=False, safe_mode=False, allow_root=False, octoprint_daemon=None):
|
||||
self._settings = settings
|
||||
self._plugin_manager = plugin_manager
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._debug = debug
|
||||
self._safe_mode = safe_mode
|
||||
self._allow_root = allow_root
|
||||
self._octoprint_daemon = octoprint_daemon
|
||||
self._server = None
|
||||
@@ -155,11 +157,13 @@ class Server(object):
|
||||
global pluginLifecycleManager
|
||||
global preemptiveCache
|
||||
global debug
|
||||
global safe_mode
|
||||
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.web import Application, RequestHandler
|
||||
|
||||
debug = self._debug
|
||||
safe_mode = self._safe_mode
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
pluginManager = self._plugin_manager
|
||||
@@ -245,7 +249,14 @@ class Server(object):
|
||||
return props
|
||||
|
||||
def settings_plugin_inject_factory(name, implementation):
|
||||
"""Factory for additional injections depending on plugin type"""
|
||||
"""Factory for additional injections/initializations depending on plugin type"""
|
||||
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
|
||||
return
|
||||
|
||||
default_settings_overlay = dict(plugins=dict())
|
||||
default_settings_overlay["plugins"][name] = implementation.get_settings_defaults()
|
||||
self._settings.add_overlay(default_settings_overlay, at_end=True)
|
||||
|
||||
plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin(name, implementation)
|
||||
if plugin_settings is None:
|
||||
return
|
||||
@@ -272,7 +283,8 @@ class Server(object):
|
||||
|
||||
implementation.on_settings_initialized()
|
||||
|
||||
pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory, settings_plugin_inject_factory]
|
||||
pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory,
|
||||
settings_plugin_inject_factory]
|
||||
pluginManager.initialize_implementations()
|
||||
|
||||
settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin)
|
||||
@@ -487,6 +499,11 @@ class Server(object):
|
||||
def on_after_startup():
|
||||
self._logger.info("Listening on http://%s:%d" % (self._host, self._port))
|
||||
|
||||
if safe_mode and self._settings.getBoolean(["server", "startOnceInSafeMode"]):
|
||||
self._logger.info("Server started successfully in safe mode as requested from config, removing flag")
|
||||
self._settings.setBoolean(["server", "startOnceInSafeMode"], False)
|
||||
self._settings.save()
|
||||
|
||||
# now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for
|
||||
# which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons
|
||||
# or service xmls or the like). While they are working though the ioloop would block. Therefore we'll
|
||||
@@ -567,6 +584,9 @@ class Server(object):
|
||||
if "l10n" in request.values:
|
||||
return Locale.negotiate([request.values["l10n"]], LANGUAGES)
|
||||
|
||||
if "X-Locale" in request.headers:
|
||||
return Locale.negotiate([request.headers["X-Locale"]], LANGUAGES)
|
||||
|
||||
if hasattr(g, "identity") and g.identity and userManager.enabled:
|
||||
userid = g.identity.id
|
||||
try:
|
||||
|
||||
@@ -31,6 +31,7 @@ def _etag(lm=None):
|
||||
hash = hashlib.sha1()
|
||||
hash.update(str(lm))
|
||||
hash.update(repr(printerProfileManager.get_default()))
|
||||
hash.update(repr(printerProfileManager.get_current()))
|
||||
return hash.hexdigest()
|
||||
|
||||
|
||||
@@ -128,17 +129,17 @@ def printerProfilesUpdate(identifier):
|
||||
profile = printerProfileManager.get_default()
|
||||
|
||||
new_profile = json_data["profile"]
|
||||
new_profile = dict_merge(profile, new_profile)
|
||||
merged_profile = dict_merge(profile, new_profile)
|
||||
|
||||
make_default = False
|
||||
if "default" in new_profile:
|
||||
if "default" in merged_profile:
|
||||
make_default = True
|
||||
del new_profile["default"]
|
||||
|
||||
new_profile["id"] = identifier
|
||||
merged_profile["id"] = identifier
|
||||
|
||||
try:
|
||||
saved_profile = printerProfileManager.save(new_profile, allow_overwrite=True, make_default=make_default)
|
||||
saved_profile = printerProfileManager.save(merged_profile, allow_overwrite=True, make_default=make_default)
|
||||
except InvalidProfileError:
|
||||
return make_response("Profile is invalid", 400)
|
||||
except CouldNotOverwriteError:
|
||||
|
||||
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import logging
|
||||
|
||||
from flask import request, jsonify, make_response
|
||||
from flask.ext.login import current_user
|
||||
from werkzeug.exceptions import BadRequest
|
||||
|
||||
from octoprint.events import eventManager, Events
|
||||
@@ -30,11 +31,41 @@ def _etag(lm=None):
|
||||
lm = _lastmodified()
|
||||
|
||||
connection_options = printer.__class__.get_connection_options()
|
||||
plugins = sorted(octoprint.plugin.plugin_manager().enabled_plugins)
|
||||
plugin_settings = _get_plugin_settings()
|
||||
|
||||
from collections import OrderedDict
|
||||
sorted_plugin_settings = OrderedDict()
|
||||
for key in sorted(plugin_settings.keys()):
|
||||
sorted_plugin_settings[key] = plugin_settings.get(key, dict())
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous():
|
||||
roles = sorted(current_user.roles)
|
||||
else:
|
||||
roles = []
|
||||
|
||||
import hashlib
|
||||
hash = hashlib.sha1()
|
||||
|
||||
# last modified timestamp
|
||||
hash.update(str(lm))
|
||||
|
||||
# effective config from config.yaml + overlays
|
||||
hash.update(repr(settings().effective))
|
||||
|
||||
# might duplicate settings().effective, but plugins might also inject additional keys into the settings
|
||||
# output that are not stored in config.yaml
|
||||
hash.update(repr(sorted_plugin_settings))
|
||||
|
||||
# connection options are also part of the settings
|
||||
hash.update(repr(connection_options))
|
||||
|
||||
# if the list of plugins changes, the settings structure changes too
|
||||
hash.update(repr(plugins))
|
||||
|
||||
# and likewise if the role of the user changes
|
||||
hash.update(repr(roles))
|
||||
|
||||
return hash.hexdigest()
|
||||
|
||||
@api.route("/settings", methods=["GET"])
|
||||
@@ -42,8 +73,6 @@ def _etag(lm=None):
|
||||
lastmodified_factory=_lastmodified,
|
||||
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
|
||||
def getSettings():
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
s = settings()
|
||||
|
||||
connectionOptions = printer.__class__.get_connection_options()
|
||||
@@ -95,7 +124,8 @@ def getSettings():
|
||||
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
|
||||
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
|
||||
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"]),
|
||||
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"])
|
||||
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
|
||||
"firmwareDetection": s.getBoolean(["feature", "firmwareDetection"])
|
||||
},
|
||||
"serial": {
|
||||
"port": connectionOptions["portPreference"],
|
||||
@@ -170,32 +200,45 @@ def getSettings():
|
||||
for name in gcode_scripts:
|
||||
data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True)
|
||||
|
||||
plugin_settings = _get_plugin_settings()
|
||||
if len(plugin_settings):
|
||||
data["plugins"] = plugin_settings
|
||||
|
||||
return jsonify(data)
|
||||
|
||||
|
||||
def _get_plugin_settings():
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
data = dict()
|
||||
|
||||
def process_plugin_result(name, result):
|
||||
if result:
|
||||
try:
|
||||
jsonify(test=result)
|
||||
except:
|
||||
logger.exception("Error while jsonifying settings from plugin {}, please contact the plugin author about this".format(name))
|
||||
|
||||
if not "plugins" in data:
|
||||
data["plugins"] = dict()
|
||||
if "__enabled" in result:
|
||||
del result["__enabled"]
|
||||
data["plugins"][name] = result
|
||||
raise
|
||||
else:
|
||||
if "__enabled" in result:
|
||||
del result["__enabled"]
|
||||
data[name] = result
|
||||
|
||||
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
|
||||
try:
|
||||
result = plugin.on_settings_load()
|
||||
process_plugin_result(plugin._identifier, result)
|
||||
except TypeError:
|
||||
logger.warn("Could not load settings for plugin {name} ({version}) since it called super(...)".format(name=plugin._plugin_name, version=plugin._plugin_version))
|
||||
logger.warn("Could not load settings for plugin {name} ({version}) since it called super(...)".format(name=plugin._plugin_name,
|
||||
version=plugin._plugin_version))
|
||||
logger.warn("in a way which has issues due to OctoPrint's dynamic reloading after plugin operations.")
|
||||
logger.warn("Please contact the plugin's author and ask to update the plugin to use a direct call like")
|
||||
logger.warn("octoprint.plugin.SettingsPlugin.on_settings_load(self) instead.")
|
||||
except:
|
||||
logger.exception("Could not load settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name))
|
||||
logger.exception("Could not load settings for plugin {name} ({version})".format(version=plugin._plugin_version,
|
||||
name=plugin._plugin_name))
|
||||
|
||||
return jsonify(data)
|
||||
return data
|
||||
|
||||
|
||||
@api.route("/settings", methods=["POST"])
|
||||
@@ -265,6 +308,7 @@ def _saveSettings(data):
|
||||
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
|
||||
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
|
||||
if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"])
|
||||
if "firmwareDetection" in data["feature"]: s.setBoolean(["feature", "firmwareDetection"], data["feature"]["firmwareDetection"])
|
||||
|
||||
if "serial" in data.keys():
|
||||
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
@@ -348,9 +392,10 @@ def _saveSettings(data):
|
||||
except:
|
||||
logger.exception("Could not save settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name))
|
||||
|
||||
if s.save():
|
||||
payload = dict(
|
||||
config_hash=s.config_hash,
|
||||
effective_hash=s.effective_hash
|
||||
)
|
||||
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
|
||||
s.save()
|
||||
|
||||
payload = dict(
|
||||
config_hash=s.config_hash,
|
||||
effective_hash=s.effective_hash
|
||||
)
|
||||
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
|
||||
@@ -129,19 +129,19 @@ def _get_core_command_specs():
|
||||
commands = collections.OrderedDict(
|
||||
shutdown=dict(
|
||||
command=s().get(["server", "commands", "systemShutdownCommand"]),
|
||||
name=gettext("Shutdown"),
|
||||
name=gettext("Shutdown system"),
|
||||
confirm=gettext("You are about to shutdown the system.")),
|
||||
reboot=dict(
|
||||
command=s().get(["server", "commands", "systemRestartCommand"]),
|
||||
name=gettext("Reboot"),
|
||||
name=gettext("Reboot system"),
|
||||
confirm=gettext("You are about to reboot the system.")),
|
||||
restart=dict(
|
||||
command=s().get(["server", "commands", "serverRestartCommand"]),
|
||||
name="Restart OctoPrint",
|
||||
confirm="You are about to restart the OctoPrint server.")
|
||||
name=gettext("Restart OctoPrint"),
|
||||
confirm=gettext("You are about to restart the OctoPrint server."))
|
||||
)
|
||||
|
||||
available_commands = dict()
|
||||
available_commands = collections.OrderedDict()
|
||||
for action, spec in commands.items():
|
||||
if not spec["command"]:
|
||||
continue
|
||||
|
||||
@@ -30,6 +30,21 @@ _timelapse_cache_unrendered = []
|
||||
_timelapse_cache_unrendered_lastmodified = None
|
||||
_timelapse_cache_mutex = threading.RLock()
|
||||
|
||||
def _config_for_timelapse(timelapse):
|
||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||
return dict(type="zchange",
|
||||
postRoll=timelapse.post_roll,
|
||||
fps=timelapse.fps,
|
||||
retractionZHop=timelapse.retraction_zhop)
|
||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||
return dict(type="timed",
|
||||
postRoll=timelapse.post_roll,
|
||||
fps=timelapse.fps,
|
||||
interval=timelapse.interval,
|
||||
capturePostRoll=timelapse.capture_post_roll)
|
||||
else:
|
||||
return dict(type="off")
|
||||
|
||||
def _lastmodified(unrendered):
|
||||
lm_finished = octoprint.timelapse.last_modified_finished()
|
||||
if unrendered:
|
||||
@@ -44,9 +59,13 @@ def _etag(unrendered, lm=None):
|
||||
if lm is None:
|
||||
lm = _lastmodified(unrendered)
|
||||
|
||||
timelapse = octoprint.timelapse.current
|
||||
config = _config_for_timelapse(timelapse)
|
||||
|
||||
import hashlib
|
||||
hash = hashlib.sha1()
|
||||
hash.update(str(lm))
|
||||
hash.update(repr(config))
|
||||
|
||||
return hash.hexdigest()
|
||||
|
||||
@@ -56,19 +75,7 @@ def _etag(unrendered, lm=None):
|
||||
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
|
||||
def getTimelapseData():
|
||||
timelapse = octoprint.timelapse.current
|
||||
|
||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||
config = dict(type="zchange",
|
||||
postRoll=timelapse.post_roll,
|
||||
fps=timelapse.fps,
|
||||
retractionZHop=timelapse.retraction_zhop)
|
||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||
config = dict(type="timed",
|
||||
postRoll=timelapse.post_roll,
|
||||
fps=timelapse.fps,
|
||||
interval=timelapse.interval)
|
||||
else:
|
||||
config = dict(type="off")
|
||||
config = _config_for_timelapse(timelapse)
|
||||
|
||||
force = request.values.get("force", "false") in valid_boolean_trues
|
||||
unrendered = request.values.get("unrendered", "false") in valid_boolean_trues
|
||||
@@ -204,21 +211,31 @@ def setTimelapseConfig():
|
||||
else:
|
||||
return make_response("Invalid value for interval: %d" % interval)
|
||||
|
||||
if "retractionZHop" in request.values:
|
||||
if "capturePostRoll" in data:
|
||||
config["options"]["capturePostRoll"] = True
|
||||
try:
|
||||
capturePostRoll = bool(data["capturePostRoll"])
|
||||
except ValueError:
|
||||
return make_response("Invalid value for capturePostRoll: %r" % data["capturePostRoll"])
|
||||
else:
|
||||
config["options"]["capturePostRoll"] = capturePostRoll
|
||||
|
||||
if "retractionZHop" in data:
|
||||
config["options"] = {
|
||||
"retractionZHop": 0
|
||||
}
|
||||
|
||||
try:
|
||||
retractionZHop = float(request.values["retractionZHop"])
|
||||
retractionZHop = float(data["retractionZHop"])
|
||||
except ValueError:
|
||||
return make_response("Invalid value for retraction Z-Hop: %r" % request.values["retractionZHop"])
|
||||
return make_response("Invalid value for retraction Z-Hop: %r" % data["retractionZHop"])
|
||||
else:
|
||||
if retractionZHop > 0:
|
||||
config["options"]["retractionZHop"] = retractionZHop
|
||||
else:
|
||||
return make_response("Invalid value for retraction Z-Hop: %d" % retractionZHop)
|
||||
|
||||
|
||||
if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues:
|
||||
octoprint.timelapse.configure_timelapse(config, True)
|
||||
else:
|
||||
|
||||
@@ -236,6 +236,15 @@ class ReverseProxiedEnvironment(object):
|
||||
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
|
||||
return map(to_wsgi_format, values)
|
||||
|
||||
@staticmethod
|
||||
def valid_ip(address):
|
||||
import netaddr
|
||||
try:
|
||||
netaddr.IPAddress(address)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
def __init__(self,
|
||||
header_prefix=None,
|
||||
header_scheme=None,
|
||||
@@ -290,11 +299,43 @@ class ReverseProxiedEnvironment(object):
|
||||
if host is None:
|
||||
return None, None
|
||||
|
||||
default_port = "443" if scheme == "https" else "80"
|
||||
host = host.strip()
|
||||
|
||||
if ":" in host:
|
||||
server, port = host.split(":", 1)
|
||||
# we might have an ipv6 address here, or a port, or both
|
||||
|
||||
if host[0] == "[":
|
||||
# that looks like an ipv6 address with port, e.g. [fec1::1]:80
|
||||
address_end = host.find("]")
|
||||
if address_end == -1:
|
||||
# no ], that looks like a seriously broken address
|
||||
return None, None
|
||||
|
||||
# extract server ip, skip enclosing [ and ]
|
||||
server = host[1:address_end]
|
||||
tail = host[address_end + 1:]
|
||||
|
||||
# now check if there's also a port
|
||||
if len(tail) and tail[0] == ":":
|
||||
# port included as well
|
||||
port = tail[1:]
|
||||
else:
|
||||
# no port, use default one
|
||||
port = default_port
|
||||
|
||||
elif self.__class__.valid_ip(host):
|
||||
# ipv6 address without port
|
||||
server = host
|
||||
port = default_port
|
||||
|
||||
else:
|
||||
# ipv4 address with port
|
||||
server, port = host.rsplit(":", 1)
|
||||
|
||||
else:
|
||||
server = host
|
||||
port = "443" if scheme == "https" else "80"
|
||||
port = default_port
|
||||
|
||||
return server, port
|
||||
|
||||
@@ -352,7 +393,12 @@ class ReverseProxiedEnvironment(object):
|
||||
# default port for scheme, can be skipped
|
||||
environ["HTTP_HOST"] = environ["SERVER_NAME"]
|
||||
else:
|
||||
environ["HTTP_HOST"] = environ["SERVER_NAME"] + ":" + environ["SERVER_PORT"]
|
||||
server_name_component = environ["SERVER_NAME"]
|
||||
if ":" in server_name_component and self.__class__.valid_ip(server_name_component):
|
||||
# this is an ipv6 address, we need to wrap that in [ and ] before appending the port
|
||||
server_name_component = "[" + server_name_component + "]"
|
||||
|
||||
environ["HTTP_HOST"] = server_name_component + ":" + environ["SERVER_PORT"]
|
||||
|
||||
# call wrapped app with rewritten environment
|
||||
return environ
|
||||
|
||||
@@ -77,7 +77,9 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
|
||||
display_version=octoprint.server.DISPLAY_VERSION,
|
||||
branch=octoprint.server.BRANCH,
|
||||
plugin_hash=plugin_hash.hexdigest(),
|
||||
config_hash=config_hash
|
||||
config_hash=config_hash,
|
||||
debug=octoprint.server.debug,
|
||||
safe_mode=octoprint.server.safe_mode
|
||||
))
|
||||
|
||||
self._printer.register_callback(self)
|
||||
|
||||
@@ -27,7 +27,7 @@ from . import util
|
||||
import logging
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_templates = None
|
||||
_templates = dict()
|
||||
_plugin_names = None
|
||||
_plugin_vars = None
|
||||
|
||||
@@ -159,19 +159,21 @@ def index():
|
||||
|
||||
preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"])
|
||||
|
||||
locale = g.locale.language if g.locale else "en"
|
||||
|
||||
# helper to check if wizards are active
|
||||
def wizard_active(templates):
|
||||
return templates is not None and bool(templates["wizard"]["order"])
|
||||
|
||||
# we force a refresh if the client forces one or if we have wizards cached
|
||||
force_refresh = util.flask.cache_check_headers() or "_refresh" in request.values or wizard_active(_templates)
|
||||
force_refresh = util.flask.cache_check_headers() or "_refresh" in request.values or wizard_active(_templates.get(locale))
|
||||
|
||||
# if we need to refresh our template cache or it's not yet set, process it
|
||||
if force_refresh or _templates is None or _plugin_names is None or _plugin_vars is None:
|
||||
_templates, _plugin_names, _plugin_vars = _process_templates()
|
||||
if force_refresh or _templates.get(locale) is None or _plugin_names is None or _plugin_vars is None:
|
||||
_templates[locale], _plugin_names, _plugin_vars = _process_templates()
|
||||
|
||||
now = datetime.datetime.utcnow()
|
||||
render_kwargs = _get_render_kwargs(_templates, _plugin_names, _plugin_vars, now)
|
||||
render_kwargs = _get_render_kwargs(_templates[locale], _plugin_names, _plugin_vars, now)
|
||||
|
||||
def get_preemptively_cached_view(key, view, data=None, additional_request_data=None, additional_unless=None):
|
||||
if (data is None and additional_request_data is None) or g.locale is None:
|
||||
@@ -304,7 +306,7 @@ def index():
|
||||
return view(now, request, render_kwargs)
|
||||
|
||||
def default_view():
|
||||
wizard = wizard_active(_templates)
|
||||
wizard = wizard_active(_templates[locale])
|
||||
enable_accesscontrol = userManager.enabled
|
||||
accesscontrol_active = enable_accesscontrol and userManager.hasBeenCustomized()
|
||||
render_kwargs.update(dict(
|
||||
|
||||
+98
-28
@@ -103,7 +103,7 @@ default_settings = {
|
||||
"maxWritePasses": 5,
|
||||
"additionalPorts": [],
|
||||
"additionalBaudrates": [],
|
||||
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226"],
|
||||
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226", "M600"],
|
||||
"checksumRequiringCommands": ["M110"],
|
||||
"helloCommand": "M110 N0",
|
||||
"disconnectOnErrors": True,
|
||||
@@ -118,6 +118,7 @@ default_settings = {
|
||||
"host": "0.0.0.0",
|
||||
"port": 5000,
|
||||
"firstRun": True,
|
||||
"startOnceInSafeMode": False,
|
||||
"seenWizards": {},
|
||||
"secretKey": None,
|
||||
"reverseProxy": {
|
||||
@@ -166,7 +167,8 @@ default_settings = {
|
||||
"type": "off",
|
||||
"options": {},
|
||||
"postRoll": 0,
|
||||
"fps": 25
|
||||
"fps": 25,
|
||||
"capturePostRoll": True
|
||||
},
|
||||
"cleanTmpAfterDays": 7
|
||||
},
|
||||
@@ -197,7 +199,8 @@ default_settings = {
|
||||
"ignoreIdenticalResends": False,
|
||||
"identicalResendsCountdown": 7,
|
||||
"supportFAsCommand": False,
|
||||
"modelSizeDetection": True
|
||||
"modelSizeDetection": True,
|
||||
"firmwareDetection": True
|
||||
},
|
||||
"folder": {
|
||||
"uploads": None,
|
||||
@@ -332,12 +335,6 @@ default_settings = {
|
||||
"numExtruders": 1,
|
||||
"includeCurrentToolInTemps": True,
|
||||
"includeFilenameInOpened": True,
|
||||
"movementSpeed": {
|
||||
"x": 6000,
|
||||
"y": 6000,
|
||||
"z": 200,
|
||||
"e": 300
|
||||
},
|
||||
"hasBed": True,
|
||||
"repetierStyleTargetTemperature": False,
|
||||
"repetierStyleResends": False,
|
||||
@@ -354,7 +351,8 @@ default_settings = {
|
||||
"supportM112": True,
|
||||
"echoOnM117": True,
|
||||
"brokenM29": True,
|
||||
"supportF": False
|
||||
"supportF": False,
|
||||
"firmwareName": "Virtual Marlin 1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -835,12 +833,17 @@ class Settings(object):
|
||||
self._migrate_config(config)
|
||||
return config
|
||||
|
||||
def add_overlay(self, overlay):
|
||||
self._map.maps.insert(1, overlay)
|
||||
def add_overlay(self, overlay, at_end=False):
|
||||
if at_end:
|
||||
pos = len(self._map.maps) - 1
|
||||
self._map.maps.insert(pos, overlay)
|
||||
else:
|
||||
self._map.maps.insert(1, overlay)
|
||||
|
||||
def _migrate_config(self, config=None):
|
||||
def _migrate_config(self, config=None, persist=False):
|
||||
if config is None:
|
||||
config = self._config
|
||||
persist = True
|
||||
|
||||
dirty = False
|
||||
|
||||
@@ -848,12 +851,14 @@ class Settings(object):
|
||||
self._migrate_event_config,
|
||||
self._migrate_reverse_proxy_config,
|
||||
self._migrate_printer_parameters,
|
||||
self._migrate_gcode_scripts
|
||||
self._migrate_gcode_scripts,
|
||||
self._migrate_core_system_commands
|
||||
)
|
||||
|
||||
for migrate in migrators:
|
||||
dirty = migrate(config) or dirty
|
||||
if dirty:
|
||||
|
||||
if dirty and persist:
|
||||
self.save(force=True)
|
||||
|
||||
def _migrate_gcode_scripts(self, config):
|
||||
@@ -1062,6 +1067,67 @@ class Settings(object):
|
||||
else:
|
||||
return False
|
||||
|
||||
def _migrate_core_system_commands(self, config):
|
||||
"""
|
||||
Migrates system commands for restart, reboot and shutdown as defined on OctoPi or
|
||||
according to the official setup guide to new core system commands to remove
|
||||
duplication.
|
||||
|
||||
If server commands for action is not yet set, migrates command. Otherwise only
|
||||
deletes definition from custom system commands.
|
||||
"""
|
||||
changed = False
|
||||
|
||||
migration_map = dict(shutdown="systemShutdownCommand",
|
||||
reboot="systemRestartCommand",
|
||||
restart="serverRestartCommand")
|
||||
|
||||
if "system" in config and "actions" in config["system"]:
|
||||
actions = config["system"]["actions"]
|
||||
to_delete = []
|
||||
for index, spec in enumerate(actions):
|
||||
action = spec.get("action")
|
||||
command = spec.get("command")
|
||||
if action is None or command is None:
|
||||
continue
|
||||
|
||||
migrate_to = migration_map.get(action)
|
||||
if migrate_to is not None:
|
||||
if not "server" in config or not "commands" in config["server"] or not migrate_to in config["server"]["commands"]:
|
||||
if not "server" in config:
|
||||
config["server"] = dict()
|
||||
if not "commands" in config["server"]:
|
||||
config["server"]["commands"] = dict()
|
||||
config["server"]["commands"][migrate_to] = command
|
||||
self._logger.info("Migrated {} action to server.commands.{}".format(action, migrate_to))
|
||||
|
||||
to_delete.append(index)
|
||||
self._logger.info("Deleting {} action from configured system commands, superseeded by server.commands.{}".format(action, migrate_to))
|
||||
|
||||
for index in reversed(to_delete):
|
||||
actions.pop(index)
|
||||
changed = True
|
||||
|
||||
if changed:
|
||||
# let's make a backup of our current config, in case someone wants to roll back to an
|
||||
# earlier version and needs to recover the former system commands for that
|
||||
backup_path = self.backup("system_command_migration")
|
||||
self._logger.info("Made a copy of the current config at {} to allow recovery of manual system command configuration".format(backup_path))
|
||||
|
||||
return changed
|
||||
|
||||
def backup(self, suffix, path=None):
|
||||
import shutil
|
||||
|
||||
if path is None:
|
||||
path = os.path.dirname(self._configfile)
|
||||
basename = os.path.basename(self._configfile)
|
||||
name, ext = os.path.splitext(basename)
|
||||
|
||||
backup = os.path.join(path, "{}.{}{}".format(name, suffix, ext))
|
||||
shutil.copy(self._configfile, backup)
|
||||
return backup
|
||||
|
||||
def save(self, force=False):
|
||||
if not self._dirty and not force:
|
||||
return False
|
||||
@@ -1105,12 +1171,14 @@ class Settings(object):
|
||||
else:
|
||||
chain = self._map
|
||||
|
||||
if preprocessors is None:
|
||||
preprocessors = self._get_preprocessors
|
||||
|
||||
preprocessor = None
|
||||
if preprocessors is not None:
|
||||
try:
|
||||
preprocessor = self._get_by_path(path, preprocessors)
|
||||
except NoSuchSettingsPath:
|
||||
pass
|
||||
try:
|
||||
preprocessor = self._get_by_path(path, preprocessors)
|
||||
except NoSuchSettingsPath:
|
||||
pass
|
||||
|
||||
parent_path = path[:-1]
|
||||
last = path[-1]
|
||||
@@ -1310,15 +1378,17 @@ class Settings(object):
|
||||
else:
|
||||
chain = self._map
|
||||
|
||||
preprocessor = None
|
||||
if preprocessors is not None:
|
||||
try:
|
||||
preprocessor = self._get_by_path(path, preprocessors)
|
||||
except NoSuchSettingsPath:
|
||||
pass
|
||||
if preprocessors is None:
|
||||
preprocessors = self._set_preprocessors
|
||||
|
||||
if callable(preprocessor):
|
||||
value = preprocessor(value)
|
||||
preprocessor = None
|
||||
try:
|
||||
preprocessor = self._get_by_path(path, preprocessors)
|
||||
except NoSuchSettingsPath:
|
||||
pass
|
||||
|
||||
if callable(preprocessor):
|
||||
value = preprocessor(value)
|
||||
|
||||
try:
|
||||
current = chain.get_by_path(path)
|
||||
|
||||
@@ -46,7 +46,8 @@
|
||||
|
||||
OctoPrint.options = {
|
||||
"baseurl": undefined,
|
||||
"apikey": undefined
|
||||
"apikey": undefined,
|
||||
"locale": undefined
|
||||
};
|
||||
|
||||
OctoPrint.plugins = {};
|
||||
@@ -65,6 +66,10 @@
|
||||
var headers = $.extend({}, additional);
|
||||
headers["X-Api-Key"] = OctoPrint.options.apikey;
|
||||
|
||||
if (OctoPrint.options.locale !== undefined) {
|
||||
headers["X-Locale"] = OctoPrint.options.locale;
|
||||
}
|
||||
|
||||
return headers;
|
||||
};
|
||||
|
||||
@@ -163,6 +168,7 @@
|
||||
}
|
||||
|
||||
filename = filename || fileData.name;
|
||||
var filesize = fileData.size;
|
||||
|
||||
var form = new FormData();
|
||||
form.append("file", fileData, filename);
|
||||
@@ -216,7 +222,12 @@
|
||||
|
||||
var headers = OctoPrint.getRequestHeaders();
|
||||
|
||||
request.open("POST", OctoPrint.getBaseUrl() + url);
|
||||
var urlToCall = url;
|
||||
if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) {
|
||||
urlToCall = OctoPrint.getBaseUrl() + url;
|
||||
}
|
||||
|
||||
request.open("POST", urlToCall);
|
||||
_.each(headers, function(value, key) {
|
||||
request.setRequestHeader(key, value);
|
||||
});
|
||||
|
||||
@@ -13,6 +13,8 @@ function DataUpdater(allViewModels) {
|
||||
self._lastProcessingTimes = [];
|
||||
self._lastProcessingTimesSize = 20;
|
||||
|
||||
self._safeModePopup = undefined;
|
||||
|
||||
self.increaseThrottle = function() {
|
||||
self.setThrottle(self._throttleFactor + 1);
|
||||
};
|
||||
@@ -115,16 +117,25 @@ function DataUpdater(allViewModels) {
|
||||
var oldConfigHash = self._configHash;
|
||||
self._configHash = data["config_hash"];
|
||||
|
||||
// process safe mode
|
||||
if (self._safeModePopup) self._safeModePopup.remove();
|
||||
if (data["safe_mode"]) {
|
||||
// safe mode is active, let's inform the user
|
||||
log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled.");
|
||||
|
||||
self._safeModePopup = new PNotify({
|
||||
title: gettext("Safe mode is active"),
|
||||
text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
|
||||
// if the offline overlay is still showing, now's a good time to
|
||||
// hide it, plus reload the camera feed if it's currently displayed
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
hideOfflineOverlay();
|
||||
callViewModels(self.allViewModels, "onServerReconnect");
|
||||
callViewModels(self.allViewModels, "onDataUpdaterReconnect");
|
||||
|
||||
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
|
||||
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
|
||||
}
|
||||
} else {
|
||||
callViewModels(self.allViewModels, "onServerConnect");
|
||||
}
|
||||
|
||||
@@ -777,9 +777,14 @@ function getOnlyChangedData(data, oldData) {
|
||||
|
||||
var retval = {};
|
||||
_.forOwn(root, function(value, key) {
|
||||
var oldValue = oldRoot[key];
|
||||
var oldValue = undefined;
|
||||
if (oldRoot != undefined && oldRoot.hasOwnProperty(key)) {
|
||||
oldValue = oldRoot[key];
|
||||
}
|
||||
if (_.isPlainObject(value)) {
|
||||
if (hasDataChanged(value, oldValue)) {
|
||||
if (oldValue == undefined) {
|
||||
retval[key] = value;
|
||||
} else if (hasDataChanged(value, oldValue)) {
|
||||
retval[key] = f(value, oldValue);
|
||||
}
|
||||
} else {
|
||||
@@ -832,17 +837,21 @@ function callViewModelsIf(allViewModels, method, condition, callback) {
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty(method) && condition(viewModel, method)) {
|
||||
if (callback == undefined) {
|
||||
if (parameters != undefined) {
|
||||
// call the method with the provided parameters
|
||||
viewModel[method].apply(viewModel, parameters);
|
||||
try {
|
||||
if (callback == undefined) {
|
||||
if (parameters != undefined) {
|
||||
// call the method with the provided parameters
|
||||
viewModel[method].apply(viewModel, parameters);
|
||||
} else {
|
||||
// call the method without parameters
|
||||
viewModel[method]();
|
||||
}
|
||||
} else {
|
||||
// call the method without parameters
|
||||
viewModel[method]();
|
||||
// provide the method to the callback
|
||||
callback(viewModel[method], viewModel);
|
||||
}
|
||||
} else {
|
||||
// provide the method to the callback
|
||||
callback(viewModel[method], viewModel);
|
||||
} catch (exc) {
|
||||
log.error("Error calling", method, "on view model", viewModel.constructor.name, ":", (exc.stack || exc));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -861,3 +870,16 @@ var sizeObservable = function(observable) {
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
var getQueryParameterByName = function(name, url) {
|
||||
// from http://stackoverflow.com/a/901144/2028598
|
||||
if (!url) {
|
||||
url = window.location.href;
|
||||
}
|
||||
name = name.replace(/[\[\]]/g, "\\$&");
|
||||
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
|
||||
results = regex.exec(url);
|
||||
if (!results) return null;
|
||||
if (!results[2]) return '';
|
||||
return decodeURIComponent(results[2].replace(/\+/g, " "));
|
||||
};
|
||||
@@ -13,6 +13,11 @@ $(function() {
|
||||
OctoPrint.options.baseurl = BASEURL;
|
||||
OctoPrint.options.apikey = UI_API_KEY;
|
||||
|
||||
var l10n = getQueryParameterByName("l10n");
|
||||
if (l10n) {
|
||||
OctoPrint.options.locale = l10n;
|
||||
}
|
||||
|
||||
OctoPrint.socket.onMessage("connected", function(data) {
|
||||
var payload = data.data;
|
||||
OctoPrint.options.apikey = payload.apikey;
|
||||
@@ -31,7 +36,9 @@ $(function() {
|
||||
OctoPrint.coreui = (function() {
|
||||
var exports = {
|
||||
browserTabVisibility: undefined,
|
||||
selectedTab: undefined
|
||||
selectedTab: undefined,
|
||||
settingsOpen: false,
|
||||
wizardOpen: false
|
||||
};
|
||||
|
||||
var browserVisibilityCallbacks = [];
|
||||
|
||||
@@ -91,6 +91,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onEventSettingsUpdated = function (payload) {
|
||||
// the webcam url might have changed, make sure we replace it now if the tab is focused
|
||||
self._enableWebcam();
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
@@ -378,9 +380,9 @@ $(function() {
|
||||
}
|
||||
var webcamImage = $("#webcam_image");
|
||||
var currentSrc = webcamImage.attr("src");
|
||||
if (currentSrc === undefined || currentSrc.trim() == "") {
|
||||
var newSrc = CONFIG_WEBCAM_STREAM;
|
||||
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
|
||||
var newSrc = self.settings.webcam_streamUrl();
|
||||
if (currentSrc != newSrc) {
|
||||
if (newSrc.lastIndexOf("?") > -1) {
|
||||
newSrc += "&";
|
||||
} else {
|
||||
newSrc += "?";
|
||||
|
||||
@@ -402,13 +402,10 @@ $(function() {
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
OctoPrint.files.select(file.origin, file.path)
|
||||
.done(function() {
|
||||
var withinPrintDimensions = self.evaluatePrintDimensions(file, true);
|
||||
if (withinPrintDimensions && printAfterLoad) {
|
||||
OctoPrint.job.start();
|
||||
}
|
||||
});
|
||||
var withinPrintDimensions = self.evaluatePrintDimensions(file, true);
|
||||
var print = printAfterLoad && withinPrintDimensions;
|
||||
|
||||
OctoPrint.files.select(file.origin, file.path, print);
|
||||
};
|
||||
|
||||
self.removeFile = function(file, event) {
|
||||
@@ -444,20 +441,6 @@ $(function() {
|
||||
};
|
||||
|
||||
self._removeEntry = function(entry, event) {
|
||||
var index = self.listHelper.paginatedItems().indexOf(entry) + 1;
|
||||
if (index >= self.listHelper.paginatedItems().length) {
|
||||
index = index - 2;
|
||||
}
|
||||
if (index < 0) {
|
||||
index = 0;
|
||||
}
|
||||
|
||||
var focus = undefined;
|
||||
var fileToFocus = self.listHelper.paginatedItems()[index];
|
||||
if (fileToFocus) {
|
||||
focus = {location: fileToFocus.origin, path: fileToFocus.path};
|
||||
}
|
||||
|
||||
self.activeRemovals.push(entry.origin + ":" + entry.path);
|
||||
var finishActiveRemoval = function() {
|
||||
self.activeRemovals(_.filter(self.activeRemovals(), function(e) {
|
||||
@@ -488,10 +471,7 @@ $(function() {
|
||||
var deferred = $.Deferred();
|
||||
OctoPrint.files.delete(entry.origin, entry.path)
|
||||
.done(function() {
|
||||
self.requestData({
|
||||
focus: focus,
|
||||
switchToPath: (entry.parent ? entry.parent.path : "")
|
||||
})
|
||||
self.requestData()
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
})
|
||||
@@ -647,19 +627,31 @@ $(function() {
|
||||
}
|
||||
|
||||
// set print volume boundaries
|
||||
var boundaries = {
|
||||
minX : 0,
|
||||
maxX : volumeInfo.width(),
|
||||
minY : 0,
|
||||
maxY : volumeInfo.depth(),
|
||||
minZ : 0,
|
||||
maxZ : volumeInfo.height()
|
||||
};
|
||||
if (volumeInfo.origin() == "center") {
|
||||
boundaries["maxX"] = volumeInfo.width() / 2;
|
||||
boundaries["minX"] = -1 * boundaries["maxX"];
|
||||
boundaries["maxY"] = volumeInfo.depth() / 2;
|
||||
boundaries["minY"] = -1 * boundaries["maxY"];
|
||||
var boundaries;
|
||||
if (_.isPlainObject(volumeInfo.custom_box)) {
|
||||
boundaries = {
|
||||
minX : volumeInfo.custom_box.x_min(),
|
||||
minY : volumeInfo.custom_box.y_min(),
|
||||
minZ : volumeInfo.custom_box.z_min(),
|
||||
maxX : volumeInfo.custom_box.x_max(),
|
||||
maxY : volumeInfo.custom_box.y_max(),
|
||||
maxZ : volumeInfo.custom_box.z_max()
|
||||
}
|
||||
} else {
|
||||
boundaries = {
|
||||
minX : 0,
|
||||
maxX : volumeInfo.width(),
|
||||
minY : 0,
|
||||
maxY : volumeInfo.depth(),
|
||||
minZ : 0,
|
||||
maxZ : volumeInfo.height()
|
||||
};
|
||||
if (volumeInfo.origin() == "center") {
|
||||
boundaries["maxX"] = volumeInfo.width() / 2;
|
||||
boundaries["minX"] = -1 * boundaries["maxX"];
|
||||
boundaries["maxY"] = volumeInfo.depth() / 2;
|
||||
boundaries["minY"] = -1 * boundaries["maxY"];
|
||||
}
|
||||
}
|
||||
|
||||
// model not within bounds, we need to prepare a warning
|
||||
|
||||
@@ -10,7 +10,8 @@ $(function() {
|
||||
width: 200,
|
||||
depth: 200,
|
||||
height: 200,
|
||||
origin: "lowerleft"
|
||||
origin: "lowerleft",
|
||||
custom_box: false
|
||||
},
|
||||
heatedBed: true,
|
||||
axes: {
|
||||
@@ -53,6 +54,9 @@ $(function() {
|
||||
self.volumeOrigin("center");
|
||||
}
|
||||
});
|
||||
self.volumeOrigin.subscribe(function() {
|
||||
self.toBoundingBoxPlaceholders(self.defaultBoundingBox(self.volumeWidth(), self.volumeDepth(), self.volumeHeight(), self.volumeOrigin()));
|
||||
});
|
||||
|
||||
self.heatedBed = ko.observable();
|
||||
|
||||
@@ -70,6 +74,20 @@ $(function() {
|
||||
self.axisZInverted = ko.observable(false);
|
||||
self.axisEInverted = ko.observable(false);
|
||||
|
||||
self.customBoundingBox = ko.observable(false);
|
||||
self.boundingBoxMinX = ko.observable();
|
||||
self.boundingBoxMinY = ko.observable();
|
||||
self.boundingBoxMinZ = ko.observable();
|
||||
self.boundingBoxMaxX = ko.observable();
|
||||
self.boundingBoxMaxY = ko.observable();
|
||||
self.boundingBoxMaxZ = ko.observable();
|
||||
self.boundingBoxMinXPlaceholder = ko.observable();
|
||||
self.boundingBoxMinYPlaceholder = ko.observable();
|
||||
self.boundingBoxMinZPlaceholder = ko.observable();
|
||||
self.boundingBoxMaxXPlaceholder = ko.observable();
|
||||
self.boundingBoxMaxYPlaceholder = ko.observable();
|
||||
self.boundingBoxMaxZPlaceholder = ko.observable();
|
||||
|
||||
self.koExtruderOffsets = ko.pureComputed(function() {
|
||||
var extruderOffsets = self.extruderOffsets();
|
||||
var numExtruders = self.extruders();
|
||||
@@ -181,6 +199,13 @@ $(function() {
|
||||
self.volumeFormFactor(data.volume.formFactor);
|
||||
self.volumeOrigin(data.volume.origin);
|
||||
|
||||
if (data.volume.custom_box) {
|
||||
self.toBoundingBoxData(data.volume.custom_box, true);
|
||||
} else {
|
||||
var box = self.defaultBoundingBox(data.volume.width, data.volume.depth, data.volume.height, data.volume.origin);
|
||||
self.toBoundingBoxData(box, false);
|
||||
}
|
||||
|
||||
self.heatedBed(data.heatedBed);
|
||||
|
||||
self.nozzleDiameter(data.extruder.nozzleDiameter);
|
||||
@@ -268,6 +293,8 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.fillBoundingBoxData(profile);
|
||||
|
||||
var offsetX, offsetY;
|
||||
if (self.extruders() > 1) {
|
||||
for (var i = 0; i < self.extruders() - 1; i++) {
|
||||
@@ -288,6 +315,76 @@ $(function() {
|
||||
return profile;
|
||||
};
|
||||
|
||||
self.defaultBoundingBox = function(width, depth, height, origin) {
|
||||
if (origin == "center") {
|
||||
var halfWidth = width / 2.0;
|
||||
var halfDepth = depth / 2.0;
|
||||
|
||||
return {
|
||||
x_min: -halfWidth,
|
||||
y_min: -halfDepth,
|
||||
z_min: 0.0,
|
||||
x_max: halfWidth,
|
||||
y_max: halfDepth,
|
||||
z_max: height
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
x_min: 0.0,
|
||||
y_min: 0.0,
|
||||
z_min: 0.0,
|
||||
x_max: width,
|
||||
y_max: depth,
|
||||
z_max: height
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.toBoundingBoxData = function(box, custom) {
|
||||
self.customBoundingBox(custom);
|
||||
if (custom) {
|
||||
self.boundingBoxMinX(box.x_min);
|
||||
self.boundingBoxMinY(box.y_min);
|
||||
self.boundingBoxMinZ(box.z_min);
|
||||
self.boundingBoxMaxX(box.x_max);
|
||||
self.boundingBoxMaxY(box.y_max);
|
||||
self.boundingBoxMaxZ(box.z_max);
|
||||
} else {
|
||||
self.boundingBoxMinX(undefined);
|
||||
self.boundingBoxMinY(undefined);
|
||||
self.boundingBoxMinZ(undefined);
|
||||
self.boundingBoxMaxX(undefined);
|
||||
self.boundingBoxMaxY(undefined);
|
||||
self.boundingBoxMaxZ(undefined);
|
||||
}
|
||||
self.toBoundingBoxPlaceholders(box);
|
||||
};
|
||||
|
||||
self.toBoundingBoxPlaceholders = function(box) {
|
||||
self.boundingBoxMinXPlaceholder(box.x_min);
|
||||
self.boundingBoxMinYPlaceholder(box.y_min);
|
||||
self.boundingBoxMinZPlaceholder(box.z_min);
|
||||
self.boundingBoxMaxXPlaceholder(box.x_max);
|
||||
self.boundingBoxMaxYPlaceholder(box.y_max);
|
||||
self.boundingBoxMaxZPlaceholder(box.z_max);
|
||||
};
|
||||
|
||||
self.fillBoundingBoxData = function(profile) {
|
||||
if (self.customBoundingBox()) {
|
||||
var defaultBox = self.defaultBoundingBox(self.volumeWidth(), self.volumeDepth(), self.volumeHeight(), self.volumeOrigin());
|
||||
profile.volume.custom_box = {
|
||||
x_min: (self.boundingBoxMinX() !== undefined) ? Math.min(self.boundingBoxMinX(), defaultBox.x_min) : defaultBox.x_min,
|
||||
y_min: (self.boundingBoxMinY() !== undefined) ? Math.min(self.boundingBoxMinY(), defaultBox.y_min) : defaultBox.y_min,
|
||||
z_min: (self.boundingBoxMinZ() !== undefined) ? Math.min(self.boundingBoxMinZ(), defaultBox.z_min) : defaultBox.z_min,
|
||||
x_max: (self.boundingBoxMaxX() !== undefined) ? Math.max(self.boundingBoxMaxX(), defaultBox.x_max) : defaultBox.x_max,
|
||||
y_max: (self.boundingBoxMaxY() !== undefined) ? Math.max(self.boundingBoxMaxY(), defaultBox.y_max) : defaultBox.y_max,
|
||||
z_max: (self.boundingBoxMaxZ() !== undefined) ? Math.max(self.boundingBoxMaxZ(), defaultBox.z_max) : defaultBox.z_max
|
||||
};
|
||||
} else {
|
||||
profile.volume.custom_box = false;
|
||||
}
|
||||
};
|
||||
|
||||
self._sanitize = function(name) {
|
||||
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
|
||||
};
|
||||
|
||||
@@ -288,7 +288,12 @@ $(function() {
|
||||
};
|
||||
|
||||
self.cancel = function() {
|
||||
OctoPrint.job.cancel();
|
||||
showConfirmationDialog({
|
||||
message: gettext("This will cancel your print."),
|
||||
onproceed: function() {
|
||||
OctoPrint.job.cancel();
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,10 @@ $(function() {
|
||||
});
|
||||
self.outstanding = [];
|
||||
|
||||
self.active = false;
|
||||
self.sawUpdateEventWhileActive = false;
|
||||
self.ignoreNextUpdateEvent = false;
|
||||
|
||||
self.settingsDialog = undefined;
|
||||
self.settings_dialog_update_detected = undefined;
|
||||
self.translationManagerDialog = undefined;
|
||||
@@ -133,6 +137,7 @@ $(function() {
|
||||
self.feature_pollWatched = ko.observable(undefined);
|
||||
self.feature_ignoreIdenticalResends = ko.observable(undefined);
|
||||
self.feature_modelSizeDetection = ko.observable(undefined);
|
||||
self.feature_firmwareDetection = ko.observable(undefined);
|
||||
|
||||
self.serial_port = ko.observable();
|
||||
self.serial_baudrate = ko.observable();
|
||||
@@ -355,12 +360,14 @@ $(function() {
|
||||
self.allViewModels = allViewModels;
|
||||
|
||||
self.settingsDialog.on('show', function(event) {
|
||||
OctoPrint.coreui.settingsOpen = true;
|
||||
if (event.target.id == "settings_dialog") {
|
||||
self.requestTranslationData();
|
||||
callViewModels(allViewModels, "onSettingsShown");
|
||||
}
|
||||
});
|
||||
self.settingsDialog.on('hidden', function(event) {
|
||||
OctoPrint.coreui.settingsOpen = false;
|
||||
if (event.target.id == "settings_dialog") {
|
||||
callViewModels(allViewModels, "onSettingsHidden");
|
||||
}
|
||||
@@ -727,6 +734,7 @@ $(function() {
|
||||
|
||||
self.settingsDialog.trigger("beforeSave");
|
||||
|
||||
self.sawUpdateEventWhileSending = false;
|
||||
self.sending(data == undefined || options.sending || false);
|
||||
|
||||
if (data == undefined) {
|
||||
@@ -734,10 +742,15 @@ $(function() {
|
||||
data = getOnlyChangedData(self.getLocalData(), self.lastReceivedSettings);
|
||||
}
|
||||
|
||||
self.active = true;
|
||||
return OctoPrint.settings.save(data)
|
||||
.done(function(data, status, xhr) {
|
||||
self.ignoreNextUpdateEvent = !self.sawUpdateEventWhileSending;
|
||||
self.active = false;
|
||||
|
||||
self.receiving(true);
|
||||
self.sending(false);
|
||||
|
||||
try {
|
||||
self.fromResponse(data);
|
||||
if (options.success) options.success(data, status, xhr);
|
||||
@@ -747,6 +760,7 @@ $(function() {
|
||||
})
|
||||
.fail(function(xhr, status, error) {
|
||||
self.sending(false);
|
||||
self.active = false;
|
||||
if (options.error) options.error(xhr, status, error);
|
||||
})
|
||||
.always(function(xhr, status) {
|
||||
@@ -755,6 +769,10 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onEventSettingsUpdated = function() {
|
||||
if (self.active) {
|
||||
self.sawUpdateEventWhileActive = true;
|
||||
}
|
||||
|
||||
var preventSettingsRefresh = _.any(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onSettingsPreventRefresh")) {
|
||||
try {
|
||||
@@ -775,7 +793,8 @@ $(function() {
|
||||
|
||||
if (self.isDialogActive()) {
|
||||
// dialog is open and not currently busy...
|
||||
if (self.sending() || self.receiving()) {
|
||||
if (self.sending() || self.receiving() || self.active || self.ignoreNextUpdateEvent) {
|
||||
self.ignoreNextUpdateEvent = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -806,6 +825,12 @@ $(function() {
|
||||
$('ul.nav-list a:first', self.settingsDialog).tab("show");
|
||||
}
|
||||
};
|
||||
|
||||
self.onServerReconnect = function() {
|
||||
// the settings might have changed if the server was just restarted,
|
||||
// better refresh them now
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
|
||||
@@ -28,7 +28,9 @@ $(function() {
|
||||
action.actionSource = "core";
|
||||
actions.push(action);
|
||||
});
|
||||
actions.push({action: "divider"});
|
||||
if (response.custom && response.custom.length) {
|
||||
actions.push({action: "divider"});
|
||||
}
|
||||
}
|
||||
_.each(response.custom, function(data) {
|
||||
var action = _.extend({}, data);
|
||||
|
||||
@@ -36,6 +36,10 @@ $(function() {
|
||||
|
||||
self.heaterOptions = ko.observable({});
|
||||
|
||||
self._printerProfileInitialized = false;
|
||||
self._currentTemperatureDataBacklog = [];
|
||||
self._historyTemperatureDataBacklog = [];
|
||||
|
||||
self._printerProfileUpdated = function() {
|
||||
var graphColors = ["red", "orange", "green", "brown", "purple"];
|
||||
var heaterOptions = {};
|
||||
@@ -81,6 +85,10 @@ $(function() {
|
||||
// write back
|
||||
self.heaterOptions(heaterOptions);
|
||||
self.tools(tools);
|
||||
|
||||
if (!self._printerProfileInitialized) {
|
||||
self._triggerBacklog();
|
||||
}
|
||||
self.updatePlot();
|
||||
};
|
||||
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
|
||||
@@ -126,16 +134,36 @@ $(function() {
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processTemperatureUpdateData(data.serverTime, data.temps);
|
||||
if (!self._printerProfileInitialized) {
|
||||
self._currentTemperatureDataBacklog.push(data);
|
||||
} else {
|
||||
self._processTemperatureUpdateData(data.serverTime, data.temps);
|
||||
}
|
||||
self._processOffsetData(data.offsets);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processTemperatureHistoryData(data.serverTime, data.temps);
|
||||
if (!self._printerProfileInitialized) {
|
||||
self._historyTemperatureDataBacklog.push(data);
|
||||
} else {
|
||||
self._processTemperatureHistoryData(data.serverTime, data.temps);
|
||||
}
|
||||
self._processOffsetData(data.offsets);
|
||||
};
|
||||
|
||||
self._triggerBacklog = function() {
|
||||
_.each(self._historyTemperatureDataBacklog, function(data) {
|
||||
self._processTemperatureHistoryData(data.serverTime, data.temps);
|
||||
});
|
||||
_.each(self._currentTemperatureDataBacklog, function(data) {
|
||||
self._processTemperatureUpdateData(data.serverTime, data.temps);
|
||||
});
|
||||
self._historyTemperatureDataBacklog = [];
|
||||
self._currentTemperatureDataBacklog = [];
|
||||
self._printerProfileInitialized = true;
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
@@ -217,14 +245,17 @@ $(function() {
|
||||
})
|
||||
});
|
||||
|
||||
var filterOld = function(item) {
|
||||
return item[0] >= clientTime - self.temperature_cutoff() * 60 * 1000;
|
||||
};
|
||||
var temperature_cutoff = self.temperature_cutoff();
|
||||
if (temperature_cutoff != undefined) {
|
||||
var filterOld = function(item) {
|
||||
return item[0] >= clientTime - temperature_cutoff * 60 * 1000;
|
||||
};
|
||||
|
||||
_.each(_.keys(self.heaterOptions()), function(d) {
|
||||
result[d].actual = _.filter(result[d].actual, filterOld);
|
||||
result[d].target = _.filter(result[d].target, filterOld);
|
||||
});
|
||||
_.each(_.keys(self.heaterOptions()), function(d) {
|
||||
result[d].actual = _.filter(result[d].actual, filterOld);
|
||||
result[d].target = _.filter(result[d].target, filterOld);
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
@@ -10,12 +10,14 @@ $(function() {
|
||||
self.defaultPostRoll = 0;
|
||||
self.defaultInterval = 10;
|
||||
self.defaultRetractionZHop = 0;
|
||||
self.defaultCapturePostroll = true;
|
||||
|
||||
self.timelapseType = ko.observable(undefined);
|
||||
self.timelapseTimedInterval = ko.observable(self.defaultInterval);
|
||||
self.timelapsePostRoll = ko.observable(self.defaultPostRoll);
|
||||
self.timelapseFps = ko.observable(self.defaultFps);
|
||||
self.timelapseRetractionZHop = ko.observable(self.defaultRetractionZHop);
|
||||
self.timelapseCapturePostRoll = ko.observable(self.defaultCapturePostRoll);
|
||||
|
||||
self.persist = ko.observable(false);
|
||||
self.isDirty = ko.observable(false);
|
||||
@@ -61,6 +63,9 @@ $(function() {
|
||||
self.timelapseRetractionZHop.subscribe(function(newValue) {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.timelapseCapturePostRoll.subscribe(function() {
|
||||
self.isDirty(true);
|
||||
});
|
||||
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
@@ -167,6 +172,12 @@ $(function() {
|
||||
self.timelapseFps(self.defaultFps);
|
||||
}
|
||||
|
||||
if (config.capturePostRoll != undefined){
|
||||
self.timelapseCapturePostRoll(config.capturePostRoll);
|
||||
} else {
|
||||
self.timelapseCapturePostRoll(self.defaultCapturePostRoll);
|
||||
}
|
||||
|
||||
self.persist(false);
|
||||
self.isDirty(false);
|
||||
};
|
||||
@@ -214,6 +225,7 @@ $(function() {
|
||||
|
||||
if (self.timelapseType() == "timed") {
|
||||
payload["interval"] = self.timelapseTimedInterval();
|
||||
payload["capturePostRoll"] = self.timelapseCapturePostRoll();
|
||||
}
|
||||
|
||||
if (self.timelapseType() == "zchange") {
|
||||
|
||||
@@ -43,6 +43,13 @@ $(function() {
|
||||
|
||||
self.onStartup = function() {
|
||||
self.wizardDialog = $("#wizard_dialog");
|
||||
self.wizardDialog.on('show', function(event) {
|
||||
OctoPrint.coreui.wizardOpen = true;
|
||||
});
|
||||
self.wizardDialog.on('hidden', function(event) {
|
||||
OctoPrint.coreui.wizardOpen = false;
|
||||
});
|
||||
|
||||
self.reloadOverlay = $("#reloadui_overlay");
|
||||
};
|
||||
|
||||
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Form Factor') }}</label>
|
||||
<div class="controls">
|
||||
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="rectangular" data-bind="checked: volumeFormFactor"> {{ _('Rectangular') }}</label>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="circular" data-bind="checked: volumeFormFactor"> {{ _('Circular') }}</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Origin') }}</label>
|
||||
<div class="controls">
|
||||
<select data-bind="value: volumeOrigin, options: availableOrigins, optionsText: 'name', optionsValue: 'key'">
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Heated Bed') }}</label>
|
||||
<div class="controls">
|
||||
<input type="checkbox" data-bind="checked: heatedBed">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
{{ _('Please define the print volume.') }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div data-bind="visible: volumeFormFactor() != 'circular'" style="display: none">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Width (X)') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeWidth" placeholder="200">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Depth (Y)') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeDepth" placeholder="200">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div data-bind="visible: volumeFormFactor() == 'circular'" style="display: none">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Diameter (X/Y)') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeWidth" placeholder="200">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Height (Z)') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeHeight" placeholder="200">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
<small>{{ _('This information is used for the GCODE Viewer and/or when slicing from OctoPrint. It does NOT influence already sliced files that you upload to OctoPrint!') }}</small>
|
||||
</p>
|
||||
</form>
|
||||
@@ -1,7 +1,7 @@
|
||||
<div id="add_folder_dialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>Create Folder</h3>
|
||||
<h3>{{ _('Create Folder') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>{{ _('Please specify the name of the folder to create.') }}</p>
|
||||
|
||||
@@ -34,53 +34,67 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_sdRelativePath" id="settings-sdRelativePath"> {{ _('Select SD files by relative path') }} <span class="label">{{ _('RepRap Firmware') }}</span>
|
||||
<input type="checkbox" data-bind="checked: feature_firmwareDetection" id="settings-firmwareDetection"> {{ _('Enable automatic firmware detection') }}
|
||||
<span class="help-inline">{% trans %}
|
||||
If enabled, OctoPrint will try to figure out your printer's firmware automatically and adjust a couple of communication parameters based on that.
|
||||
If that doesn't work out, or you want more granular control, uncheck this and the parameters in question will become visible for you to adjust.
|
||||
{% endtrans %}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_sdAlwaysAvailable" id="settings-featureSdAlwaysAvailable"> {{ _('Always assume SD card is present') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
<div data-bind="visible: !feature_firmwareDetection()">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_sdRelativePath" id="settings-sdRelativePath"> {{ _('Select SD files by relative path') }} <span class="label">{{ _('RepRap Firmware') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_ignoreIdenticalResends" id="settings-ignoreIdenticalResends"> {{ _('Ignore consecutive resend requests for the same line') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_sdAlwaysAvailable" id="settings-featureSdAlwaysAvailable"> {{ _('Always assume SD card is present') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_repetierTargetTemp" id="settings-featureRepetierTargetTemp"> {{ _('Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_ignoreIdenticalResends" id="settings-ignoreIdenticalResends"> {{ _('Ignore consecutive resend requests for the same line') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_disableExternalHeatupDetection" id="settings-featureExternalHeatupDetection"> {{ _('Disable detection of external heatups') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_repetierTargetTemp" id="settings-featureRepetierTargetTemp"> {{ _('Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Send a checksum with the command')}}</label>
|
||||
<div class="controls">
|
||||
<label class="radio">
|
||||
<input type="radio" name="sendChecksumGroup" value="print" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumPrint"> {{ _('When printing') }}
|
||||
</label>
|
||||
<label class="radio">
|
||||
<input type="radio" name="sendChecksumGroup" value="always" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumAlways"> {{ _('Always') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
<label class="radio">
|
||||
<input type="radio" name="sendChecksumGroup" value="never" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumNever"> {{ _('Never') }}
|
||||
</label>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_disableExternalHeatupDetection" id="settings-featureExternalHeatupDetection"> {{ _('Disable detection of external heatups') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Send a checksum with the command')}}</label>
|
||||
<div class="controls">
|
||||
<label class="radio">
|
||||
<input type="radio" name="sendChecksumGroup" value="print" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumPrint"> {{ _('When printing') }}
|
||||
</label>
|
||||
<label class="radio">
|
||||
<input type="radio" name="sendChecksumGroup" value="always" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumAlways"> {{ _('Always') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
<label class="radio">
|
||||
<input type="radio" name="sendChecksumGroup" value="never" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumNever"> {{ _('Never') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -1,7 +1,7 @@
|
||||
<h3>{{ _('Printer Profiles') }}</h3>
|
||||
|
||||
{% include "_snippets/settings/printerprofiles/profiles.jinja2" %}
|
||||
{% include "snippets/settings/printerprofiles/profiles.jinja2" %}
|
||||
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog(); }">{{ _('Add Profile...') }}</button>
|
||||
|
||||
{% include "_snippets/settings/printerprofiles/profileEditor.jinja2" %}
|
||||
{% include "snippets/settings/printerprofiles/profileEditor.jinja2" %}
|
||||
@@ -1,7 +1,7 @@
|
||||
<form class="form-horizontal">
|
||||
<h3>{{ _('Commands') }}</h3>
|
||||
|
||||
{% include "_snippets/settings/server/serverCommandServerRestart.jinja2" %}
|
||||
{% include "_snippets/settings/server/serverCommandSystemRestart.jinja2" %}
|
||||
{% include "_snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
|
||||
{% include "snippets/settings/server/serverCommandServerRestart.jinja2" %}
|
||||
{% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %}
|
||||
{% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
|
||||
</form>
|
||||
@@ -1,21 +1,21 @@
|
||||
<h3>{{ _('Webcam') }}</h3>
|
||||
|
||||
<form class="form-horizontal">
|
||||
{% include "_snippets/settings/webcam/webcamStreamUrl.jinja2" %}
|
||||
{% include "_snippets/settings/webcam/webcamOrientation.jinja2" %}
|
||||
{% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %}
|
||||
{% include "snippets/settings/webcam/webcamOrientation.jinja2" %}
|
||||
</form>
|
||||
|
||||
<h3>{{ _('Timelapse Recordings') }}</h3>
|
||||
|
||||
<form class="form-horizontal">
|
||||
{% include "_snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
|
||||
{% include "_snippets/settings/webcam/ffmpegPath.jinja2" %}
|
||||
{% include "_snippets/settings/webcam/watermark.jinja2" %}
|
||||
{% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
|
||||
{% include "snippets/settings/webcam/ffmpegPath.jinja2" %}
|
||||
{% include "snippets/settings/webcam/watermark.jinja2" %}
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'icon-caret-right icon-caret-down', parent: '.form-horizontal', container: '.hide' }"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
{% include "_snippets/settings/webcam/ffmpegBitrate.jinja2" %}
|
||||
{% include "_snippets/settings/webcam/ffmpegThreads.jinja2" %}
|
||||
{% include "snippets/settings/webcam/ffmpegBitrate.jinja2" %}
|
||||
{% include "snippets/settings/webcam/ffmpegThreads.jinja2" %}
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -7,6 +7,6 @@
|
||||
|
||||
<p>{% trans url='http://octoprint.org/support-octoprint/' %}
|
||||
If you enjoy OctoPrint, please consider <a href="{{ url }}" target="_blank">supporting its ongoing
|
||||
development</a>. You can find find this link also in the "About" dialog. Thank you!
|
||||
development</a>, which is fully funded by users like you! You can also find this link in the "About" dialog. <strong>Thank you!</strong>
|
||||
{% endtrans %}</p>
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
var CONFIG_TIMELAPSEFILESPERPAGE = 10;
|
||||
var CONFIG_LOGFILESPERPAGE = 10;
|
||||
var CONFIG_USERSPERPAGE = 10;
|
||||
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}";
|
||||
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}"; // deprecated, only left for compatibility reasons
|
||||
var CONFIG_ACCESS_CONTROL = {% if enableAccessControl -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_ACCESS_CONTROL_ACTIVE = {% if accessControlActive -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_SD_SUPPORT = {% if enableSdSupport -%} true; {% else %} false; {%- endif %}
|
||||
|
||||
+5
-5
@@ -13,21 +13,21 @@
|
||||
</ul>
|
||||
|
||||
<!-- ko with: printerProfiles.editor -->
|
||||
<div class="tab-content scrollable">
|
||||
<div class="tab-content">
|
||||
<div id="settings_printerProfiles_editDialog_general" class="tab-pane active">
|
||||
{% include '_snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
|
||||
{% include 'snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
|
||||
</div>
|
||||
|
||||
<div id="settings_printerProfiles_editDialog_buildvolume" class="tab-pane">
|
||||
{% include '_snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
|
||||
{% include 'snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
|
||||
</div>
|
||||
|
||||
<div id="settings_printerProfiles_editDialog_axes" class="tab-pane">
|
||||
{% include '_snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
|
||||
{% include 'snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
|
||||
</div>
|
||||
|
||||
<div id="settings_printerProfiles_editDialog_extruder" class="tab-pane">
|
||||
{% include '_snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
|
||||
{% include 'snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
|
||||
</div>
|
||||
</div>
|
||||
<!-- /ko -->
|
||||
File renamed without changes.
+132
@@ -0,0 +1,132 @@
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Form Factor') }}</label>
|
||||
<div class="controls">
|
||||
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="rectangular" data-bind="checked: volumeFormFactor"> {{ _('Rectangular') }}</label>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="circular" data-bind="checked: volumeFormFactor"> {{ _('Circular') }}</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Origin') }}</label>
|
||||
<div class="controls">
|
||||
<select data-bind="value: volumeOrigin, options: availableOrigins, optionsText: 'name', optionsValue: 'key'">
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Heated Bed') }}</label>
|
||||
<div class="controls">
|
||||
<input type="checkbox" data-bind="checked: heatedBed">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
{{ _('Please define the print volume.') }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div data-bind="visible: volumeFormFactor() != 'circular'" style="display: none">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Width (X)') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeWidth" placeholder="200">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Depth (Y)') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeDepth" placeholder="200">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div data-bind="visible: volumeFormFactor() == 'circular'" style="display: none">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Diameter (X/Y)') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeWidth" placeholder="200">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Height (Z)') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeHeight" placeholder="200">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">{% trans %}
|
||||
If your printer's print head may move slightly outside the print volume (e.g. for nozzle cleaning routines)
|
||||
you can define a custom safe bounding box for its movements below.
|
||||
{% endtrans %}</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Custom bounding box') }}</label>
|
||||
<div class="controls">
|
||||
<input type="checkbox" data-bind="checked: customBoundingBox">
|
||||
</div>
|
||||
</div>
|
||||
<div data-bind="visible: customBoundingBox">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('X Coordinates') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-prepend">
|
||||
<span class="add-on">Min</span>
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMinX, attr: {placeholder: boundingBoxMinXPlaceholder, max: boundingBoxMinXPlaceholder}">
|
||||
</div>
|
||||
<div class="input-prepend">
|
||||
<span class="add-on">Max</span>
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMaxX, attr: {placeholder: boundingBoxMaxXPlaceholder, min: boundingBoxMaxXPlaceholder}">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Y Coordinates') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-prepend">
|
||||
<span class="add-on">Min</span>
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMinY, attr: {placeholder: boundingBoxMinYPlaceholder, max: boundingBoxMinYPlaceholder}">
|
||||
</div>
|
||||
<div class="input-prepend">
|
||||
<span class="add-on">Max</span>
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMaxY, attr: {placeholder: boundingBoxMaxYPlaceholder, min: boundingBoxMaxYPlaceholder}">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Z Coordinates') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-prepend">
|
||||
<span class="add-on">Min</span>
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMinZ, attr: {placeholder: boundingBoxMinZPlaceholder, max: boundingBoxMinZPlaceholder}">
|
||||
</div>
|
||||
<div class="input-prepend">
|
||||
<span class="add-on">Max</span>
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMaxZ, attr: {placeholder: boundingBoxMaxZPlaceholder, min: boundingBoxMaxZPlaceholder}">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
<small>{{ _('This information is used for the temperature tab, the bounding box check, the GCODE Viewer and/or when slicing from OctoPrint. It does NOT influence already sliced files that you upload to OctoPrint!') }}</small>
|
||||
</p>
|
||||
</form>
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -24,6 +24,13 @@
|
||||
<input type="text" class="input-mini" id="webcam_timelapse_postRoll" data-bind="value: timelapsePostRoll, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
|
||||
<span class="add-on">{{ _('sec') }}</span>
|
||||
</div>
|
||||
<div id="webcam_timelapse_capturePostRoll" data-bind="visible: timelapseType() == 'timed'">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: timelapseCapturePostRoll, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser()"> {{ _('Capture post roll images') }}
|
||||
<span class="help-block">{{ _('If this is unchecked, OctoPrint will simply repeat the last frame for the post roll instead of continuing to capture new frames.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
||||
<div id="webcam_timelapse_timedsettings" data-bind="visible: intervalInputEnabled">
|
||||
<label for="webcam_timelapse_interval">{{ _('Interval') }}</label>
|
||||
|
||||
+46
-18
@@ -303,7 +303,10 @@ def configure_timelapse(config=None, persist=False):
|
||||
interval = 10
|
||||
if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0:
|
||||
interval = config["options"]["interval"]
|
||||
current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps)
|
||||
capture_post_roll = True
|
||||
if "options" in config and "capturePostRoll" in config["options"] and isinstance(config["options"]["capturePostRoll"], bool):
|
||||
capture_post_roll = config["options"]["capturePostRoll"]
|
||||
current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps, capture_post_roll=capture_post_roll)
|
||||
|
||||
notify_callbacks(current)
|
||||
|
||||
@@ -572,6 +575,19 @@ class Timelapse(object):
|
||||
self._capture_success += 1
|
||||
return True
|
||||
|
||||
def _copying_postroll(self):
|
||||
with self._capture_mutex:
|
||||
filename = os.path.join(self._capture_dir,
|
||||
_capture_format.format(prefix=self._file_prefix) % self._image_number)
|
||||
self._image_number += 1
|
||||
|
||||
if self._perform_capture(filename):
|
||||
for _ in range(self._post_roll * self._fps):
|
||||
newFile = os.path.join(self._capture_dir,
|
||||
_capture_format.format(prefix=self._file_prefix) % self._image_number)
|
||||
self._image_number += 1
|
||||
shutil.copyfile(filename, newFile)
|
||||
|
||||
def clean_capture_dir(self):
|
||||
if not os.path.isdir(self._capture_dir):
|
||||
self._logger.warn("Cannot clean capture directory, it is unset")
|
||||
@@ -604,20 +620,13 @@ class ZTimelapse(Timelapse):
|
||||
}
|
||||
|
||||
def process_post_roll(self):
|
||||
with self._capture_mutex:
|
||||
filename = os.path.join(self._capture_dir, _capture_format.format(prefix=self._file_prefix) % self._image_number)
|
||||
self._image_number += 1
|
||||
|
||||
if self._perform_capture(filename):
|
||||
for _ in range(self._post_roll * self._fps):
|
||||
newFile = os.path.join(self._capture_dir, _capture_format.format(prefix=self._file_prefix) % self._image_number)
|
||||
self._image_number += 1
|
||||
shutil.copyfile(filename, newFile)
|
||||
|
||||
# we always copy the final image for the whole post roll
|
||||
# for z based timelapses
|
||||
self._copying_postroll()
|
||||
Timelapse.process_post_roll(self)
|
||||
|
||||
def _on_z_change(self, event, payload):
|
||||
if self._retraction_zhop != 0:
|
||||
if self._retraction_zhop != 0 and payload["old"] is not None and payload["new"] is not None:
|
||||
# check if height difference equals z-hop or is negative, if so don't take a picture
|
||||
diff = round(payload["new"] - payload["old"], 3)
|
||||
zhop = round(self._retraction_zhop, 3)
|
||||
@@ -628,11 +637,12 @@ class ZTimelapse(Timelapse):
|
||||
|
||||
|
||||
class TimedTimelapse(Timelapse):
|
||||
def __init__(self, post_roll=0, interval=1, fps=25):
|
||||
def __init__(self, post_roll=0, interval=1, fps=25, capture_post_roll=True):
|
||||
Timelapse.__init__(self, post_roll=post_roll, fps=fps)
|
||||
self._interval = interval
|
||||
if self._interval < 1:
|
||||
self._interval = 1 # force minimum interval of 1s
|
||||
self._capture_post_roll = capture_post_roll
|
||||
self._postroll_captures = 0
|
||||
self._timer = None
|
||||
self._logger.debug("TimedTimelapse initialized")
|
||||
@@ -641,11 +651,16 @@ class TimedTimelapse(Timelapse):
|
||||
def interval(self):
|
||||
return self._interval
|
||||
|
||||
@property
|
||||
def capture_post_roll(self):
|
||||
return self._capture_post_roll
|
||||
|
||||
def config_data(self):
|
||||
return {
|
||||
"type": "timed",
|
||||
"options": {
|
||||
"interval": self._interval
|
||||
"interval": self._interval,
|
||||
"capture_post_roll": self._capture_post_roll
|
||||
}
|
||||
}
|
||||
|
||||
@@ -662,14 +677,26 @@ class TimedTimelapse(Timelapse):
|
||||
self._timer.start()
|
||||
|
||||
def on_print_done(self, event, payload):
|
||||
self._postroll_captures = self._post_roll * self._fps
|
||||
if self._capture_post_roll:
|
||||
self._postroll_captures = self._post_roll * self._fps
|
||||
else:
|
||||
self._postroll_captures = 0
|
||||
Timelapse.on_print_done(self, event, payload)
|
||||
|
||||
def calculate_post_roll(self):
|
||||
return self._post_roll * self._fps * self._interval
|
||||
if self._capture_post_roll:
|
||||
return self._post_roll * self._fps * self._interval
|
||||
else:
|
||||
return Timelapse.calculate_post_roll(self)
|
||||
|
||||
def process_post_roll(self):
|
||||
pass
|
||||
if self._capture_post_roll:
|
||||
return
|
||||
|
||||
# we only use the final image as post roll if we
|
||||
# are not supposed to capture it
|
||||
self._copying_postroll()
|
||||
self.post_roll_finished()
|
||||
|
||||
def post_roll_finished(self):
|
||||
Timelapse.post_roll_finished(self)
|
||||
@@ -684,7 +711,8 @@ class TimedTimelapse(Timelapse):
|
||||
self._postroll_captures -= 1
|
||||
|
||||
def _on_timer_finished(self):
|
||||
self.post_roll_finished()
|
||||
if self._capture_post_roll:
|
||||
self.post_roll_finished()
|
||||
|
||||
|
||||
class TimelapseRenderJob(object):
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -464,6 +464,10 @@ class User(UserMixin):
|
||||
|
||||
return self._get_setting(path)
|
||||
|
||||
@property
|
||||
def roles(self):
|
||||
return list(self._roles)
|
||||
|
||||
def set_setting(self, key, value):
|
||||
if not isinstance(key, (tuple, list)):
|
||||
path = [key]
|
||||
|
||||
@@ -442,6 +442,16 @@ def to_unicode(s_or_u, encoding="utf-8", errors="strict"):
|
||||
return s_or_u
|
||||
|
||||
|
||||
def chunks(l, n):
|
||||
"""
|
||||
Yield successive n-sized chunks from l.
|
||||
|
||||
Taken from http://stackoverflow.com/a/312464/2028598
|
||||
"""
|
||||
for i in range(0, len(l), n):
|
||||
yield l[i:i+n]
|
||||
|
||||
|
||||
def is_running_from_source():
|
||||
root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
|
||||
return os.path.isdir(os.path.join(root, "src")) and os.path.isfile(os.path.join(root, "setup.py"))
|
||||
|
||||
+242
-34
@@ -28,7 +28,7 @@ from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import valid_file_type
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \
|
||||
to_unicode, bom_aware_open, TypedQueue, TypeAlreadyInQueue
|
||||
to_unicode, bom_aware_open, TypedQueue, TypeAlreadyInQueue, chunks
|
||||
|
||||
try:
|
||||
import _winreg
|
||||
@@ -50,9 +50,13 @@ regex_float = re.compile(regex_float_pattern)
|
||||
"""Regex for a float value."""
|
||||
|
||||
regexes_parameters = dict(
|
||||
floatE=re.compile("(^|[^A-Za-z])[Ee](?P<value>%s)" % regex_float_pattern),
|
||||
floatF=re.compile("(^|[^A-Za-z])[Ff](?P<value>%s)" % regex_float_pattern),
|
||||
floatP=re.compile("(^|[^A-Za-z])[Pp](?P<value>%s)" % regex_float_pattern),
|
||||
floatR=re.compile("(^|[^A-Za-z])[Rr](?P<value>%s)" % regex_float_pattern),
|
||||
floatS=re.compile("(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_float_pattern),
|
||||
floatX=re.compile("(^|[^A-Za-z])[Xx](?P<value>%s)" % regex_float_pattern),
|
||||
floatY=re.compile("(^|[^A-Za-z])[Yy](?P<value>%s)" % regex_float_pattern),
|
||||
floatZ=re.compile("(^|[^A-Za-z])[Zz](?P<value>%s)" % regex_float_pattern),
|
||||
intN=re.compile("(^|[^A-Za-z])[Nn](?P<value>%s)" % regex_int_pattern),
|
||||
intT=re.compile("(^|[^A-Za-z])[Tt](?P<value>%s)" % regex_int_pattern)
|
||||
@@ -109,6 +113,20 @@ Groups will be as follows:
|
||||
* ``target``: new target temperature (float)
|
||||
"""
|
||||
|
||||
regex_position = re.compile("X:(?P<x>{float})\s*Y:(?P<y>{float})\s*Z:(?P<z>{float})\s*E:(?P<e>{float})".format(float=regex_float_pattern))
|
||||
"""Regex for matching position reporting.
|
||||
|
||||
Groups will be as follows:
|
||||
|
||||
* ``x``: X coordinate
|
||||
* ``y``: Y coordinate
|
||||
* ``z``: Z coordinate
|
||||
* ``e``: E coordinate
|
||||
"""
|
||||
|
||||
regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):")
|
||||
"""Regex to use for splitting M115 responses."""
|
||||
|
||||
def serialList():
|
||||
baselist=[]
|
||||
if os.name=="nt":
|
||||
@@ -188,6 +206,31 @@ gcodeToEvent = {
|
||||
"M81": Events.POWER_OFF,
|
||||
}
|
||||
|
||||
class PositionRecord(object):
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.x = kwargs.get("x")
|
||||
self.y = kwargs.get("y")
|
||||
self.z = kwargs.get("z")
|
||||
self.e = kwargs.get("e")
|
||||
self.f = kwargs.get("f")
|
||||
self.t = kwargs.get("t")
|
||||
|
||||
def copy_from(self, other):
|
||||
self.x = other.x
|
||||
self.y = other.y
|
||||
self.z = other.z
|
||||
self.e = other.e
|
||||
self.f = other.f
|
||||
self.t = other.t
|
||||
|
||||
def as_dict(self):
|
||||
return dict(x=self.x,
|
||||
y=self.y,
|
||||
z=self.z,
|
||||
e=self.e,
|
||||
t=self.t,
|
||||
f=self.f)
|
||||
|
||||
class MachineCom(object):
|
||||
STATE_NONE = 0
|
||||
STATE_OPEN_SERIAL = 1
|
||||
@@ -231,6 +274,7 @@ class MachineCom(object):
|
||||
self._tempOffsets = dict()
|
||||
self._command_queue = TypedQueue()
|
||||
self._currentZ = None
|
||||
self._currentF = None
|
||||
self._heatupWaitStartTime = None
|
||||
self._heatupWaitTimeLost = 0.0
|
||||
self._pauseWaitStartTime = None
|
||||
@@ -269,6 +313,8 @@ class MachineCom(object):
|
||||
self._neverSendChecksum = settings().getBoolean(["feature", "neverSendChecksum"])
|
||||
self._sendChecksumWithUnknownCommands = settings().getBoolean(["feature", "sendChecksumWithUnknownCommands"])
|
||||
self._unknownCommandsNeedAck = settings().getBoolean(["feature", "unknownCommandsNeedAck"])
|
||||
self._sdAlwaysAvailable = settings().getBoolean(["feature", "sdAlwaysAvailable"])
|
||||
self._sdRelativePath = settings().getBoolean(["feature", "sdRelativePath"])
|
||||
self._currentLine = 1
|
||||
self._line_mutex = threading.RLock()
|
||||
self._resendDelta = None
|
||||
@@ -278,7 +324,9 @@ class MachineCom(object):
|
||||
self._currentResendCount = 0
|
||||
self._resendSwallowRepetitions = settings().getBoolean(["feature", "ignoreIdenticalResends"])
|
||||
self._resendSwallowRepetitionsCounter = 0
|
||||
self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"])
|
||||
|
||||
self._firmwareDetection = settings().getBoolean(["feature", "firmwareDetection"])
|
||||
self._firmwareInfoReceived = not self._firmwareDetection
|
||||
|
||||
self._supportResendsWithoutOk = settings().getBoolean(["serial", "supportResendsWithoutOk"])
|
||||
|
||||
@@ -329,6 +377,12 @@ class MachineCom(object):
|
||||
self._ignore_select = False
|
||||
self._manualStreaming = False
|
||||
|
||||
self.last_position = PositionRecord()
|
||||
self.pause_position = PositionRecord()
|
||||
self._record_pause_position = False
|
||||
self.cancel_position = PositionRecord()
|
||||
self._record_cancel_position = False
|
||||
|
||||
# print job
|
||||
self._currentFile = None
|
||||
|
||||
@@ -601,7 +655,7 @@ class MachineCom(object):
|
||||
def fakeOk(self):
|
||||
self._handle_ok()
|
||||
|
||||
def sendCommand(self, cmd, cmd_type=None, processed=False, force=False):
|
||||
def sendCommand(self, cmd, cmd_type=None, processed=False, force=False, on_sent=None):
|
||||
cmd = to_unicode(cmd, errors="replace")
|
||||
if not processed:
|
||||
cmd = process_gcode_line(cmd)
|
||||
@@ -610,22 +664,28 @@ class MachineCom(object):
|
||||
|
||||
if self.isPrinting() and not self.isSdFileSelected():
|
||||
try:
|
||||
self._command_queue.put((cmd, cmd_type), item_type=cmd_type)
|
||||
self._command_queue.put((cmd, cmd_type, on_sent), item_type=cmd_type)
|
||||
return True
|
||||
except TypeAlreadyInQueue as e:
|
||||
self._logger.debug("Type already in command queue: " + e.type)
|
||||
return False
|
||||
elif self.isOperational() or force:
|
||||
return self._sendCommand(cmd, cmd_type=cmd_type)
|
||||
return self._sendCommand(cmd, cmd_type=cmd_type, on_sent=on_sent)
|
||||
|
||||
def sendGcodeScript(self, scriptName, replacements=None):
|
||||
context = dict()
|
||||
if replacements is not None and isinstance(replacements, dict):
|
||||
context.update(replacements)
|
||||
context.update(dict(
|
||||
printer_profile=self._printerProfileManager.get_current_or_default()
|
||||
printer_profile=self._printerProfileManager.get_current_or_default(),
|
||||
last_position=self.last_position
|
||||
))
|
||||
|
||||
if scriptName == "afterPrintPaused" or scriptName == "beforePrintResumed":
|
||||
context.update(dict(pause_position=self.pause_position))
|
||||
elif scriptName == "afterPrintCancelled":
|
||||
context.update(dict(cancel_position=self.cancel_position))
|
||||
|
||||
template = settings().loadScript("gcode", scriptName, context=context)
|
||||
if template is None:
|
||||
scriptLines = []
|
||||
@@ -746,6 +806,10 @@ class MachineCom(object):
|
||||
if not self.isOperational():
|
||||
# printer is not connected, can't use SD
|
||||
return
|
||||
|
||||
if filename.startswith("/") and self._sdRelativePath:
|
||||
filename = filename[1:]
|
||||
|
||||
self._sdFileToSelect = filename
|
||||
self.sendCommand("M23 %s" % filename)
|
||||
else:
|
||||
@@ -759,6 +823,10 @@ class MachineCom(object):
|
||||
self._currentFile = None
|
||||
self._callback.on_comm_file_selected(None, None, False)
|
||||
|
||||
def _cancel_preparation_done(self):
|
||||
self._recordFilePosition()
|
||||
self._callback.on_comm_print_job_cancelled()
|
||||
|
||||
def cancelPrint(self, firmware_error=None):
|
||||
if not self.isOperational() or self.isStreaming():
|
||||
return
|
||||
@@ -771,6 +839,7 @@ class MachineCom(object):
|
||||
|
||||
if self.isSdFileSelected():
|
||||
self.sendCommand("M25") # pause print
|
||||
self.sendCommand("M27") # get current byte position in file
|
||||
self.sendCommand("M26 S0") # reset position in file to byte 0
|
||||
if self._sd_status_timer is not None:
|
||||
try:
|
||||
@@ -778,8 +847,17 @@ class MachineCom(object):
|
||||
except:
|
||||
pass
|
||||
|
||||
self._recordFilePosition()
|
||||
self._callback.on_comm_print_job_cancelled()
|
||||
def _on_M400_sent():
|
||||
# we don't call on_print_job_cancelled on our callback here
|
||||
# because we do this only after our M114 has been answered
|
||||
# by the firmware
|
||||
self._record_cancel_position = True
|
||||
self.sendCommand("M114")
|
||||
|
||||
self.sendCommand("M400", on_sent=_on_M400_sent)
|
||||
|
||||
def _pause_preparation_done(self):
|
||||
self._callback.on_comm_print_job_paused()
|
||||
|
||||
def setPause(self, pause):
|
||||
if self.isStreaming():
|
||||
@@ -815,8 +893,14 @@ class MachineCom(object):
|
||||
if self.isSdFileSelected():
|
||||
self.sendCommand("M25") # pause print
|
||||
|
||||
self._callback.on_comm_print_job_paused()
|
||||
def _on_M400_sent():
|
||||
# we don't call on_print_job_paused on our callback here
|
||||
# because we do this only after our M114 has been answered
|
||||
# by the firmware
|
||||
self._record_pause_position = True
|
||||
self.sendCommand("M114")
|
||||
|
||||
self.sendCommand("M400", on_sent=_on_M400_sent)
|
||||
|
||||
def getSdFiles(self):
|
||||
return self._sdFiles
|
||||
@@ -851,7 +935,7 @@ class MachineCom(object):
|
||||
return
|
||||
|
||||
self.sendCommand("M21")
|
||||
if settings().getBoolean(["feature", "sdAlwaysAvailable"]):
|
||||
if self._sdAlwaysAvailable:
|
||||
self._sdAvailable = True
|
||||
self.refreshSdFiles()
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
@@ -883,15 +967,23 @@ class MachineCom(object):
|
||||
|
||||
##~~ record aborted file positions
|
||||
|
||||
def _recordFilePosition(self):
|
||||
def getFilePosition(self):
|
||||
if self._currentFile is None:
|
||||
return
|
||||
return None
|
||||
|
||||
origin = self._currentFile.getFileLocation()
|
||||
filename = self._currentFile.getFilename()
|
||||
pos = self._currentFile.getFilepos()
|
||||
|
||||
self._callback.on_comm_record_fileposition(origin, filename, pos)
|
||||
return dict(origin=origin,
|
||||
filename=filename,
|
||||
pos=pos)
|
||||
|
||||
def _recordFilePosition(self):
|
||||
if self._currentFile is None:
|
||||
return
|
||||
data = self.getFilePosition()
|
||||
self._callback.on_comm_record_fileposition(data["origin"], data["filename"], data["pos"])
|
||||
|
||||
##~~ communication monitoring and handling
|
||||
|
||||
@@ -1045,7 +1137,9 @@ class MachineCom(object):
|
||||
# ok only considered handled if it's alone on the line, might be
|
||||
# a response to an M105 or an M114
|
||||
self._handle_ok()
|
||||
handled = (line == "wait" or line == "ok" or not ("T:" in line or "T0:" in line or "B:" in line or "C:" in line))
|
||||
needs_further_handling = "T:" in line or "T0:" in line or "B:" in line or "C:" in line or \
|
||||
"X:" in line or "FIRMWARE_NAME:" in line
|
||||
handled = (line == "wait" or line == "ok" or not needs_further_handling)
|
||||
|
||||
# process resends
|
||||
elif lower_line.startswith("resend") or lower_line.startswith("rs"):
|
||||
@@ -1064,12 +1158,34 @@ class MachineCom(object):
|
||||
|
||||
# position report processing
|
||||
if 'X:' in line and 'Y:' in line and 'Z:' in line:
|
||||
# currently only here to prevent any "B:"s in a position report from
|
||||
# triggering temperature processing and being interpreted as a bed
|
||||
# temperature - can happen with COREXY in current Marlin
|
||||
#
|
||||
# see also issue #1373
|
||||
pass
|
||||
match = regex_position.search(line)
|
||||
if match:
|
||||
# we don't know T or F when printing from SD since
|
||||
# there's no way to query it from the firmware and
|
||||
# no way to track it ourselves when not streaming
|
||||
# the file - this all sucks sooo much
|
||||
self.last_position.x = float(match.group("x"))
|
||||
self.last_position.y = float(match.group("y"))
|
||||
self.last_position.z = float(match.group("z"))
|
||||
self.last_position.e = float(match.group("e"))
|
||||
self.last_position.t = self._currentTool if not self.isSdFileSelected() else None
|
||||
self.last_position.f = self._currentF if not self.isSdFileSelected() else None
|
||||
|
||||
reason = None
|
||||
|
||||
if self._record_pause_position:
|
||||
reason = "pause"
|
||||
self._record_pause_position = False
|
||||
self.pause_position.copy_from(self.last_position)
|
||||
self._pause_preparation_done()
|
||||
|
||||
if self._record_cancel_position:
|
||||
reason = "cancel"
|
||||
self._record_cancel_position = False
|
||||
self.cancel_position.copy_from(self.last_position)
|
||||
self._cancel_preparation_done()
|
||||
|
||||
self._callback.on_comm_position_update(self.last_position.as_dict(), reason=reason)
|
||||
|
||||
# temperature processing
|
||||
elif ' T:' in line or line.startswith('T:') or ' T0:' in line or line.startswith('T0:') or ((' B:' in line or line.startswith('B:')) and not 'A:' in line):
|
||||
@@ -1108,6 +1224,33 @@ class MachineCom(object):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
##~~ firmware name & version
|
||||
elif "FIRMWARE_NAME:" in line:
|
||||
# looks like a response to M115
|
||||
data = parse_firmware_line(line)
|
||||
firmware_name = data.get("FIRMWARE_NAME")
|
||||
self._logger.info("Printer reports firmware name \"{}\"".format(firmware_name))
|
||||
|
||||
if not self._firmwareInfoReceived and firmware_name:
|
||||
if "repetier" in firmware_name.lower():
|
||||
self._logger.info("Detected Repetier firmware, enabling relevant features for issue free communication")
|
||||
|
||||
self._alwaysSendChecksum = True
|
||||
self._resendSwallowRepetitions = True
|
||||
supportRepetierTargetTemp = True
|
||||
disable_external_heatup_detection = True
|
||||
|
||||
sd_always_available = self._sdAlwaysAvailable
|
||||
self._sdAlwaysAvailable = True
|
||||
if not sd_always_available and not self._sdAvailable:
|
||||
self.initSdCard()
|
||||
|
||||
elif "reprapfirmware" in firmware_name.lower():
|
||||
self._logger.info("Detected RepRapFirmware, enabling relevant features for issue free communication")
|
||||
self._sdRelativePath = True
|
||||
|
||||
self._firmwareInfoReceived = True
|
||||
|
||||
##~~ SD Card handling
|
||||
elif 'SD init fail' in line or 'volume.init failed' in line or 'openRoot failed' in line:
|
||||
self._sdAvailable = False
|
||||
@@ -1429,6 +1572,8 @@ class MachineCom(object):
|
||||
self._changeState(self.STATE_OPERATIONAL)
|
||||
|
||||
self.resetLineNumbers()
|
||||
if self._firmwareDetection:
|
||||
self.sendCommand("M115")
|
||||
|
||||
if self._sdAvailable:
|
||||
self.refreshSdFiles()
|
||||
@@ -1472,16 +1617,17 @@ class MachineCom(object):
|
||||
|
||||
try:
|
||||
if isinstance(entry, tuple):
|
||||
if not len(entry) == 2:
|
||||
if not len(entry) == 3:
|
||||
# something with that entry is broken, ignore it and fetch
|
||||
# the next one
|
||||
continue
|
||||
cmd, cmd_type = entry
|
||||
cmd, cmd_type, callback = entry
|
||||
else:
|
||||
cmd = entry
|
||||
cmd_type = None
|
||||
callback = None
|
||||
|
||||
if self._sendCommand(cmd, cmd_type=cmd_type):
|
||||
if self._sendCommand(cmd, cmd_type=cmd_type, on_sent=callback):
|
||||
# we actually did add this cmd to the send queue, so let's
|
||||
# return, we are done here
|
||||
return True
|
||||
@@ -1809,7 +1955,7 @@ class MachineCom(object):
|
||||
|
||||
return result
|
||||
|
||||
def _sendCommand(self, cmd, cmd_type=None):
|
||||
def _sendCommand(self, cmd, cmd_type=None, on_sent=None):
|
||||
# Make sure we are only handling one sending job at a time
|
||||
with self._sendingLock:
|
||||
if self._serial is None:
|
||||
@@ -1829,7 +1975,7 @@ class MachineCom(object):
|
||||
eventManager().fire(gcodeToEvent[gcode])
|
||||
|
||||
# actually enqueue the command for sending
|
||||
if self._enqueue_for_sending(cmd, command_type=cmd_type):
|
||||
if self._enqueue_for_sending(cmd, command_type=cmd_type, on_sent=on_sent):
|
||||
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
|
||||
return True
|
||||
else:
|
||||
@@ -1837,7 +1983,7 @@ class MachineCom(object):
|
||||
|
||||
##~~ send loop handling
|
||||
|
||||
def _enqueue_for_sending(self, command, linenumber=None, command_type=None):
|
||||
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None):
|
||||
"""
|
||||
Enqueues a command an optional linenumber to use for it in the send queue.
|
||||
|
||||
@@ -1848,7 +1994,7 @@ class MachineCom(object):
|
||||
"""
|
||||
|
||||
try:
|
||||
self._send_queue.put((command, linenumber, command_type), item_type=command_type)
|
||||
self._send_queue.put((command, linenumber, command_type, on_sent), item_type=command_type)
|
||||
return True
|
||||
except TypeAlreadyInQueue as e:
|
||||
self._logger.debug("Type already in send queue: " + e.type)
|
||||
@@ -1872,8 +2018,8 @@ class MachineCom(object):
|
||||
if not self._send_queue_active:
|
||||
break
|
||||
|
||||
# fetch command and optional linenumber from queue
|
||||
command, linenumber, command_type = entry
|
||||
# fetch command, command type and optional linenumber and sent callback from queue
|
||||
command, linenumber, command_type, on_sent = entry
|
||||
|
||||
# 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
|
||||
@@ -1912,7 +2058,9 @@ class MachineCom(object):
|
||||
# now comes the part where we increase line numbers and send stuff - no turning back now
|
||||
command_requiring_checksum = gcode is not None and gcode in self._checksum_requiring_commands
|
||||
command_allowing_checksum = gcode is not None or self._sendChecksumWithUnknownCommands
|
||||
checksum_enabled = self.isPrinting() or self._alwaysSendChecksum
|
||||
checksum_enabled = not self._neverSendChecksum and (self.isPrinting() or
|
||||
self._alwaysSendChecksum or
|
||||
not self._firmwareInfoReceived)
|
||||
|
||||
command_to_send = command.encode("ascii", errors="replace")
|
||||
if command_requiring_checksum or (command_allowing_checksum and checksum_enabled):
|
||||
@@ -1921,6 +2069,9 @@ class MachineCom(object):
|
||||
self._do_send_without_checksum(command_to_send)
|
||||
|
||||
# trigger "sent" phase and use up one "ok"
|
||||
if on_sent is not None and callable(on_sent):
|
||||
# we have a sent callback for this specific command, let's execute it now
|
||||
on_sent()
|
||||
self._process_command_phase("sent", command, command_type, gcode=gcode)
|
||||
|
||||
# we only need to use up a clear if the command we just sent was either a gcode command or if we also
|
||||
@@ -2093,7 +2244,8 @@ class MachineCom(object):
|
||||
self._currentTool = int(toolMatch.group("value"))
|
||||
|
||||
def _gcode_G0_sent(self, cmd, cmd_type=None):
|
||||
if 'Z' in cmd:
|
||||
if "Z" in cmd or "F" in cmd:
|
||||
# track Z
|
||||
match = regexes_parameters["floatZ"].search(cmd)
|
||||
if match:
|
||||
try:
|
||||
@@ -2103,8 +2255,27 @@ class MachineCom(object):
|
||||
self._callback.on_comm_z_change(z)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# track F
|
||||
match = regexes_parameters["floatF"].search(cmd)
|
||||
if match:
|
||||
try:
|
||||
f = float(match.group("value"))
|
||||
self._currentF = f
|
||||
except ValueError:
|
||||
pass
|
||||
_gcode_G1_sent = _gcode_G0_sent
|
||||
|
||||
def _gcode_G28_sent(self, cmd, cmd_type=None):
|
||||
if "F" in cmd:
|
||||
match = regexes_parameters["floatF"].search(cmd)
|
||||
if match:
|
||||
try:
|
||||
f = float(match.group("value"))
|
||||
self._currentF = f
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def _gcode_M0_queuing(self, cmd, cmd_type=None):
|
||||
self.setPause(True)
|
||||
return None, # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
|
||||
@@ -2268,6 +2439,9 @@ class MachineComPrintCallback(object):
|
||||
def on_comm_temperature_update(self, temp, bedTemp):
|
||||
pass
|
||||
|
||||
def on_comm_position_update(self, position, reason=None):
|
||||
pass
|
||||
|
||||
def on_comm_state_change(self, state):
|
||||
pass
|
||||
|
||||
@@ -2429,8 +2603,16 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
|
||||
Opens the file for reading and determines the file size.
|
||||
"""
|
||||
PrintingFileInformation.start(self)
|
||||
self._read_lines = 0
|
||||
self._handle = bom_aware_open(self._filename, encoding="utf-8", errors="replace")
|
||||
self._pos = self._handle.tell()
|
||||
if self._handle.encoding.endswith("-sig"):
|
||||
# Apparently we found an utf-8 bom in the file.
|
||||
# We need to add its length to our pos because it will
|
||||
# be stripped transparently and we'll have no chance
|
||||
# catching that.
|
||||
import codecs
|
||||
self._pos += len(codecs.BOM_UTF8)
|
||||
self._read_lines = 0
|
||||
|
||||
def close(self):
|
||||
"""
|
||||
@@ -2462,11 +2644,17 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
|
||||
self._pos = self._size
|
||||
self._report_stats()
|
||||
return None
|
||||
line = to_unicode(self._handle.readline())
|
||||
|
||||
# we need to manually keep track of our pos here since
|
||||
# codecs' readline will make our handle's tell not
|
||||
# return the actual number of bytes read, but also the
|
||||
# already buffered bytes (for detecting the newlines)
|
||||
line = self._handle.readline()
|
||||
self._pos += len(line.encode("utf-8"))
|
||||
|
||||
if not line:
|
||||
self.close()
|
||||
processed = self._process(line, offsets, current_tool)
|
||||
self._pos = self._handle.tell()
|
||||
self._read_lines += 1
|
||||
return processed
|
||||
except Exception as e:
|
||||
@@ -2776,6 +2964,26 @@ def parse_temperature_line(line, current):
|
||||
|
||||
return max(maxToolNum, current), canonicalize_temperatures(result, current)
|
||||
|
||||
def parse_firmware_line(line):
|
||||
"""
|
||||
Parses the provided firmware info line.
|
||||
|
||||
The result will be a dictionary mapping from the contained keys to the contained
|
||||
values.
|
||||
|
||||
Arguments:
|
||||
line (str): the line to parse
|
||||
|
||||
Returns:
|
||||
dict: a dictionary with the parsed data
|
||||
"""
|
||||
|
||||
result = dict()
|
||||
split_line = regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string
|
||||
for key, value in chunks(split_line, 2):
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
def gcode_command_for_cmd(cmd):
|
||||
"""
|
||||
Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0").
|
||||
|
||||
@@ -9,6 +9,9 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
import sarge
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
|
||||
from . import to_unicode
|
||||
|
||||
|
||||
# These regexes are based on the colorama package
|
||||
@@ -78,40 +81,49 @@ class CommandlineCaller(object):
|
||||
kwargs.update(dict(async=True, stdout=sarge.Capture(), stderr=sarge.Capture()))
|
||||
|
||||
p = sarge.run(command, **kwargs)
|
||||
p.wait_events()
|
||||
while len(p.commands) == 0:
|
||||
# somewhat ugly... we can't use wait_events because
|
||||
# the events might not be all set if an exception
|
||||
# by sarge is triggered within the async process
|
||||
# thread
|
||||
time.sleep(0.01)
|
||||
|
||||
# by now we should have a command, let's wait for its
|
||||
# process to have been prepared
|
||||
p.commands[0].process_ready.wait()
|
||||
|
||||
if not p.commands[0].process:
|
||||
# the process might have been set to None in case of any exception
|
||||
self._logger.error(u"Error while trying to run command {}".format(joined_command))
|
||||
return None, [], []
|
||||
|
||||
all_stdout = []
|
||||
all_stderr = []
|
||||
|
||||
def process_lines(lines, logger):
|
||||
if not lines:
|
||||
return []
|
||||
l = self._preprocess_lines(*map(lambda x: to_unicode(x, errors="replace"), lines))
|
||||
logger(*l)
|
||||
return list(l)
|
||||
|
||||
def process_stdout(lines):
|
||||
return process_lines(lines, self._log_stdout)
|
||||
|
||||
def process_stderr(lines):
|
||||
return process_lines(lines, self._log_stderr)
|
||||
|
||||
try:
|
||||
while p.returncode is None:
|
||||
lines = p.stderr.readlines(timeout=0.5)
|
||||
if lines:
|
||||
lines = self._preprocess_lines(*lines)
|
||||
self._log_stderr(*lines)
|
||||
all_stderr += list(lines)
|
||||
|
||||
lines = p.stdout.readlines(timeout=0.5)
|
||||
if lines:
|
||||
lines = self._preprocess_lines(*lines)
|
||||
self._log_stdout(*lines)
|
||||
all_stdout += list(lines)
|
||||
|
||||
all_stderr += process_stderr(p.stderr.readlines(timeout=0.5))
|
||||
all_stdout += process_stdout(p.stdout.readlines(timeout=0.5))
|
||||
p.commands[0].poll()
|
||||
|
||||
finally:
|
||||
p.close()
|
||||
|
||||
lines = p.stderr.readlines()
|
||||
if lines:
|
||||
lines = self._preprocess_lines(*lines)
|
||||
self._log_stderr(*lines)
|
||||
all_stderr += lines
|
||||
|
||||
lines = p.stdout.readlines()
|
||||
if lines:
|
||||
lines = self._preprocess_lines(*lines)
|
||||
self._log_stdout(*lines)
|
||||
all_stdout += lines
|
||||
all_stderr += process_stderr(p.stderr.readlines())
|
||||
all_stdout += process_stdout(p.stdout.readlines())
|
||||
|
||||
return p.returncode, all_stdout, all_stderr
|
||||
|
||||
|
||||
@@ -143,7 +143,95 @@ class ReverseProxiedEnvironmentTest(unittest.TestCase):
|
||||
"HTTP_HOST": "example.com",
|
||||
"SERVER_NAME": "example.com",
|
||||
"SERVER_PORT": "80"
|
||||
})
|
||||
}),
|
||||
|
||||
# host = none, default port -> server & port used for reconstruction (ipv4)
|
||||
({
|
||||
"HTTP_HOST": None,
|
||||
"SERVER_NAME": "127.0.0.1",
|
||||
"SERVER_PORT": "80"
|
||||
}, {
|
||||
"HTTP_HOST": "127.0.0.1",
|
||||
"SERVER_NAME": "127.0.0.1",
|
||||
"SERVER_PORT": "80"
|
||||
}),
|
||||
|
||||
# host = none, non standard port -> server & port used for reconstruction (ipv4)
|
||||
({
|
||||
"HTTP_HOST": None,
|
||||
"SERVER_NAME": "127.0.0.1",
|
||||
"SERVER_PORT": "444"
|
||||
}, {
|
||||
"HTTP_HOST": "127.0.0.1:444",
|
||||
"SERVER_NAME": "127.0.0.1",
|
||||
"SERVER_PORT": "444"
|
||||
}),
|
||||
|
||||
# host = none, default port -> server & port used for reconstruction (ipv6)
|
||||
({
|
||||
"HTTP_HOST": None,
|
||||
"SERVER_NAME": "fec1::1",
|
||||
"SERVER_PORT": "80"
|
||||
}, {
|
||||
"HTTP_HOST": "fec1::1",
|
||||
"SERVER_NAME": "fec1::1",
|
||||
"SERVER_PORT": "80"
|
||||
}),
|
||||
|
||||
# host = none, non standard port -> server & port used for reconstruction (ipv6)
|
||||
({
|
||||
"HTTP_HOST": None,
|
||||
"SERVER_NAME": "fec1::1",
|
||||
"SERVER_PORT": "444"
|
||||
}, {
|
||||
"HTTP_HOST": "[fec1::1]:444",
|
||||
"SERVER_NAME": "fec1::1",
|
||||
"SERVER_PORT": "444"
|
||||
}),
|
||||
|
||||
# host set, server and port not, default port -> server & port derived from host (ipv4)
|
||||
({
|
||||
"HTTP_HOST": "127.0.0.1",
|
||||
"SERVER_NAME": None,
|
||||
"SERVER_PORT": None
|
||||
}, {
|
||||
"HTTP_HOST": "127.0.0.1",
|
||||
"SERVER_NAME": "127.0.0.1",
|
||||
"SERVER_PORT": "80"
|
||||
}),
|
||||
|
||||
# host set, server and port not, non standard port -> server & port derived from host (ipv4)
|
||||
({
|
||||
"HTTP_HOST": "127.0.0.1:444",
|
||||
"SERVER_NAME": None,
|
||||
"SERVER_PORT": None
|
||||
}, {
|
||||
"HTTP_HOST": "127.0.0.1:444",
|
||||
"SERVER_NAME": "127.0.0.1",
|
||||
"SERVER_PORT": "444"
|
||||
}),
|
||||
|
||||
# host set, server and port not, default port -> server & port derived from host (ipv6)
|
||||
({
|
||||
"HTTP_HOST": "fec1::1",
|
||||
"SERVER_NAME": None,
|
||||
"SERVER_PORT": None
|
||||
}, {
|
||||
"HTTP_HOST": "fec1::1",
|
||||
"SERVER_NAME": "fec1::1",
|
||||
"SERVER_PORT": "80"
|
||||
}),
|
||||
|
||||
# host set, server and port not, non standard port -> server & port derived from host (ipv6)
|
||||
({
|
||||
"HTTP_HOST": "[fec1::1]:444",
|
||||
"SERVER_NAME": None,
|
||||
"SERVER_PORT": None
|
||||
}, {
|
||||
"HTTP_HOST": "[fec1::1]:444",
|
||||
"SERVER_NAME": "fec1::1",
|
||||
"SERVER_PORT": "444"
|
||||
}),
|
||||
)
|
||||
@unpack
|
||||
def test_stock(self, environ, expected):
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user