Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c622f7c43 | ||
|
|
d34790e74e | ||
|
|
aa5099340e | ||
|
|
693633bd1d | ||
|
|
758062133c | ||
|
|
c55fea666d | ||
|
|
c932e496fa | ||
|
|
bbbdb3dde6 | ||
|
|
b9460b4890 | ||
|
|
947f4c89cc | ||
|
|
5f982ec6c8 | ||
|
|
dcf2e51b21 | ||
|
|
85e6ae8e82 | ||
|
|
859ea0d0e4 | ||
|
|
9cf21aa036 | ||
|
|
637adc3095 | ||
|
|
548f976d35 | ||
|
|
45c92cb1f4 | ||
|
|
f83d5aa89f | ||
|
|
abf073340f | ||
|
|
918ffa2557 | ||
|
|
5cc8ec5cc3 | ||
|
|
fce7b40b51 | ||
|
|
1178fe9e95 | ||
|
|
2f24e73fcb | ||
|
|
9ff5c36370 | ||
|
|
1b4ea75466 | ||
|
|
b4b5689bc4 | ||
|
|
fd4271a962 | ||
|
|
65bc28a03e | ||
|
|
c26515c13d | ||
|
|
25a4d4b79b | ||
|
|
43ca4d8252 | ||
|
|
b56ba6589c | ||
|
|
5c9b507cb7 | ||
|
|
cd7ac032f4 | ||
|
|
a2e5fc0c5c | ||
|
|
536bb31965 | ||
|
|
ef46a49430 | ||
|
|
8e28ddd6a4 | ||
|
|
ab8b0230bd | ||
|
|
754ef428a0 | ||
|
|
455474841e | ||
|
|
ae4e4f22c4 | ||
|
|
96fc70bdb2 | ||
|
|
8ed0befd62 | ||
|
|
766c0c21d4 | ||
|
|
7d50563666 | ||
|
|
4011f60ff9 | ||
|
|
37950cb466 | ||
|
|
2824b967ff | ||
|
|
7b8bf2cf5c | ||
|
|
9299cb54a4 | ||
|
|
b965d4cbde | ||
|
|
7d922f3c77 | ||
|
|
7e894d2ac2 | ||
|
|
948e20b269 | ||
|
|
0e863ad776 | ||
|
|
13d7d5f2f6 | ||
|
|
ac8faf7910 | ||
|
|
bf049ddee4 | ||
|
|
e435d55cb1 | ||
|
|
2c50237699 | ||
|
|
93763a5563 | ||
|
|
7a74f5348d | ||
|
|
b25c2220d1 | ||
|
|
57161dd9c3 | ||
|
|
1343a4a253 | ||
|
|
6de7eabca2 | ||
|
|
2247f30c87 | ||
|
|
ba6a6723a6 | ||
|
|
f9a0cb94f7 | ||
|
|
e689a2c733 | ||
|
|
d07c81f312 | ||
|
|
32f4f8d95b | ||
|
|
7f2e0161a8 | ||
|
|
59993bfca4 | ||
|
|
0782dda20f | ||
|
|
8c1a79558b | ||
|
|
0705a7054c | ||
|
|
54bd7766b9 | ||
|
|
ed215fc5fa | ||
|
|
5f53b704dd | ||
|
|
e8ef0ba8a4 | ||
|
|
49f62bc655 | ||
|
|
0ff43def3a | ||
|
|
cc14b77487 | ||
|
|
7f10c317f1 | ||
|
|
ba1f8c58b4 | ||
|
|
273bb45741 | ||
|
|
e33f69917f | ||
|
|
4b8bdd244e | ||
|
|
202f93426a | ||
|
|
c538604cd5 | ||
|
|
0c44762f6f | ||
|
|
6df57bc1d1 | ||
|
|
e328695100 | ||
|
|
738c699a6e | ||
|
|
8a28220e63 | ||
|
|
5808c1bd8a | ||
|
|
8bbb642a56 | ||
|
|
1f0dbf8f7f |
No files matched your search
+6
-3
@@ -10,10 +10,13 @@
|
|||||||
# master shall not use the lookup table, only tags
|
# master shall not use the lookup table, only tags
|
||||||
master
|
master
|
||||||
|
|
||||||
# maintenance is currently the branch for preparation of maintenance release 1.2.4
|
# maintenance is currently the branch for preparation of maintenance release 1.2.7
|
||||||
# so are any fix/... branches
|
# so are any fix/... branches
|
||||||
maintenance 1.2.4-dev 3761995aff94acf32495556730f133a1626245b3
|
maintenance 1.2.7-dev 536bb31965db17b969e7c1c53e241ddac4ae1814
|
||||||
fix/.* 1.2.4-dev 3761995aff94acf32495556730f133a1626245b3
|
fix/.* 1.2.7-dev 536bb31965db17b969e7c1c53e241ddac4ae1814
|
||||||
|
|
||||||
|
# Special case disconnected checkouts, e.g. 'git checkout <tag>'
|
||||||
|
\(detached.*
|
||||||
|
|
||||||
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
|
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
|
||||||
.* 1.3.0-dev 198d3450d94be1a2
|
.* 1.3.0-dev 198d3450d94be1a2
|
||||||
@@ -52,6 +52,7 @@ date of first contribution):
|
|||||||
* [Lucas Clemente](https://github.com/lucas-clemente)
|
* [Lucas Clemente](https://github.com/lucas-clemente)
|
||||||
* [Andrew Erickson](https://github.com/aerickson)
|
* [Andrew Erickson](https://github.com/aerickson)
|
||||||
* [Nicanor Romero Venier](https://github.com/nicanor-romero)
|
* [Nicanor Romero Venier](https://github.com/nicanor-romero)
|
||||||
|
* [Thomas Hou](https://github.com/masterhou)
|
||||||
|
|
||||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||||
|
|||||||
+146
@@ -1,5 +1,151 @@
|
|||||||
# OctoPrint Changelog
|
# OctoPrint Changelog
|
||||||
|
|
||||||
|
## 1.2.7 (2015-10-20)
|
||||||
|
|
||||||
|
### Improvements
|
||||||
|
|
||||||
|
* [#1062](https://github.com/foosel/OctoPrint/issues/1062) - Plugin Manager
|
||||||
|
now has a configuration dialog that among other things allows defining the
|
||||||
|
used `pip` command if auto detection proves to be insufficient here.
|
||||||
|
* Allow defining additional `pip` parameters in Plugin Manager. That might
|
||||||
|
make `sudo`-less installation of plugins possible in situations where it's
|
||||||
|
tricky otherwise.
|
||||||
|
* Improved timelapse processing (backported from `devel` branch):
|
||||||
|
* Individually captured frames cannot "overtake" each other anymore through
|
||||||
|
usage of a capture queue.
|
||||||
|
* Notifications will now be shown when the capturing of the timelapse's
|
||||||
|
post roll happens, including an approximation of how long that will take.
|
||||||
|
* Usage of `requests` instead of `urllib` for fetching the snapshot,
|
||||||
|
appears to also have [positive effects on webcam compatibility](https://github.com/foosel/OctoPrint/issues/1078).
|
||||||
|
* Some more defensive escaping for various settings in the UI (e.g. webcam URL)
|
||||||
|
* Switch to more error resilient saving of configuration files and other files
|
||||||
|
modified during runtime (save to temporary file & move). Should reduce risk
|
||||||
|
of file corruption.
|
||||||
|
* Downloading GCODE and STL files should now set more fitting `Content-Type`
|
||||||
|
headers (`text/plain` and `application/sla`) for better client side support
|
||||||
|
for "Open with" like usage scenarios.
|
||||||
|
* Selecting z-triggered timelapse mode will now inform about that not working
|
||||||
|
when printing from SD card.
|
||||||
|
* Software Update Plugin: Removed "The web interface will now be reloaded"
|
||||||
|
notification after successful update since that became obsolete with
|
||||||
|
introduction of the "Reload Now" overlay.
|
||||||
|
* Updated required version of `psutil` and `netifaces` dependencies.
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* [#1057](https://github.com/foosel/OctoPrint/issues/1057) - Better error
|
||||||
|
resilience of the Software Update plugin against broken/incomplete update
|
||||||
|
configurations.
|
||||||
|
* [#1075](https://github.com/foosel/OctoPrint/issues/1075) - Fixed support
|
||||||
|
of `sudo` for installing plugins, but added big visible warning about it
|
||||||
|
as it's **not** recommended.
|
||||||
|
* [#1077](https://github.com/foosel/OctoPrint/issues/1077) - Do not hiccup
|
||||||
|
on [UTF-8 BOMs](https://en.wikipedia.org/wiki/Byte_order_mark) (or other
|
||||||
|
BOMs for that matter) at the beginning of GCODE files.
|
||||||
|
* Fixed an issue that caused user sessions to not be properly associated,
|
||||||
|
leading to Sessions getting duplicated, wrongly saved etc.
|
||||||
|
* Fixed internal server error (HTTP 500) response on REST API calls with
|
||||||
|
unset `Content-Type` header.
|
||||||
|
* Fixed an issue leading to drag-and-drop file uploads to trigger frontend
|
||||||
|
processing in various other file upload widgets.
|
||||||
|
* Fixed a documentation error.
|
||||||
|
* Fixed caching behaviour on GCODE/STL downloads, was setting the `ETag`
|
||||||
|
header improperly.
|
||||||
|
* Fixed GCODE viewer not properly detecting change of currently visualized
|
||||||
|
file on Windows systems.
|
||||||
|
|
||||||
|
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.6...1.2.7))
|
||||||
|
|
||||||
|
## 1.2.6 (2015-09-02)
|
||||||
|
|
||||||
|
### Improvements
|
||||||
|
|
||||||
|
* Added support for version reporting on detached checkouts
|
||||||
|
(see [#1041](https://github.com/foosel/OctoPrint/pull/1041))
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* Pinned requirement for [psutil](https://pypi.python.org/pypi/psutil)
|
||||||
|
dependency to version 3.1.1 of that library due to an issue when
|
||||||
|
installing version 3.2.0 of that library released on 2015-09-02 through
|
||||||
|
a `python setup.py install` on OctoPrint. Also pinned all other requirements
|
||||||
|
to definitive versions that definitely work while at it to keep that from
|
||||||
|
happening again.
|
||||||
|
|
||||||
|
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.5...1.2.6))
|
||||||
|
|
||||||
|
## 1.2.5 (2015-08-31)
|
||||||
|
|
||||||
|
### Improvements
|
||||||
|
|
||||||
|
* [#986](https://github.com/foosel/OctoPrint/issues/986) - Added tooltip for
|
||||||
|
"additional data" button in file list.
|
||||||
|
* [#1028](https://github.com/foosel/OctoPrint/issues/1028) - Hint about why
|
||||||
|
timelapse configuration is disabled.
|
||||||
|
* 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.
|
||||||
|
* Settings dialog now visualizes when settings are saving and when they being
|
||||||
|
retrieved. Also the Send/Cancel buttons are disabled while settings are saving
|
||||||
|
to prevent duplicated requests and concurrent retrieval of the settings by
|
||||||
|
multiple viewmodels is disabled as well.
|
||||||
|
* Better protection against rendering errors from templates provided by third
|
||||||
|
party plugins.
|
||||||
|
* Better protection against corrupting the configuration by using a temporary
|
||||||
|
file as intermediate buffer.
|
||||||
|
* Added warning to UI regarding Z timelapses and spiralized objects.
|
||||||
|
* Better compatibility with Repetier firmware:
|
||||||
|
* Added "Format Error" to whitelisted recoverable communication errors
|
||||||
|
(see also [#1032](https://github.com/foosel/OctoPrint/pull/1032)).
|
||||||
|
* Added option to ignore repeated resend requests for the same line (see
|
||||||
|
also discussion in [#1015](https://github.com/foosel/OctoPrint/pull/1015)).
|
||||||
|
* Software Update Plugin:
|
||||||
|
* Adjusted to utilize new centralized restart commands (see above).
|
||||||
|
* Allow configuration of checkout folder and version tracking type via
|
||||||
|
Plugin Configuration.
|
||||||
|
* Display message to user if OctoPrint's checkout folder is not configured
|
||||||
|
or a non-release version is running and version tracking against releases
|
||||||
|
is enabled.
|
||||||
|
* Clear version cache when a change in the check configuration is detected.
|
||||||
|
* Mark check configurations for which an update is not possible.
|
||||||
|
* Made disk space running low a bit more obvious through visual warning on
|
||||||
|
configurable thresholds.
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* [#985](https://github.com/foosel/OctoPrint/issues/985) - Do not hiccup on
|
||||||
|
unset `Content-Type` part headers for multipart file uploads.
|
||||||
|
* [#1001](https://github.com/foosel/OctoPrint/issues/1001) - Fixed connection
|
||||||
|
tab not unfolding properly (see also [#1002](https://github.com/foosel/OctoPrint/pull/1002)).
|
||||||
|
* [#1012](https://github.com/foosel/OctoPrint/issues/1012) - All API
|
||||||
|
responses now set no-cache headers, making the Edge browser behave a bit better
|
||||||
|
* [#1019](https://github.com/foosel/OctoPrint/issues/1019) - Better error
|
||||||
|
handling of problems when trying to write the webassets cache.
|
||||||
|
* [#1021](https://github.com/foosel/OctoPrint/issues/1021) - Properly handle
|
||||||
|
serial close on Macs.
|
||||||
|
* [#1031](https://github.com/foosel/OctoPrint/issues/1031) - Special
|
||||||
|
handling of `M112` (emergency stop) command:
|
||||||
|
* Jump send queue
|
||||||
|
* In case the printer's firmware doesn't understand it yet, at least
|
||||||
|
shutdown all of the heaters
|
||||||
|
* Disconnect
|
||||||
|
* Properly reset job progress to 0% when restarting a previously completed
|
||||||
|
printjob (see [#998](https://github.com/foosel/OctoPrint/pull/998)).
|
||||||
|
* Report an update as failed if the `pip` command returns a return code that
|
||||||
|
indicates failure.
|
||||||
|
* Fixed sorting of templates: could only be sorted by name, individual
|
||||||
|
configurations were ignored (see [#1022](https://github.com/foosel/OctoPrint/pull/1022)).
|
||||||
|
* Fixed positioning of custom context menus: were offset due to changes in
|
||||||
|
overall positioning settings (see [#1023](https://github.com/foosel/OctoPrint/pull/1023)).
|
||||||
|
* Software Update: Don't use display version for comparison of git commit
|
||||||
|
hashs.
|
||||||
|
* Fixed temperature parsing for multi extruder setups.
|
||||||
|
* Fixed nested vertical and horizontal custom control layouts.
|
||||||
|
|
||||||
|
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.4...1.2.5))
|
||||||
|
|
||||||
## 1.2.4 (2015-07-23)
|
## 1.2.4 (2015-07-23)
|
||||||
|
|
||||||
### Improvements
|
### Improvements
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
OctoPrint
|
OctoPrint
|
||||||
=========
|
=========
|
||||||
|
|
||||||
OctoPrint provides a responsive web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
|
OctoPrint provides a snappy web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
|
||||||
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
|
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
|
||||||
|
|
||||||
Its website can be found at [octoprint.org](http://octoprint.org).
|
Its website can be found at [octoprint.org](http://octoprint.org).
|
||||||
|
|
||||||
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
|
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
|
||||||
|
|
||||||
|
The official plugin repository can be reached at [plugins.octoprint.org](http://plugins.octoprint.org).
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
You are currently looking at the source code repository of OctoPrint. If you already installed it
|
You are currently looking at the source code repository of OctoPrint. If you already installed it
|
||||||
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
|
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
|
||||||
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
|
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
|
||||||
@@ -34,15 +38,30 @@ For information about how to go about contributions of any kind, please see the
|
|||||||
Installation
|
Installation
|
||||||
------------
|
------------
|
||||||
|
|
||||||
Installation instructions for installing from source for different operating systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
|
Installation instructions for installing from source for different operating
|
||||||
|
systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
|
||||||
|
|
||||||
If you want to run OctoPrint on a Raspberry Pi you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
|
If you want to run OctoPrint on a Raspberry Pi you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
|
||||||
which is a custom SD card image that includes OctoPrint plus dependencies.
|
which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||||
|
|
||||||
|
The generic steps that should basically be done regardless of operating system
|
||||||
|
and runtime environment are the following (as *regular
|
||||||
|
user*, please keep your hands *off* of the `sudo` command here!) - this assumes
|
||||||
|
you already have Python 2.7, pip and virtualenv set up:
|
||||||
|
|
||||||
|
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
|
||||||
|
2. Change into the OctoPrint folder: `cd OctoPrint`
|
||||||
|
3. Create a user-owned virtual environment therein: `virtualenv --system-site-packages venv`
|
||||||
|
4. Install OctoPrint *into that virtual environment*: `./venv/bin/python setup.py install`
|
||||||
|
|
||||||
|
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
|
||||||
|
for details.
|
||||||
|
|
||||||
After installation, please make sure you follow the first-run wizard and set up
|
After installation, please make sure you follow the first-run wizard and set up
|
||||||
access control as necessary. If you want to not only be notified about new
|
access control as necessary. If you want to not only be notified about new
|
||||||
releases but also be able to automatically upgrade to them from within
|
releases but also be able to automatically upgrade to them from within
|
||||||
OctoPrint, take a look [at the documentation of the Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#making-octoprint-updateable-on-existing-installations).
|
OctoPrint, take a look [at the documentation of the Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#making-octoprint-updateable-on-existing-installations)
|
||||||
|
and at its settings.
|
||||||
|
|
||||||
Dependencies
|
Dependencies
|
||||||
------------
|
------------
|
||||||
@@ -113,3 +132,4 @@ Special Thanks
|
|||||||
|
|
||||||
The development of OctoPrint is sponsored and maintained by [BQ](http://www.bq.com/).
|
The development of OctoPrint is sponsored and maintained by [BQ](http://www.bq.com/).
|
||||||
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
|
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
|
||||||
|
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
|
||||||
+1
-1
@@ -15,7 +15,7 @@ Log file management
|
|||||||
Retrieve a list of available log files
|
Retrieve a list of available log files
|
||||||
======================================
|
======================================
|
||||||
|
|
||||||
.. http:post:: /api/logs
|
.. http:get:: /api/logs
|
||||||
|
|
||||||
Retrieve information regarding all log files currently available and regarding the disk space still available
|
Retrieve information regarding all log files currently available and regarding the disk space still available
|
||||||
in the system on the location the log files are being stored.
|
in the system on the location the log files are being stored.
|
||||||
|
|||||||
@@ -621,7 +621,8 @@ Use the following settings to configure the server:
|
|||||||
.. code-block:: yaml
|
.. code-block:: yaml
|
||||||
|
|
||||||
server:
|
server:
|
||||||
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all interfaces)
|
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all
|
||||||
|
# interfaces)
|
||||||
host: 0.0.0.0
|
host: 0.0.0.0
|
||||||
|
|
||||||
# Use this option to define the port to which to bind the server, defaults to 5000
|
# Use this option to define the port to which to bind the server, defaults to 5000
|
||||||
@@ -691,6 +692,18 @@ Use the following settings to configure the server:
|
|||||||
# Maximum size of requests other than file uploads in bytes, defaults to 100KB.
|
# Maximum size of requests other than file uploads in bytes, defaults to 100KB.
|
||||||
maxSize: 102400
|
maxSize: 102400
|
||||||
|
|
||||||
|
# Commands to restart/shutdown octoprint or the system it's running on
|
||||||
|
commands:
|
||||||
|
|
||||||
|
# Command to restart OctoPrint, defaults to being unset
|
||||||
|
serverRestartCommand: sudo service octoprint restart
|
||||||
|
|
||||||
|
# Command to restart the system OctoPrint is running on, defaults to being unset
|
||||||
|
systemRestartCommand: sudo shutdown -r now
|
||||||
|
|
||||||
|
# Command to shut down the system OctoPrint is running on, defaults to being unset
|
||||||
|
systemShutdownCommand: sudo shutdown -h now
|
||||||
|
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
|
|||||||
@@ -16,22 +16,23 @@ INSTALL_REQUIRES = [
|
|||||||
"flask>=0.9,<0.11",
|
"flask>=0.9,<0.11",
|
||||||
"werkzeug==0.8.3",
|
"werkzeug==0.8.3",
|
||||||
"tornado==4.0.1",
|
"tornado==4.0.1",
|
||||||
"sockjs-tornado>=1.0.0",
|
"sockjs-tornado==1.0.1",
|
||||||
"PyYAML==3.10",
|
"PyYAML==3.10",
|
||||||
"Flask-Login==0.2.2",
|
"Flask-Login==0.2.2",
|
||||||
"Flask-Principal==0.3.5",
|
"Flask-Principal==0.3.5",
|
||||||
"Flask-Babel==0.9",
|
"Flask-Babel==0.9",
|
||||||
"Flask-Assets==0.10",
|
"Flask-Assets==0.10",
|
||||||
"pyserial",
|
"pyserial==2.7",
|
||||||
"netaddr",
|
"netaddr==0.7.17",
|
||||||
"watchdog",
|
"watchdog==0.8.3",
|
||||||
"sarge>=0.1.4",
|
"sarge==0.1.4",
|
||||||
"netifaces",
|
"netifaces==0.10",
|
||||||
"pylru",
|
"pylru==1.0.9",
|
||||||
"rsa",
|
"rsa==3.2",
|
||||||
"pkginfo",
|
"pkginfo==1.2.1",
|
||||||
"requests",
|
"requests==2.7.0",
|
||||||
"semantic_version"
|
"semantic_version==2.4.2",
|
||||||
|
"psutil==3.2.1"
|
||||||
]
|
]
|
||||||
|
|
||||||
# Additional requirements for optional install options
|
# Additional requirements for optional install options
|
||||||
|
|||||||
@@ -74,6 +74,9 @@ class Events(object):
|
|||||||
# Timelapse
|
# Timelapse
|
||||||
CAPTURE_START = "CaptureStart"
|
CAPTURE_START = "CaptureStart"
|
||||||
CAPTURE_DONE = "CaptureDone"
|
CAPTURE_DONE = "CaptureDone"
|
||||||
|
CAPTURE_FAILED = "CaptureFailed"
|
||||||
|
POSTROLL_START = "PostRollStart"
|
||||||
|
POSTROLL_END = "PostRollEnd"
|
||||||
MOVIE_RENDERING = "MovieRendering"
|
MOVIE_RENDERING = "MovieRendering"
|
||||||
MOVIE_DONE = "MovieDone"
|
MOVIE_DONE = "MovieDone"
|
||||||
MOVIE_FAILED = "MovieFailed"
|
MOVIE_FAILED = "MovieFailed"
|
||||||
|
|||||||
@@ -18,6 +18,11 @@ from .analysis import QueueEntry, AnalysisQueue
|
|||||||
from .storage import LocalFileStorage
|
from .storage import LocalFileStorage
|
||||||
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
|
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
|
||||||
|
|
||||||
|
from collections import namedtuple
|
||||||
|
|
||||||
|
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
|
||||||
|
ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector")
|
||||||
|
|
||||||
extensions = dict(
|
extensions = dict(
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -25,11 +30,11 @@ def full_extension_tree():
|
|||||||
result = dict(
|
result = dict(
|
||||||
# extensions for 3d model files
|
# extensions for 3d model files
|
||||||
model=dict(
|
model=dict(
|
||||||
stl=["stl"]
|
stl=ContentTypeMapping(["stl"], "application/sla")
|
||||||
),
|
),
|
||||||
# extensions for printable machine code
|
# extensions for printable machine code
|
||||||
machinecode=dict(
|
machinecode=dict(
|
||||||
gcode=["gcode", "gco", "g"]
|
gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain")
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -68,8 +73,12 @@ def get_all_extensions(subtree=None):
|
|||||||
for key, value in subtree.items():
|
for key, value in subtree.items():
|
||||||
if isinstance(value, dict):
|
if isinstance(value, dict):
|
||||||
result += get_all_extensions(value)
|
result += get_all_extensions(value)
|
||||||
|
elif isinstance(value, (ContentTypeMapping, ContentTypeDetector)):
|
||||||
|
result += value.extensions
|
||||||
elif isinstance(value, (list, tuple)):
|
elif isinstance(value, (list, tuple)):
|
||||||
result += value
|
result += value
|
||||||
|
elif isinstance(subtree, (ContentTypeMapping, ContentTypeDetector)):
|
||||||
|
result = subtree.extensions
|
||||||
elif isinstance(subtree, (list, tuple)):
|
elif isinstance(subtree, (list, tuple)):
|
||||||
result = subtree
|
result = subtree
|
||||||
return result
|
return result
|
||||||
@@ -79,7 +88,9 @@ def get_path_for_extension(extension, subtree=None):
|
|||||||
subtree = full_extension_tree()
|
subtree = full_extension_tree()
|
||||||
|
|
||||||
for key, value in subtree.items():
|
for key, value in subtree.items():
|
||||||
if isinstance(value, (list, tuple)) and extension in value:
|
if isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions:
|
||||||
|
return [key]
|
||||||
|
elif isinstance(value, (list, tuple)) and extension in value:
|
||||||
return [key]
|
return [key]
|
||||||
elif isinstance(value, dict):
|
elif isinstance(value, dict):
|
||||||
path = get_path_for_extension(extension, subtree=value)
|
path = get_path_for_extension(extension, subtree=value)
|
||||||
@@ -88,6 +99,23 @@ def get_path_for_extension(extension, subtree=None):
|
|||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def get_content_type_mapping_for_extension(extension, subtree=None):
|
||||||
|
if not subtree:
|
||||||
|
subtree = full_extension_tree()
|
||||||
|
|
||||||
|
for key, value in subtree.items():
|
||||||
|
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions
|
||||||
|
list_extension_matches = isinstance(value, (list, tuple)) and extension in value
|
||||||
|
|
||||||
|
if content_extension_matches or list_extension_matches:
|
||||||
|
return value
|
||||||
|
elif isinstance(value, dict):
|
||||||
|
result = get_content_type_mapping_for_extension(extension, subtree=value)
|
||||||
|
if result is not None:
|
||||||
|
return result
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
def valid_extension(extension, type=None):
|
def valid_extension(extension, type=None):
|
||||||
if not type:
|
if not type:
|
||||||
return extension in get_all_extensions()
|
return extension in get_all_extensions()
|
||||||
@@ -106,6 +134,19 @@ def get_file_type(filename):
|
|||||||
extension = extension[1:].lower()
|
extension = extension[1:].lower()
|
||||||
return get_path_for_extension(extension)
|
return get_path_for_extension(extension)
|
||||||
|
|
||||||
|
def get_mime_type(filename):
|
||||||
|
_, extension = os.path.splitext(filename)
|
||||||
|
extension = extension[1:].lower()
|
||||||
|
mapping = get_content_type_mapping_for_extension(extension)
|
||||||
|
if mapping:
|
||||||
|
if isinstance(mapping, ContentTypeMapping) and mapping.content_type is not None:
|
||||||
|
return mapping.content_type
|
||||||
|
elif isinstance(mapping, ContentTypeDetector) and callable(mapping.detector):
|
||||||
|
result = mapping.detector(filename)
|
||||||
|
if result is not None:
|
||||||
|
return result
|
||||||
|
return "application/octet-stream"
|
||||||
|
|
||||||
|
|
||||||
class NoSuchStorage(Exception):
|
class NoSuchStorage(Exception):
|
||||||
pass
|
pass
|
||||||
@@ -155,7 +196,11 @@ class FileManager(object):
|
|||||||
self._slicing_progress_callbacks.append(callback)
|
self._slicing_progress_callbacks.append(callback)
|
||||||
|
|
||||||
def unregister_slicingprogress_callback(self, callback):
|
def unregister_slicingprogress_callback(self, callback):
|
||||||
self._slicing_progress_callbacks.remove(callback)
|
try:
|
||||||
|
self._slicing_progress_callbacks.remove(callback)
|
||||||
|
except ValueError:
|
||||||
|
# callback was not registered
|
||||||
|
pass
|
||||||
|
|
||||||
def _determine_analysis_backlog(self, storage_type, storage_manager):
|
def _determine_analysis_backlog(self, storage_type, storage_manager):
|
||||||
counter = 0
|
counter = 0
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
|||||||
|
|
||||||
import io
|
import io
|
||||||
|
|
||||||
|
from octoprint.util import atomic_write
|
||||||
|
|
||||||
class AbstractFileWrapper(object):
|
class AbstractFileWrapper(object):
|
||||||
"""
|
"""
|
||||||
Wrapper for file representations to save to storages.
|
Wrapper for file representations to save to storages.
|
||||||
@@ -85,7 +87,7 @@ class StreamWrapper(AbstractFileWrapper):
|
|||||||
"""
|
"""
|
||||||
import shutil
|
import shutil
|
||||||
|
|
||||||
with open(path, "wb") as dest:
|
with atomic_write(path, "wb") as dest:
|
||||||
with self.stream() as source:
|
with self.stream() as source:
|
||||||
shutil.copyfileobj(source, dest)
|
shutil.copyfileobj(source, dest)
|
||||||
|
|
||||||
|
|||||||
@@ -861,7 +861,7 @@ class PluginManager(object):
|
|||||||
additional_pre_inits=additional_pre_inits,
|
additional_pre_inits=additional_pre_inits,
|
||||||
additional_post_inits=additional_post_inits)
|
additional_post_inits=additional_post_inits)
|
||||||
|
|
||||||
self.logger.info("Initialized {count} plugin(s)".format(count=len(self.plugin_implementations)))
|
self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
|
||||||
|
|
||||||
def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
||||||
if plugin.implementation is None:
|
if plugin.implementation is None:
|
||||||
@@ -955,15 +955,13 @@ class PluginManager(object):
|
|||||||
self.logger.info("No plugins available")
|
self.logger.info("No plugins available")
|
||||||
else:
|
else:
|
||||||
self.logger.info("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), plugins="\n".join(
|
self.logger.info("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), plugins="\n".join(
|
||||||
sorted(
|
map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
|
||||||
map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
|
bundled_strs=bundled_str,
|
||||||
bundled_strs=bundled_str,
|
show_location=show_location,
|
||||||
show_location=show_location,
|
location_str=location_str,
|
||||||
location_str=location_str,
|
show_enabled=show_enabled,
|
||||||
show_enabled=show_enabled,
|
enabled_strs=enabled_str),
|
||||||
enabled_strs=enabled_str),
|
sorted(self.plugins.values(), key=lambda x: str(x).lower()))
|
||||||
self.enabled_plugins.values())
|
|
||||||
)
|
|
||||||
)))
|
)))
|
||||||
|
|
||||||
def get_plugin(self, identifier, require_enabled=True):
|
def get_plugin(self, identifier, require_enabled=True):
|
||||||
|
|||||||
@@ -393,7 +393,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
|||||||
|
|
||||||
def _save_profile(self, path, profile, allow_overwrite=True):
|
def _save_profile(self, path, profile, allow_overwrite=True):
|
||||||
import yaml
|
import yaml
|
||||||
with open(path, "wb") as f:
|
with octoprint.util.atomic_write(path, "wb") as f:
|
||||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||||
|
|
||||||
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
|
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
|
||||||
|
|||||||
@@ -82,14 +82,23 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
|||||||
repository="http://plugins.octoprint.org/plugins.json",
|
repository="http://plugins.octoprint.org/plugins.json",
|
||||||
repository_ttl=24*60,
|
repository_ttl=24*60,
|
||||||
pip=None,
|
pip=None,
|
||||||
|
pip_args=None,
|
||||||
dependency_links=False,
|
dependency_links=False,
|
||||||
hidden=[]
|
hidden=[]
|
||||||
)
|
)
|
||||||
|
|
||||||
def on_settings_save(self, data):
|
def on_settings_save(self, data):
|
||||||
|
old_pip = self._settings.get(["pip"])
|
||||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||||
|
new_pip = self._settings.get(["pip"])
|
||||||
|
|
||||||
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
|
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
|
||||||
self._pip_caller.refresh = True
|
if old_pip != new_pip:
|
||||||
|
self._pip_caller.configured = new_pip
|
||||||
|
try:
|
||||||
|
self._pip_caller.trigger_refresh()
|
||||||
|
except:
|
||||||
|
self._pip_caller
|
||||||
|
|
||||||
##~~ AssetPlugin
|
##~~ AssetPlugin
|
||||||
|
|
||||||
@@ -169,7 +178,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
|||||||
if "refresh_repository" in request.values and request.values["refresh_repository"] in valid_boolean_trues:
|
if "refresh_repository" in request.values and request.values["refresh_repository"] in valid_boolean_trues:
|
||||||
self._repository_available = self._refresh_repository()
|
self._repository_available = self._refresh_repository()
|
||||||
|
|
||||||
return jsonify(plugins=result, repository=dict(available=self._repository_available, plugins=self._repository_plugins), os=self._get_os(), octoprint=self._get_octoprint_version())
|
return jsonify(plugins=result,
|
||||||
|
repository=dict(
|
||||||
|
available=self._repository_available,
|
||||||
|
plugins=self._repository_plugins
|
||||||
|
),
|
||||||
|
os=self._get_os(),
|
||||||
|
octoprint=self._get_octoprint_version(),
|
||||||
|
pip=dict(
|
||||||
|
available=self._pip_caller.available,
|
||||||
|
command=self._pip_caller.command,
|
||||||
|
version=self._pip_caller.version_string,
|
||||||
|
use_sudo=self._pip_caller.use_sudo,
|
||||||
|
additional_args=self._settings.get(["pip_args"])
|
||||||
|
))
|
||||||
|
|
||||||
def on_api_command(self, command, data):
|
def on_api_command(self, command, data):
|
||||||
if not admin_permission.can():
|
if not admin_permission.can():
|
||||||
@@ -428,6 +450,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
|||||||
if self._pip_caller < self._pip_version_dependency_links:
|
if self._pip_caller < self._pip_version_dependency_links:
|
||||||
args.remove("--process-dependency-links")
|
args.remove("--process-dependency-links")
|
||||||
|
|
||||||
|
additional_args = self._settings.get(["pip_args"])
|
||||||
|
if additional_args:
|
||||||
|
args.append(additional_args)
|
||||||
|
|
||||||
return self._pip_caller.execute(*args)
|
return self._pip_caller.execute(*args)
|
||||||
|
|
||||||
def _log_message(self, *lines):
|
def _log_message(self, *lines):
|
||||||
@@ -510,7 +536,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
import json
|
import json
|
||||||
with open(self._repository_cache_path, "w+b") as f:
|
with octoprint.util.atomic_write(self._repository_cache_path, "wb") as f:
|
||||||
json.dump(repo_data, f)
|
json.dump(repo_data, f)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e)))
|
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e)))
|
||||||
@@ -603,7 +629,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
|||||||
pending_enable=(not plugin.enabled and plugin.key in self._pending_enable),
|
pending_enable=(not plugin.enabled and plugin.key in self._pending_enable),
|
||||||
pending_disable=(plugin.enabled and plugin.key in self._pending_disable),
|
pending_disable=(plugin.enabled and plugin.key in self._pending_disable),
|
||||||
pending_install=(plugin.key in self._pending_install),
|
pending_install=(plugin.key in self._pending_install),
|
||||||
pending_uninstall=(plugin.key in self._pending_uninstall)
|
pending_uninstall=(plugin.key in self._pending_uninstall),
|
||||||
|
origin=plugin.origin.type
|
||||||
)
|
)
|
||||||
|
|
||||||
__plugin_name__ = "Plugin Manager"
|
__plugin_name__ = "Plugin Manager"
|
||||||
|
|||||||
@@ -6,6 +6,13 @@ $(function() {
|
|||||||
self.settingsViewModel = parameters[1];
|
self.settingsViewModel = parameters[1];
|
||||||
self.printerState = parameters[2];
|
self.printerState = parameters[2];
|
||||||
|
|
||||||
|
self.config_repositoryUrl = ko.observable();
|
||||||
|
self.config_repositoryTtl = ko.observable();
|
||||||
|
self.config_pipCommand = ko.observable();
|
||||||
|
self.config_pipAdditionalArgs = ko.observable();
|
||||||
|
|
||||||
|
self.configurationDialog = $("#settings_plugin_pluginmanager_configurationdialog");
|
||||||
|
|
||||||
self.plugins = new ItemListHelper(
|
self.plugins = new ItemListHelper(
|
||||||
"plugin.pluginmanager.installedplugins",
|
"plugin.pluginmanager.installedplugins",
|
||||||
{
|
{
|
||||||
@@ -72,6 +79,12 @@ $(function() {
|
|||||||
|
|
||||||
self.followDependencyLinks = ko.observable(false);
|
self.followDependencyLinks = ko.observable(false);
|
||||||
|
|
||||||
|
self.pipAvailable = ko.observable(false);
|
||||||
|
self.pipCommand = ko.observable();
|
||||||
|
self.pipVersion = ko.observable();
|
||||||
|
self.pipUseSudo = ko.observable();
|
||||||
|
self.pipAdditionalArgs = ko.observable();
|
||||||
|
|
||||||
self.working = ko.observable(false);
|
self.working = ko.observable(false);
|
||||||
self.workingTitle = ko.observable();
|
self.workingTitle = ko.observable();
|
||||||
self.workingDialog = undefined;
|
self.workingDialog = undefined;
|
||||||
@@ -86,11 +99,15 @@ $(function() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
self.enableUninstall = function(data) {
|
self.enableUninstall = function(data) {
|
||||||
return self.enableManagement() && !data.bundled && data.key != 'pluginmanager' && !data.pending_uninstall;
|
return self.enableManagement()
|
||||||
|
&& (data.origin != "entry_point" || self.pipAvailable())
|
||||||
|
&& !data.bundled
|
||||||
|
&& data.key != 'pluginmanager'
|
||||||
|
&& !data.pending_uninstall;
|
||||||
};
|
};
|
||||||
|
|
||||||
self.enableRepoInstall = function(data) {
|
self.enableRepoInstall = function(data) {
|
||||||
return self.enableManagement() && self.isCompatible(data);
|
return self.enableManagement() && self.pipAvailable() && self.isCompatible(data);
|
||||||
};
|
};
|
||||||
|
|
||||||
self.invalidUrl = ko.computed(function() {
|
self.invalidUrl = ko.computed(function() {
|
||||||
@@ -100,7 +117,7 @@ $(function() {
|
|||||||
|
|
||||||
self.enableUrlInstall = ko.computed(function() {
|
self.enableUrlInstall = ko.computed(function() {
|
||||||
var url = self.installUrl();
|
var url = self.installUrl();
|
||||||
return self.enableManagement() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
return self.enableManagement() && self.pipAvailable() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||||
});
|
});
|
||||||
|
|
||||||
self.invalidArchive = ko.computed(function() {
|
self.invalidArchive = ko.computed(function() {
|
||||||
@@ -110,7 +127,7 @@ $(function() {
|
|||||||
|
|
||||||
self.enableArchiveInstall = ko.computed(function() {
|
self.enableArchiveInstall = ko.computed(function() {
|
||||||
var name = self.uploadFilename();
|
var name = self.uploadFilename();
|
||||||
return self.enableManagement() && name !== undefined && name.trim() != "" && !self.invalidArchive();
|
return self.enableManagement() && self.pipAvailable() && name !== undefined && name.trim() != "" && !self.invalidArchive();
|
||||||
});
|
});
|
||||||
|
|
||||||
self.uploadElement.fileupload({
|
self.uploadElement.fileupload({
|
||||||
@@ -167,7 +184,8 @@ $(function() {
|
|||||||
|
|
||||||
self.fromResponse = function(data) {
|
self.fromResponse = function(data) {
|
||||||
self._fromPluginsResponse(data.plugins);
|
self._fromPluginsResponse(data.plugins);
|
||||||
self._fromRepositoryResponse(data.repository)
|
self._fromRepositoryResponse(data.repository);
|
||||||
|
self._fromPipResponse(data.pip);
|
||||||
};
|
};
|
||||||
|
|
||||||
self._fromPluginsResponse = function(data) {
|
self._fromPluginsResponse = function(data) {
|
||||||
@@ -188,6 +206,21 @@ $(function() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
self._fromPipResponse = function(data) {
|
||||||
|
self.pipAvailable(data.available);
|
||||||
|
if (data.available) {
|
||||||
|
self.pipCommand(data.command);
|
||||||
|
self.pipVersion(data.version);
|
||||||
|
self.pipUseSudo(data.use_sudo);
|
||||||
|
self.pipAdditionalArgs(data.additional_args);
|
||||||
|
} else {
|
||||||
|
self.pipCommand(undefined);
|
||||||
|
self.pipVersion(undefined);
|
||||||
|
self.pipUseSudo(undefined);
|
||||||
|
self.pipAdditionalArgs(undefined);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
self.requestData = function(includeRepo) {
|
self.requestData = function(includeRepo) {
|
||||||
if (!self.loginState.isAdmin()) {
|
if (!self.loginState.isAdmin()) {
|
||||||
return;
|
return;
|
||||||
@@ -343,6 +376,58 @@ $(function() {
|
|||||||
self.requestData(true);
|
self.requestData(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
self.showPluginSettings = function() {
|
||||||
|
self._copyConfig();
|
||||||
|
self.configurationDialog.modal();
|
||||||
|
};
|
||||||
|
|
||||||
|
self.savePluginSettings = function() {
|
||||||
|
var pipCommand = self.config_pipCommand();
|
||||||
|
if (pipCommand != undefined && pipCommand.trim() == "") {
|
||||||
|
pipCommand = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var repository = self.config_repositoryUrl();
|
||||||
|
if (repository != undefined && repository.trim() == "") {
|
||||||
|
repository = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var repositoryTtl;
|
||||||
|
try {
|
||||||
|
repositoryTtl = parseInt(self.config_repositoryTtl());
|
||||||
|
} catch (ex) {
|
||||||
|
repositoryTtl = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var pipArgs = self.config_pipAdditionalArgs();
|
||||||
|
if (pipArgs != undefined && pipArgs.trim() == "") {
|
||||||
|
pipArgs = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var data = {
|
||||||
|
plugins: {
|
||||||
|
pluginmanager: {
|
||||||
|
repository: repository,
|
||||||
|
repository_ttl: repositoryTtl,
|
||||||
|
pip: pipCommand,
|
||||||
|
pip_args: pipArgs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.settingsViewModel.saveData(data, function() {
|
||||||
|
self.configurationDialog.modal("hide");
|
||||||
|
self._copyConfig();
|
||||||
|
self.refreshRepository();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
self._copyConfig = function() {
|
||||||
|
self.config_repositoryUrl(self.settingsViewModel.settings.plugins.pluginmanager.repository());
|
||||||
|
self.config_repositoryTtl(self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl());
|
||||||
|
self.config_pipCommand(self.settingsViewModel.settings.plugins.pluginmanager.pip());
|
||||||
|
self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
|
||||||
|
};
|
||||||
|
|
||||||
self.installed = function(data) {
|
self.installed = function(data) {
|
||||||
return _.includes(self.installedPlugins(), data.id);
|
return _.includes(self.installedPlugins(), data.id);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,7 +4,31 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endmacro %}
|
{% endmacro %}
|
||||||
|
|
||||||
|
{% macro pluginmanager_nopip() %}
|
||||||
|
<div class="alert" data-bind="visible: !pipAvailable()">{% trans %}
|
||||||
|
The <code>pip</code> command could not be found.
|
||||||
|
Please configure it manually. No installation and uninstallation of plugin
|
||||||
|
packages is possible while <code>pip</code> is unavailable.
|
||||||
|
{% endtrans %}</div>
|
||||||
|
{% endmacro %}
|
||||||
|
|
||||||
|
{% macro pluginmanager_sudopip() %}
|
||||||
|
<div class="alert alert-error" data-bind="visible: pipUseSudo()">{% trans %}
|
||||||
|
The <code>pip</code> command is configured to use <code>sudo</code>. This
|
||||||
|
is <strong>not</strong> recommended due to security reasons. It is <strong>strongly</strong>
|
||||||
|
suggested you install OctoPrint under a
|
||||||
|
<a href="https://github.com/foosel/OctoPrint/#installation">user-owned virtual environment</a>
|
||||||
|
so that the use of <code>sudo</code> is not needed for plugin management.
|
||||||
|
{% endtrans %}</div>
|
||||||
|
{% endmacro %}
|
||||||
|
|
||||||
{{ pluginmanager_printing() }}
|
{{ pluginmanager_printing() }}
|
||||||
|
{{ pluginmanager_nopip() }}
|
||||||
|
{{ pluginmanager_sudopip() }}
|
||||||
|
|
||||||
|
<div class="pull-right">
|
||||||
|
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<h3>{{ _('Installed Plugins') }}</h3>
|
<h3>{{ _('Installed Plugins') }}</h3>
|
||||||
|
|
||||||
@@ -47,6 +71,10 @@
|
|||||||
|
|
||||||
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
|
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
|
||||||
|
|
||||||
|
<p class="muted" data-bind="visible: pipAvailable()">
|
||||||
|
<small>Using pip at "<span data-bind="text: pipCommand"></span>" (Version <span data-bind="text: pipVersion"></span><span data-bind="visible: pipAdditionalArgs">, additional arguments: <span data-bind="text: pipAdditionalArgs"></span></span>)</small>
|
||||||
|
</p>
|
||||||
|
|
||||||
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
|
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||||
@@ -67,6 +95,8 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="modal-body">
|
<div class="modal-body">
|
||||||
{{ pluginmanager_printing() }}
|
{{ pluginmanager_printing() }}
|
||||||
|
{{ pluginmanager_nopip() }}
|
||||||
|
{{ pluginmanager_sudopip() }}
|
||||||
<h4 style="position: relative">
|
<h4 style="position: relative">
|
||||||
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
|
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
|
||||||
<a class="dropdown-toggle pull-right" data-toggle="dropdown" href="#">
|
<a class="dropdown-toggle pull-right" data-toggle="dropdown" href="#">
|
||||||
@@ -167,3 +197,47 @@
|
|||||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div id="settings_plugin_pluginmanager_configurationdialog" class="modal hide fade">
|
||||||
|
<div class="modal-header">
|
||||||
|
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||||
|
<h3>{{ _('Plugin Configuration') }}</h3>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<form class="form-horizontal">
|
||||||
|
<div class="control-group" title="{{ _('pip command to use for managing plugins. You might have to configure this if auto detection fails.') }}">
|
||||||
|
<label class="control-label">{{ _('pip command') }}</label>
|
||||||
|
<div class="controls">
|
||||||
|
<input type="text" class="input-block-level" data-bind="value: config_pipCommand" placeholder="{{ _('Autodetect') }}">
|
||||||
|
<span class="help-inline">{{ _('<strong>Only</strong> set this if OctoPrint cannot autodetect the path to <code>pip</code> to use for managing plugins.') }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="control-group" title="{{ _('Additional arguments for pip command. You should normally not have to change this.') }}">
|
||||||
|
<label class="control-label">{{ _('Additional pip arguments') }}</label>
|
||||||
|
<div class="controls">
|
||||||
|
<input type="text" class="input-block-level" data-bind="value: config_pipAdditionalArgs">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.') }}">
|
||||||
|
<label class="control-label">{{ _('Repository URL') }}</label>
|
||||||
|
<div class="controls">
|
||||||
|
<input type="text" class="input-block-level" data-bind="value: config_repositoryUrl">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.') }}">
|
||||||
|
<label class="control-label">{{ _('Repository cache TTL') }}</label>
|
||||||
|
<div class="controls">
|
||||||
|
<div class="input-append">
|
||||||
|
<input type="number" class="input-mini" data-bind="value: config_repositoryTtl">
|
||||||
|
<span class="add-on">min</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
|
||||||
|
<button class="btn btn-primary" data-bind="click: savePluginSettings" aria-hidden="true">{{ _('Save') }}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
@@ -12,6 +12,7 @@ import flask
|
|||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
import hashlib
|
||||||
|
|
||||||
from . import version_checks, updaters, exceptions, util
|
from . import version_checks, updaters, exceptions, util
|
||||||
|
|
||||||
@@ -58,6 +59,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
self._refresh_configured_checks = False
|
self._refresh_configured_checks = False
|
||||||
self._configured_checks = self._settings.get(["checks"], merged=True)
|
self._configured_checks = self._settings.get(["checks"], merged=True)
|
||||||
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
||||||
|
check_providers = self._settings.get(["check_providers"], merged=True)
|
||||||
for name, hook in update_check_hooks.items():
|
for name, hook in update_check_hooks.items():
|
||||||
try:
|
try:
|
||||||
hook_checks = hook()
|
hook_checks = hook()
|
||||||
@@ -65,9 +67,23 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
|
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
|
||||||
else:
|
else:
|
||||||
for key, data in hook_checks.items():
|
for key, data in hook_checks.items():
|
||||||
|
check_providers[key] = name
|
||||||
if key in self._configured_checks:
|
if key in self._configured_checks:
|
||||||
data = dict_merge(data, self._configured_checks[key])
|
data = dict_merge(data, self._configured_checks[key])
|
||||||
self._configured_checks[key] = data
|
self._configured_checks[key] = data
|
||||||
|
self._settings.set(["check_providers"], check_providers)
|
||||||
|
self._settings.save()
|
||||||
|
|
||||||
|
# we only want to process checks that came from plugins for
|
||||||
|
# which the plugins are still installed and enabled
|
||||||
|
config_checks = self._settings.get(["checks"])
|
||||||
|
plugin_and_not_enabled = lambda k: k in check_providers and \
|
||||||
|
not check_providers[k] in self._plugin_manager.enabled_plugins
|
||||||
|
obsolete_plugin_checks = filter(plugin_and_not_enabled,
|
||||||
|
config_checks.keys())
|
||||||
|
for key in obsolete_plugin_checks:
|
||||||
|
self._logger.debug("Check for key {} was provided by plugin {} that's no longer available, ignoring it".format(key, check_providers[key]))
|
||||||
|
del self._configured_checks[key]
|
||||||
|
|
||||||
return self._configured_checks
|
return self._configured_checks
|
||||||
|
|
||||||
@@ -83,8 +99,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
self._logger.exception("Error while loading version cache from disk")
|
self._logger.exception("Error while loading version cache from disk")
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
if "octoprint" in data and len(data["octoprint"]) == 4 and "local" in data["octoprint"][1] and "value" in data["octoprint"][1]["local"]:
|
if not isinstance(data, dict):
|
||||||
data_version = data["octoprint"][1]["local"]["value"]
|
self._logger.info("Version cache was created in a different format, not using it")
|
||||||
|
return
|
||||||
|
|
||||||
|
if "__version" in data:
|
||||||
|
data_version = data["__version"]
|
||||||
else:
|
else:
|
||||||
self._logger.info("Can't determine version of OctoPrint version cache was created for, not using it")
|
self._logger.info("Can't determine version of OctoPrint version cache was created for, not using it")
|
||||||
return
|
return
|
||||||
@@ -102,24 +122,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
self._logger.exception("Error parsing in version cache data")
|
self._logger.exception("Error parsing in version cache data")
|
||||||
|
|
||||||
def _save_version_cache(self):
|
def _save_version_cache(self):
|
||||||
import tempfile
|
|
||||||
import yaml
|
import yaml
|
||||||
import shutil
|
from octoprint.util import atomic_write
|
||||||
|
from octoprint._version import get_versions
|
||||||
|
|
||||||
file_obj = tempfile.NamedTemporaryFile(delete=False)
|
octoprint_version = get_versions()["version"]
|
||||||
try:
|
self._version_cache["__version"] = octoprint_version
|
||||||
|
|
||||||
|
with atomic_write(self._version_cache_path) as file_obj:
|
||||||
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
|
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||||
file_obj.close()
|
|
||||||
shutil.move(file_obj.name, self._version_cache_path)
|
|
||||||
|
|
||||||
self._version_cache_dirty = False
|
self._version_cache_dirty = False
|
||||||
self._logger.info("Saved version cache to disk")
|
self._logger.info("Saved version cache to disk")
|
||||||
finally:
|
|
||||||
try:
|
|
||||||
if os.path.exists(file_obj.name):
|
|
||||||
os.remove(file_obj.name)
|
|
||||||
except Exception as e:
|
|
||||||
self._logger.warn("Could not delete file {}: {}".format(file_obj.name, str(e)))
|
|
||||||
|
|
||||||
#~~ SettingsPlugin API
|
#~~ SettingsPlugin API
|
||||||
|
|
||||||
@@ -134,10 +148,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
"restart": "octoprint"
|
"restart": "octoprint"
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
"octoprint_restart_command": None,
|
|
||||||
"environment_restart_command": None,
|
|
||||||
"pip_command": None,
|
"pip_command": None,
|
||||||
|
"check_providers": {},
|
||||||
|
|
||||||
"cache_ttl": 24 * 60,
|
"cache_ttl": 24 * 60,
|
||||||
}
|
}
|
||||||
@@ -146,28 +158,92 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
data = dict(octoprint.plugin.SettingsPlugin.on_settings_load(self))
|
data = dict(octoprint.plugin.SettingsPlugin.on_settings_load(self))
|
||||||
if "checks" in data:
|
if "checks" in data:
|
||||||
del data["checks"]
|
del data["checks"]
|
||||||
|
|
||||||
|
checks = self._get_configured_checks()
|
||||||
|
if "octoprint" in checks:
|
||||||
|
if "checkout_folder" in checks["octoprint"]:
|
||||||
|
data["octoprint_checkout_folder"] = checks["octoprint"]["checkout_folder"]
|
||||||
|
elif "update_folder" in checks["octoprint"]:
|
||||||
|
data["octoprint_checkout_folder"] = checks["octoprint"]["update_folder"]
|
||||||
|
else:
|
||||||
|
data["octoprint_checkout_folder"] = None
|
||||||
|
data["octoprint_type"] = checks["octoprint"].get("type", None)
|
||||||
|
else:
|
||||||
|
data["octoprint_checkout_folder"] = None
|
||||||
|
data["octoprint_type"] = None
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
def on_settings_save(self, data):
|
def on_settings_save(self, data):
|
||||||
for key in self.get_settings_defaults():
|
for key in self.get_settings_defaults():
|
||||||
if key == "checks" or key == "cache_ttl":
|
if key == "checks" or key == "cache_ttl" or key == "octoprint_checkout_folder" or key == "octoprint_type":
|
||||||
continue
|
continue
|
||||||
if key in data:
|
if key in data:
|
||||||
self._settings.set([key], data[key])
|
self._settings.set([key], data[key])
|
||||||
|
|
||||||
if "cache_ttl" in data:
|
if "cache_ttl" in data:
|
||||||
self._settings.set_int(["cache_ttl"], data["cache_ttl"])
|
self._settings.set_int(["cache_ttl"], data["cache_ttl"])
|
||||||
|
|
||||||
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
|
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
|
||||||
|
|
||||||
|
checks = self._get_configured_checks()
|
||||||
|
if "octoprint" in checks:
|
||||||
|
check = checks["octoprint"]
|
||||||
|
update_type = check.get("type", None)
|
||||||
|
checkout_folder = check.get("checkout_folder", None)
|
||||||
|
update_folder = check.get("update_folder", None)
|
||||||
|
|
||||||
|
defaults = dict(
|
||||||
|
plugins=dict(softwareupdate=dict(
|
||||||
|
checks=dict(
|
||||||
|
octoprint=dict(
|
||||||
|
type=update_type,
|
||||||
|
checkout_folder=checkout_folder,
|
||||||
|
update_folder=update_folder
|
||||||
|
)
|
||||||
|
)
|
||||||
|
))
|
||||||
|
)
|
||||||
|
|
||||||
|
if "octoprint_checkout_folder" in data:
|
||||||
|
self._settings.set(["checks", "octoprint", "checkout_folder"], data["octoprint_checkout_folder"], defaults=defaults, force=True)
|
||||||
|
if update_folder and data["octoprint_checkout_folder"]:
|
||||||
|
self._settings.set(["checks", "octoprint", "update_folder"], None, defaults=defaults, force=True)
|
||||||
|
self._refresh_configured_checks = True
|
||||||
|
|
||||||
|
if "octoprint_type" in data and data["octoprint_type"] in ("github_release", "git_commit"):
|
||||||
|
self._settings.set(["checks", "octoprint", "type"], data["octoprint_type"], defaults=defaults, force=True)
|
||||||
|
self._refresh_configured_checks = True
|
||||||
|
|
||||||
def get_settings_version(self):
|
def get_settings_version(self):
|
||||||
return 3
|
return 4
|
||||||
|
|
||||||
def on_settings_migrate(self, target, current=None):
|
def on_settings_migrate(self, target, current=None):
|
||||||
|
|
||||||
|
if current is None or current < 4:
|
||||||
|
# config version 4 and higher moves octoprint_restart_command and
|
||||||
|
# environment_restart_command to the core configuration
|
||||||
|
|
||||||
|
# current plugin commands
|
||||||
|
configured_octoprint_restart_command = self._settings.get(["octoprint_restart_command"])
|
||||||
|
configured_environment_restart_command = self._settings.get(["environment_restart_command"])
|
||||||
|
|
||||||
|
# current global commands
|
||||||
|
configured_system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||||
|
configured_server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||||
|
|
||||||
|
# only set global commands if they are not yet set
|
||||||
|
if configured_system_restart_command is None and configured_environment_restart_command is not None:
|
||||||
|
self._settings.global_set(["server", "commands", "systemRestartCommand"], configured_environment_restart_command)
|
||||||
|
if configured_server_restart_command is None and configured_octoprint_restart_command is not None:
|
||||||
|
self._settings.global_set(["server", "commands", "serverRestartCommand"], configured_octoprint_restart_command)
|
||||||
|
|
||||||
|
# delete current plugin commands from config
|
||||||
|
self._settings.set(["environment_restart_command"], None)
|
||||||
|
self._settings.set(["octoprint_restart_command"], None)
|
||||||
|
|
||||||
if current is None or current == 2:
|
if current is None or current == 2:
|
||||||
# there might be some left over data from the time we still persisted everything to settings,
|
# No config version and config version 2 need the same fix, stripping
|
||||||
# even the stuff that shouldn't be persisted but always provided by the hook - let's
|
# accidentally persisted data off the checks
|
||||||
# clean up
|
|
||||||
|
|
||||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||||
if configured_checks is None:
|
if configured_checks is None:
|
||||||
@@ -213,6 +289,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
self._settings.set(["checks", key], None, defaults=dummy_defaults)
|
self._settings.set(["checks", key], None, defaults=dummy_defaults)
|
||||||
|
|
||||||
elif current == 1:
|
elif current == 1:
|
||||||
|
# config version 1 had the error that the octoprint check got accidentally
|
||||||
|
# included in checks["octoprint"], leading to recursion and hence to
|
||||||
|
# yaml parser errors
|
||||||
|
|
||||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||||
if configured_checks is None:
|
if configured_checks is None:
|
||||||
return
|
return
|
||||||
@@ -223,7 +303,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
|
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
|
||||||
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
|
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
|
||||||
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
|
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
|
||||||
self._settings.save()
|
|
||||||
|
|
||||||
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
|
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
|
||||||
if delete is None:
|
if delete is None:
|
||||||
@@ -338,43 +417,51 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
target_information, target_update_available, target_update_possible = self._get_current_version(target, check, force=force)
|
populated_check = self._populated_check(target, check)
|
||||||
|
target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force)
|
||||||
if target_information is None:
|
if target_information is None:
|
||||||
continue
|
target_information = dict()
|
||||||
except exceptions.UnknownCheckType:
|
except exceptions.UnknownCheckType:
|
||||||
self._logger.warn("Unknown update check type for %s" % target)
|
self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", "<n/a>")))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown")), target_information)
|
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown")), target_information)
|
||||||
|
|
||||||
update_available = update_available or target_update_available
|
update_available = update_available or target_update_available
|
||||||
update_possible = update_possible or (target_update_possible and target_update_available)
|
update_possible = update_possible or (target_update_possible and target_update_available)
|
||||||
information[target] = dict(updateAvailable=target_update_available, updatePossible=target_update_possible, information=target_information)
|
|
||||||
|
|
||||||
if "displayName" in check:
|
from octoprint._version import get_versions
|
||||||
information[target]["displayName"] = check["displayName"]
|
octoprint_version = get_versions()["version"]
|
||||||
|
local_name = target_information["local"]["name"]
|
||||||
|
local_value = target_information["local"]["value"]
|
||||||
|
|
||||||
if "displayVersion" in check:
|
information[target] = dict(updateAvailable=target_update_available,
|
||||||
from octoprint._version import get_versions
|
updatePossible=target_update_possible,
|
||||||
octoprint_version = get_versions()["version"]
|
information=target_information,
|
||||||
local_name = target_information["local"]["name"]
|
displayName=populated_check["displayName"],
|
||||||
local_value = target_information["local"]["value"]
|
displayVersion=populated_check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value),
|
||||||
information[target]["displayVersion"] = check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value)
|
check=populated_check)
|
||||||
|
|
||||||
if self._version_cache_dirty:
|
if self._version_cache_dirty:
|
||||||
self._save_version_cache()
|
self._save_version_cache()
|
||||||
return information, update_available, update_possible
|
return information, update_available, update_possible
|
||||||
|
|
||||||
|
def _get_check_hash(self, check):
|
||||||
|
hash = hashlib.md5()
|
||||||
|
hash.update(repr(check))
|
||||||
|
return hash.hexdigest()
|
||||||
|
|
||||||
def _get_current_version(self, target, check, force=False):
|
def _get_current_version(self, target, check, force=False):
|
||||||
"""
|
"""
|
||||||
Determines the current version information for one target based on its check configuration.
|
Determines the current version information for one target based on its check configuration.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
current_hash = self._get_check_hash(check)
|
||||||
if target in self._version_cache and not force:
|
if target in self._version_cache and not force:
|
||||||
timestamp, information, update_available, update_possible = self._version_cache[target]
|
data = self._version_cache[target]
|
||||||
if timestamp + self._version_cache_ttl >= time.time() > timestamp:
|
if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]:
|
||||||
# we also check that timestamp < now to not get confused too much by clock changes
|
# we also check that timestamp < now to not get confused too much by clock changes
|
||||||
return information, update_available, update_possible
|
return data["information"], data["available"], data["possible"]
|
||||||
|
|
||||||
information = dict()
|
information = dict()
|
||||||
update_available = False
|
update_available = False
|
||||||
@@ -397,7 +484,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
except:
|
except:
|
||||||
update_possible = False
|
update_possible = False
|
||||||
|
|
||||||
self._version_cache[target] = (time.time(), information, update_available, update_possible)
|
self._version_cache[target] = dict(timestamp=time.time(),
|
||||||
|
hash=current_hash,
|
||||||
|
information=information,
|
||||||
|
available=update_available,
|
||||||
|
possible=update_possible)
|
||||||
self._version_cache_dirty = True
|
self._version_cache_dirty = True
|
||||||
return information, update_available, update_possible
|
return information, update_available, update_possible
|
||||||
|
|
||||||
@@ -481,7 +572,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
if restart_type is not None and restart_type in ("octoprint", "environment"):
|
if restart_type is not None and restart_type in ("octoprint", "environment"):
|
||||||
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
|
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
|
||||||
# we can actually perform that
|
# we can actually perform that
|
||||||
restart_command = self._settings.get(["%s_restart_command" % restart_type])
|
|
||||||
|
if restart_type == "octoprint":
|
||||||
|
restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||||
|
elif restart_type == "environment":
|
||||||
|
restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||||
|
|
||||||
if restart_command is not None:
|
if restart_command is not None:
|
||||||
self._send_client_message("restarting", dict(restart_type=restart_type, results=target_results))
|
self._send_client_message("restarting", dict(restart_type=restart_type, results=target_results))
|
||||||
@@ -574,6 +669,33 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
self._logger.warn("Restart stderr:\n%s" % e.stderr)
|
self._logger.warn("Restart stderr:\n%s" % e.stderr)
|
||||||
raise exceptions.RestartFailed()
|
raise exceptions.RestartFailed()
|
||||||
|
|
||||||
|
def _populated_check(self, target, check):
|
||||||
|
if not "type" in check:
|
||||||
|
raise exceptions.UnknownCheckType()
|
||||||
|
|
||||||
|
result = dict(check)
|
||||||
|
|
||||||
|
if target == "octoprint":
|
||||||
|
from flask.ext.babel import gettext
|
||||||
|
result["displayName"] = check.get("displayName", gettext("OctoPrint"))
|
||||||
|
result["displayVersion"] = check.get("displayVersion", "{octoprint_version}")
|
||||||
|
|
||||||
|
from octoprint._version import get_versions
|
||||||
|
versions = get_versions()
|
||||||
|
if check["type"] == "github_commit":
|
||||||
|
result["current"] = versions.get("full-revisionid", versions.get("full", "unknown"))
|
||||||
|
else:
|
||||||
|
result["current"] = versions["version"]
|
||||||
|
else:
|
||||||
|
result["displayName"] = check.get("displayName", target)
|
||||||
|
result["displayVersion"] = check.get("displayVersion", check.get("current", "unknown"))
|
||||||
|
if check["type"] in ("github_commit"):
|
||||||
|
result["current"] = check.get("current", None)
|
||||||
|
else:
|
||||||
|
result["current"] = check.get("current", check.get("displayVersion", None))
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
def _get_version_checker(self, target, check):
|
def _get_version_checker(self, target, check):
|
||||||
"""
|
"""
|
||||||
Retrieves the version checker to use for given target and check configuration. Will raise an UnknownCheckType
|
Retrieves the version checker to use for given target and check configuration. Will raise an UnknownCheckType
|
||||||
@@ -583,13 +705,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
|||||||
if not "type" in check:
|
if not "type" in check:
|
||||||
raise exceptions.ConfigurationInvalid("no check type defined")
|
raise exceptions.ConfigurationInvalid("no check type defined")
|
||||||
|
|
||||||
if target == "octoprint":
|
|
||||||
from octoprint._version import get_versions
|
|
||||||
from flask.ext.babel import gettext
|
|
||||||
check["displayName"] = gettext("OctoPrint")
|
|
||||||
check["displayVersion"] = "{octoprint_version}"
|
|
||||||
check["current"] = get_versions()["version"]
|
|
||||||
|
|
||||||
check_type = check["type"]
|
check_type = check["type"]
|
||||||
if check_type == "github_release":
|
if check_type == "github_release":
|
||||||
return version_checks.github_release
|
return version_checks.github_release
|
||||||
|
|||||||
@@ -13,12 +13,22 @@ $(function() {
|
|||||||
|
|
||||||
self.currentlyBeingUpdated = [];
|
self.currentlyBeingUpdated = [];
|
||||||
|
|
||||||
self.config_restartCommand = ko.observable();
|
self.octoprintUnconfigured = ko.observable();
|
||||||
self.config_rebootCommand = ko.observable();
|
self.octoprintUnreleased = ko.observable();
|
||||||
|
|
||||||
self.config_cacheTtl = ko.observable();
|
self.config_cacheTtl = ko.observable();
|
||||||
|
self.config_checkoutFolder = ko.observable();
|
||||||
|
self.config_checkType = ko.observable();
|
||||||
|
|
||||||
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
||||||
|
|
||||||
|
self.config_availableCheckTypes = [
|
||||||
|
{"key": "github_release", "name": gettext("Release")},
|
||||||
|
{"key": "git_commit", "name": gettext("Commit")}
|
||||||
|
];
|
||||||
|
|
||||||
|
self.reloadOverlay = $("#reloadui_overlay");
|
||||||
|
|
||||||
self.versions = new ItemListHelper(
|
self.versions = new ItemListHelper(
|
||||||
"plugin.softwareupdate.versions",
|
"plugin.softwareupdate.versions",
|
||||||
{
|
{
|
||||||
@@ -78,19 +88,23 @@ $(function() {
|
|||||||
var data = {
|
var data = {
|
||||||
plugins: {
|
plugins: {
|
||||||
softwareupdate: {
|
softwareupdate: {
|
||||||
octoprint_restart_command: self.config_restartCommand(),
|
cache_ttl: parseInt(self.config_cacheTtl()),
|
||||||
environment_restart_command: self.config_rebootCommand(),
|
octoprint_checkout_folder: self.config_checkoutFolder(),
|
||||||
cache_ttl: parseInt(self.config_cacheTtl())
|
octoprint_type: self.config_checkType()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
self.settings.saveData(data, function() { self.configurationDialog.modal("hide"); self._copyConfig(); });
|
self.settings.saveData(data, function() {
|
||||||
|
self.configurationDialog.modal("hide");
|
||||||
|
self._copyConfig();
|
||||||
|
self.performCheck();
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
self._copyConfig = function() {
|
self._copyConfig = function() {
|
||||||
self.config_restartCommand(self.settings.settings.plugins.softwareupdate.octoprint_restart_command());
|
|
||||||
self.config_rebootCommand(self.settings.settings.plugins.softwareupdate.environment_restart_command());
|
|
||||||
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
|
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
|
||||||
|
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
|
||||||
|
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
|
||||||
};
|
};
|
||||||
|
|
||||||
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
|
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
|
||||||
@@ -109,6 +123,25 @@ $(function() {
|
|||||||
});
|
});
|
||||||
self.versions.updateItems(versions);
|
self.versions.updateItems(versions);
|
||||||
|
|
||||||
|
var octoprint = data.information["octoprint"];
|
||||||
|
if (octoprint && octoprint.hasOwnProperty("check")) {
|
||||||
|
var check = octoprint.check;
|
||||||
|
if (BRANCH != "master" && check["type"] == "github_release") {
|
||||||
|
self.octoprintUnreleased(true);
|
||||||
|
} else {
|
||||||
|
self.octoprintUnreleased(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var checkoutFolder = (check["checkout_folder"] || "").trim();
|
||||||
|
var updateFolder = (check["update_folder"] || "").trim();
|
||||||
|
var checkType = check["type"] || "";
|
||||||
|
if ((checkType == "github_release" || checkType == "git_commit") && checkoutFolder == "" && updateFolder == "") {
|
||||||
|
self.octoprintUnconfigured(true);
|
||||||
|
} else {
|
||||||
|
self.octoprintUnconfigured(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
||||||
var text = gettext("There are updates available for the following components:");
|
var text = gettext("There are updates available for the following components:");
|
||||||
|
|
||||||
@@ -298,18 +331,10 @@ $(function() {
|
|||||||
self.onDataUpdaterReconnect = function() {
|
self.onDataUpdaterReconnect = function() {
|
||||||
if (self.waitingForRestart) {
|
if (self.waitingForRestart) {
|
||||||
self.waitingForRestart = false;
|
self.waitingForRestart = false;
|
||||||
|
|
||||||
var options = {
|
|
||||||
title: gettext("Restart successful!"),
|
|
||||||
text: gettext("The server was restarted successfully. The page will now reload automatically."),
|
|
||||||
type: "success",
|
|
||||||
hide: false
|
|
||||||
};
|
|
||||||
self._showPopup(options);
|
|
||||||
self.updateInProgress = false;
|
self.updateInProgress = false;
|
||||||
|
if (!self.reloadOverlay.is(":visible")) {
|
||||||
var delay = 5 + Math.floor(Math.random() * 5) + 1;
|
self.reloadOverlay.show();
|
||||||
setTimeout(function() {location.reload(true);}, delay * 1000);
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,21 @@
|
|||||||
|
<div class="alert" data-bind="visible: octoprintUnconfigured()">{% trans %}
|
||||||
|
Please configure the <strong>checkout folder</strong> of OctoPrint, otherwise
|
||||||
|
this plugin won't be able to update it. Click on the <i class="icon-wrench"></i> button
|
||||||
|
to do this. Also refer to the <a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
|
||||||
|
{% endtrans %}</div>
|
||||||
|
<div class="alert" data-bind="visible: !octoprintUnconfigured() && octoprintUnreleased()">{% trans %}
|
||||||
|
<p>
|
||||||
|
<strong>You are running a non-release version of OctoPrint but are tracking OctoPrint
|
||||||
|
releases.</strong>
|
||||||
|
</p><p>
|
||||||
|
You probably want OctoPrint to track the matching development version instead.
|
||||||
|
If you have a local OctoPrint checkout folder switched to another branch,
|
||||||
|
<strong>simply switching over to "Commit" tracking</strong> will already
|
||||||
|
take care of that. Otherwise please take a look at the
|
||||||
|
<a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
|
||||||
|
</p>
|
||||||
|
{% endtrans %}</div>
|
||||||
|
|
||||||
<div class="pull-right">
|
<div class="pull-right">
|
||||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||||
</div>
|
</div>
|
||||||
@@ -11,7 +29,7 @@
|
|||||||
<span data-bind="invisible: !updateAvailable"><i class="icon-bell" title="{{ _('Update available') }}"></i></span>
|
<span data-bind="invisible: !updateAvailable"><i class="icon-bell" title="{{ _('Update available') }}"></i></span>
|
||||||
</td>
|
</td>
|
||||||
<td class="settings_plugin_softwareupdate_column_information">
|
<td class="settings_plugin_softwareupdate_column_information">
|
||||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span><br>
|
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="icon-exclamation-sign" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
|
||||||
<small class="muted">
|
<small class="muted">
|
||||||
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
|
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
|
||||||
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span>
|
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span>
|
||||||
@@ -44,7 +62,7 @@
|
|||||||
<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><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">
|
<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); }">{{ _('Force check for update (overrides cache used for update checks)') }}</button>
|
||||||
<button class="btn btn-block btn-danger" data-bind="click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -56,15 +74,15 @@
|
|||||||
<div class="modal-body">
|
<div class="modal-body">
|
||||||
<form class="form-horizontal">
|
<form class="form-horizontal">
|
||||||
<div class="control-group">
|
<div class="control-group">
|
||||||
<label class="control-label">{{ _('Restart Command') }}</label>
|
<label class="control-label">{{ _('OctoPrint checkout folder') }}</label>
|
||||||
<div class="controls">
|
<div class="controls">
|
||||||
<input type="text" class="input-block-level" data-bind="value: config_restartCommand">
|
<input type="text" class="input-block-level" data-bind="value: config_checkoutFolder">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="control-group">
|
<div class="control-group">
|
||||||
<label class="control-label">{{ _('Reboot Command') }}</label>
|
<label class="control-label">{{ _('OctoPrint version tracking') }}</label>
|
||||||
<div class="controls">
|
<div class="controls">
|
||||||
<input type="text" class="input-block-level" data-bind="value: config_rebootCommand">
|
<select data-bind="value: config_checkType, options: config_availableCheckTypes, optionsText: 'name', optionsValue: 'key'"></select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="control-group">
|
<div class="control-group">
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import logging
|
|||||||
import pkg_resources
|
import pkg_resources
|
||||||
|
|
||||||
from octoprint.util.pip import PipCaller, UnknownPip
|
from octoprint.util.pip import PipCaller, UnknownPip
|
||||||
|
from .. import exceptions
|
||||||
|
|
||||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
|
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
|
||||||
console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console")
|
console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console")
|
||||||
@@ -44,7 +45,7 @@ def perform_update(target, check, target_version):
|
|||||||
|
|
||||||
pip_caller = _get_pip_caller(command=pip_command)
|
pip_caller = _get_pip_caller(command=pip_command)
|
||||||
if pip_caller is None:
|
if pip_caller is None:
|
||||||
raise RuntimeError("Can't run pip")
|
raise exceptions.UpdateError("Can't run pip", None)
|
||||||
|
|
||||||
install_arg = check["pip"].format(target_version=target_version)
|
install_arg = check["pip"].format(target_version=target_version)
|
||||||
|
|
||||||
@@ -54,12 +55,16 @@ def perform_update(target, check, target_version):
|
|||||||
if "dependency_links" in check and check["dependency_links"] and pip_caller >= _pip_version_dependency_links:
|
if "dependency_links" in check and check["dependency_links"] and pip_caller >= _pip_version_dependency_links:
|
||||||
pip_args += ["--process-dependency-links"]
|
pip_args += ["--process-dependency-links"]
|
||||||
|
|
||||||
pip_caller.execute(*pip_args)
|
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||||
|
if returncode != 0:
|
||||||
|
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
|
||||||
|
|
||||||
logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
|
logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
|
||||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||||
|
|
||||||
pip_caller.execute(*pip_args)
|
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||||
|
if returncode != 0:
|
||||||
|
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
|
||||||
|
|
||||||
return "ok"
|
return "ok"
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,17 @@ from ..util import execute
|
|||||||
|
|
||||||
|
|
||||||
def can_perform_update(target, check):
|
def can_perform_update(target, check):
|
||||||
return "update_script" in check and ("checkout_folder" in check or "update_folder" in check)
|
import os
|
||||||
|
script_configured = bool("update_script" in check and check["update_script"])
|
||||||
|
|
||||||
|
folder = None
|
||||||
|
if "update_folder" in check:
|
||||||
|
folder = check["update_folder"]
|
||||||
|
elif "checkout_folder" in check:
|
||||||
|
folder = check["checkout_folder"]
|
||||||
|
folder_configured = bool(folder and os.path.isdir(folder))
|
||||||
|
|
||||||
|
return script_configured and folder_configured
|
||||||
|
|
||||||
|
|
||||||
def perform_update(target, check, target_version):
|
def perform_update(target, check, target_version):
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ class VirtualPrinter():
|
|||||||
self._heatupThread = None
|
self._heatupThread = None
|
||||||
|
|
||||||
self._okBeforeCommandOutput = settings().getBoolean(["devel", "virtualPrinter", "okBeforeCommandOutput"])
|
self._okBeforeCommandOutput = settings().getBoolean(["devel", "virtualPrinter", "okBeforeCommandOutput"])
|
||||||
|
self._supportM112 = settings().getBoolean(["devel", "virtualPrinter", "supportM112"])
|
||||||
|
|
||||||
self._sendWait = settings().getBoolean(["devel", "virtualPrinter", "sendWait"])
|
self._sendWait = settings().getBoolean(["devel", "virtualPrinter", "sendWait"])
|
||||||
self._waitInterval = settings().getFloat(["devel", "virtualPrinter", "waitInterval"])
|
self._waitInterval = settings().getFloat(["devel", "virtualPrinter", "waitInterval"])
|
||||||
@@ -83,6 +84,7 @@ class VirtualPrinter():
|
|||||||
|
|
||||||
self._action_hooks = plugin_manager().get_hooks("octoprint.plugin.virtual_printer.custom_action")
|
self._action_hooks = plugin_manager().get_hooks("octoprint.plugin.virtual_printer.custom_action")
|
||||||
|
|
||||||
|
self._killed = False
|
||||||
|
|
||||||
waitThread = threading.Thread(target=self._sendWaitAfterTimeout)
|
waitThread = threading.Thread(target=self._sendWaitAfterTimeout)
|
||||||
waitThread.start()
|
waitThread.start()
|
||||||
@@ -106,7 +108,7 @@ class VirtualPrinter():
|
|||||||
|
|
||||||
def _processIncoming(self):
|
def _processIncoming(self):
|
||||||
next_wait_timeout = time.time() + self._waitInterval
|
next_wait_timeout = time.time() + self._waitInterval
|
||||||
while self.incoming is not None:
|
while self.incoming is not None and not self._killed:
|
||||||
self._simulateTemps()
|
self._simulateTemps()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -266,9 +268,10 @@ class VirtualPrinter():
|
|||||||
elif "G92" in data:
|
elif "G92" in data:
|
||||||
self._setPosition(data)
|
self._setPosition(data)
|
||||||
|
|
||||||
elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3") \
|
elif data.startswith("G28"):
|
||||||
or data.startswith("G28") or data.startswith("G29") or data.startswith("G30") \
|
self._performMove(data)
|
||||||
or data.startswith("G31") or data.startswith("G32"):
|
|
||||||
|
elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3"):
|
||||||
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
|
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
|
||||||
self.buffered.put(data)
|
self.buffered.put(data)
|
||||||
|
|
||||||
@@ -291,6 +294,12 @@ class VirtualPrinter():
|
|||||||
if len(data.strip()) > 0 and not self._okBeforeCommandOutput:
|
if len(data.strip()) > 0 and not self._okBeforeCommandOutput:
|
||||||
self._sendOk()
|
self._sendOk()
|
||||||
|
|
||||||
|
def _kill(self):
|
||||||
|
if not self._supportM112:
|
||||||
|
return
|
||||||
|
self._killed = True
|
||||||
|
self.outgoing.put("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
|
||||||
|
|
||||||
def _triggerResend(self, expected=None, actual=None):
|
def _triggerResend(self, expected=None, actual=None):
|
||||||
with self._incoming_lock:
|
with self._incoming_lock:
|
||||||
if expected is None:
|
if expected is None:
|
||||||
@@ -303,8 +312,13 @@ class VirtualPrinter():
|
|||||||
else:
|
else:
|
||||||
self.outgoing.put("Error: expected line %d got %d" % (expected, actual))
|
self.outgoing.put("Error: expected line %d got %d" % (expected, actual))
|
||||||
|
|
||||||
self.outgoing.put("Resend:%d" % expected)
|
def request_resend():
|
||||||
self.outgoing.put("ok")
|
self.outgoing.put("Resend:%d" % expected)
|
||||||
|
self.outgoing.put("ok")
|
||||||
|
|
||||||
|
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
|
||||||
|
request_resend()
|
||||||
|
request_resend()
|
||||||
|
|
||||||
def _debugTrigger(self, data):
|
def _debugTrigger(self, data):
|
||||||
if data == "action_pause":
|
if data == "action_pause":
|
||||||
@@ -516,14 +530,10 @@ class VirtualPrinter():
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
if duration:
|
if duration:
|
||||||
if settings().getBoolean(["devel", "virtualPrinter", "waitOnLongMoves"]):
|
slept = 0
|
||||||
slept = 0
|
while duration - slept > self._read_timeout and not self._killed:
|
||||||
while duration - slept > self._read_timeout:
|
time.sleep(self._read_timeout)
|
||||||
time.sleep(self._read_timeout)
|
slept += self._read_timeout
|
||||||
self.outgoing.put("wait")
|
|
||||||
slept += self._read_timeout
|
|
||||||
else:
|
|
||||||
time.sleep(duration)
|
|
||||||
|
|
||||||
def _setPosition(self, line):
|
def _setPosition(self, line):
|
||||||
matchX = re.search("X([0-9.]+)", line)
|
matchX = re.search("X([0-9.]+)", line)
|
||||||
@@ -577,6 +587,9 @@ class VirtualPrinter():
|
|||||||
self._selectedSdFilePos = 0
|
self._selectedSdFilePos = 0
|
||||||
with open(self._selectedSdFile, "r") as f:
|
with open(self._selectedSdFile, "r") as f:
|
||||||
for line in iter(f.readline, ""):
|
for line in iter(f.readline, ""):
|
||||||
|
if self._killed:
|
||||||
|
break
|
||||||
|
|
||||||
# reset position if requested by client
|
# reset position if requested by client
|
||||||
if self._newSdFilePos is not None:
|
if self._newSdFilePos is not None:
|
||||||
f.seek(self._newSdFilePos)
|
f.seek(self._newSdFilePos)
|
||||||
@@ -606,12 +619,12 @@ class VirtualPrinter():
|
|||||||
delay = 1
|
delay = 1
|
||||||
if heater.startswith("tool"):
|
if heater.startswith("tool"):
|
||||||
toolNum = int(heater[len("tool"):])
|
toolNum = int(heater[len("tool"):])
|
||||||
while self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta:
|
while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta):
|
||||||
self._simulateTemps(delta=delta)
|
self._simulateTemps(delta=delta)
|
||||||
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
|
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
|
||||||
time.sleep(delay)
|
time.sleep(delay)
|
||||||
elif heater == "bed":
|
elif heater == "bed":
|
||||||
while self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta:
|
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta):
|
||||||
self._simulateTemps(delta=delta)
|
self._simulateTemps(delta=delta)
|
||||||
self.outgoing.put("B:%0.2f" % self.bedTemp)
|
self.outgoing.put("B:%0.2f" % self.bedTemp)
|
||||||
time.sleep(delay)
|
time.sleep(delay)
|
||||||
@@ -662,6 +675,11 @@ class VirtualPrinter():
|
|||||||
with self._incoming_lock:
|
with self._incoming_lock:
|
||||||
if self.incoming is None or self.outgoing is None:
|
if self.incoming is None or self.outgoing is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if "M112" in data and self._supportM112:
|
||||||
|
self._kill()
|
||||||
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.incoming.put(data, timeout=self._write_timeout)
|
self.incoming.put(data, timeout=self._write_timeout)
|
||||||
except Queue.Full:
|
except Queue.Full:
|
||||||
@@ -685,6 +703,9 @@ class VirtualPrinter():
|
|||||||
self.buffered = None
|
self.buffered = None
|
||||||
|
|
||||||
def _sendOk(self):
|
def _sendOk(self):
|
||||||
|
if self.outgoing is None:
|
||||||
|
return
|
||||||
|
|
||||||
if settings().getBoolean(["devel", "virtualPrinter", "okWithLinenumber"]):
|
if settings().getBoolean(["devel", "virtualPrinter", "okWithLinenumber"]):
|
||||||
self.outgoing.put("ok %d" % self.lastN)
|
self.outgoing.put("ok %d" % self.lastN)
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -329,12 +329,14 @@ class PrinterProfileManager(object):
|
|||||||
if os.path.exists(path) and not allow_overwrite:
|
if os.path.exists(path) and not allow_overwrite:
|
||||||
raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"])
|
raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"])
|
||||||
|
|
||||||
|
from octoprint.util import atomic_write
|
||||||
import yaml
|
import yaml
|
||||||
with open(path, "wb") as f:
|
try:
|
||||||
try:
|
with atomic_write(path, "wb") as f:
|
||||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
|
self._logger.exception("Error while trying to save profile %s" % profile["id"])
|
||||||
|
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
|
||||||
|
|
||||||
def _remove_from_path(self, path):
|
def _remove_from_path(self, path):
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -389,6 +389,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
|||||||
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
|
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
|
||||||
|
|
||||||
self._lastProgressReport = None
|
self._lastProgressReport = None
|
||||||
|
self._setProgressData(0, None, None, None)
|
||||||
self._setCurrentZ(None)
|
self._setCurrentZ(None)
|
||||||
self._comm.startPrint()
|
self._comm.startPrint()
|
||||||
|
|
||||||
@@ -679,7 +680,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
|||||||
# Use a string for mtime because it could be float and the
|
# Use a string for mtime because it could be float and the
|
||||||
# javascript needs to exact match
|
# javascript needs to exact match
|
||||||
if not sd:
|
if not sd:
|
||||||
date = int(os.stat(path_on_disk).st_ctime)
|
date = int(os.stat(path_on_disk).st_mtime)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
|
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ def on_identity_loaded(sender, identity):
|
|||||||
if user is None:
|
if user is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
identity.provides.add(UserNeed(user.get_name()))
|
identity.provides.add(UserNeed(user.get_id()))
|
||||||
if user.is_user():
|
if user.is_user():
|
||||||
identity.provides.add(RoleNeed("user"))
|
identity.provides.add(RoleNeed("user"))
|
||||||
if user.is_admin():
|
if user.is_admin():
|
||||||
@@ -98,9 +98,9 @@ def load_user(id):
|
|||||||
|
|
||||||
if userManager is not None:
|
if userManager is not None:
|
||||||
if sessionid:
|
if sessionid:
|
||||||
return userManager.findUser(username=id, session=sessionid)
|
return userManager.findUser(userid=id, session=sessionid)
|
||||||
else:
|
else:
|
||||||
return userManager.findUser(username=id)
|
return userManager.findUser(userid=id)
|
||||||
return users.DummyUser()
|
return users.DummyUser()
|
||||||
|
|
||||||
|
|
||||||
@@ -330,13 +330,34 @@ class Server():
|
|||||||
|
|
||||||
upload_suffixes = dict(name=s.get(["server", "uploads", "nameSuffix"]), path=s.get(["server", "uploads", "pathSuffix"]))
|
upload_suffixes = dict(name=s.get(["server", "uploads", "nameSuffix"]), path=s.get(["server", "uploads", "pathSuffix"]))
|
||||||
|
|
||||||
|
def mime_type_guesser(path):
|
||||||
|
from octoprint.filemanager import get_mime_type
|
||||||
|
return get_mime_type(path)
|
||||||
|
|
||||||
|
download_handler_kwargs = dict(
|
||||||
|
as_attachment=True,
|
||||||
|
allow_client_caching=False
|
||||||
|
)
|
||||||
|
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
|
||||||
|
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
|
||||||
|
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not os.path.basename(path).startswith("."), status_code=404))
|
||||||
|
|
||||||
|
def joined_dict(*dicts):
|
||||||
|
if not len(dicts):
|
||||||
|
return dict()
|
||||||
|
|
||||||
|
joined = dict()
|
||||||
|
for d in dicts:
|
||||||
|
joined.update(d)
|
||||||
|
return joined
|
||||||
|
|
||||||
server_routes = self._router.urls + [
|
server_routes = self._router.urls + [
|
||||||
# various downloads
|
# various downloads
|
||||||
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("timelapse"), as_attachment=True)),
|
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("timelapse")), download_handler_kwargs, no_hidden_files_validator)),
|
||||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("uploads"), as_attachment=True, path_validation=util.tornado.path_validation_factory(lambda path: not os.path.basename(path).startswith("."), status_code=404))),
|
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("uploads")), download_handler_kwargs, no_hidden_files_validator, additional_mime_types)),
|
||||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("logs"), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))),
|
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("logs")), download_handler_kwargs, admin_validator)),
|
||||||
# camera snapshot
|
# camera snapshot
|
||||||
(r"/downloads/camera/current", util.tornado.UrlForwardHandler, dict(url=s.get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
|
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, dict(url=s.get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
|
||||||
# generated webassets
|
# generated webassets
|
||||||
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("generated"), "webassets")))
|
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("generated"), "webassets")))
|
||||||
]
|
]
|
||||||
@@ -736,16 +757,58 @@ class Server():
|
|||||||
# clean the folder
|
# clean the folder
|
||||||
if settings().getBoolean(["devel", "webassets", "clean_on_startup"]):
|
if settings().getBoolean(["devel", "webassets", "clean_on_startup"]):
|
||||||
import shutil
|
import shutil
|
||||||
|
import errno
|
||||||
|
import sys
|
||||||
|
|
||||||
for entry in ("webassets", ".webassets-cache"):
|
for entry in ("webassets", ".webassets-cache"):
|
||||||
path = os.path.join(base_folder, entry)
|
path = os.path.join(base_folder, entry)
|
||||||
self._logger.debug("Deleting {path}...".format(**locals()))
|
|
||||||
|
# delete path if it exists
|
||||||
if os.path.isdir(path):
|
if os.path.isdir(path):
|
||||||
shutil.rmtree(path, ignore_errors=True)
|
|
||||||
elif os.path.isfile(path):
|
|
||||||
try:
|
try:
|
||||||
os.remove(path)
|
self._logger.debug("Deleting {path}...".format(**locals()))
|
||||||
|
shutil.rmtree(path)
|
||||||
except:
|
except:
|
||||||
self._logger.exception("Exception while trying to delete {entry} from {base_folder}".format(**locals()))
|
self._logger.exception("Error while trying to delete {path}, leaving it alone".format(**locals()))
|
||||||
|
continue
|
||||||
|
|
||||||
|
# re-create path
|
||||||
|
self._logger.debug("Creating {path}...".format(**locals()))
|
||||||
|
error_text = "Error while trying to re-create {path}, that might cause errors with the webassets cache".format(**locals())
|
||||||
|
try:
|
||||||
|
os.makedirs(path)
|
||||||
|
except OSError as e:
|
||||||
|
if e.errno == errno.EACCES:
|
||||||
|
# that might be caused by the user still having the folder open somewhere, let's try again after
|
||||||
|
# waiting a bit
|
||||||
|
import time
|
||||||
|
for n in xrange(3):
|
||||||
|
time.sleep(0.5)
|
||||||
|
self._logger.debug("Creating {path}: Retry #{retry} after {time}s".format(path=path, retry=n+1, time=(n + 1)*0.5))
|
||||||
|
try:
|
||||||
|
os.makedirs(path)
|
||||||
|
break
|
||||||
|
except:
|
||||||
|
if self._logger.isEnabledFor(logging.DEBUG):
|
||||||
|
self._logger.exception("Ignored error while creating directory {path}".format(**locals()))
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
# this will only get executed if we never did
|
||||||
|
# successfully execute makedirs above
|
||||||
|
self._logger.exception(error_text)
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
# not an access error, so something we don't understand
|
||||||
|
# went wrong -> log an error and stop
|
||||||
|
self._logger.exception(error_text)
|
||||||
|
continue
|
||||||
|
except:
|
||||||
|
# not an OSError, so something we don't understand
|
||||||
|
# went wrong -> log an error and stop
|
||||||
|
self._logger.exception(error_text)
|
||||||
|
continue
|
||||||
|
|
||||||
|
self._logger.info("Reset webasset folder {path}...".format(**locals()))
|
||||||
|
|
||||||
AdjustedEnvironment = type(Environment)(Environment.__name__, (Environment,), dict(
|
AdjustedEnvironment = type(Environment)(Environment.__name__, (Environment,), dict(
|
||||||
resolver_class=util.flask.PluginAssetResolver
|
resolver_class=util.flask.PluginAssetResolver
|
||||||
@@ -764,12 +827,10 @@ class Server():
|
|||||||
assets.updater = UpdaterType
|
assets.updater = UpdaterType
|
||||||
|
|
||||||
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
|
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
|
||||||
enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
|
|
||||||
preferred_stylesheet = settings().get(["devel", "stylesheet"])
|
preferred_stylesheet = settings().get(["devel", "stylesheet"])
|
||||||
|
|
||||||
dynamic_assets = util.flask.collect_plugin_assets(
|
dynamic_assets = util.flask.collect_plugin_assets(
|
||||||
enable_gcodeviewer=enable_gcodeviewer,
|
enable_gcodeviewer=enable_gcodeviewer,
|
||||||
enable_timelapse=enable_timelapse,
|
|
||||||
preferred_stylesheet=preferred_stylesheet
|
preferred_stylesheet=preferred_stylesheet
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import octoprint.server
|
|||||||
import octoprint.plugin
|
import octoprint.plugin
|
||||||
from octoprint.server import admin_permission, NO_CONTENT
|
from octoprint.server import admin_permission, NO_CONTENT
|
||||||
from octoprint.settings import settings as s, valid_boolean_trues
|
from octoprint.settings import settings as s, valid_boolean_trues
|
||||||
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
|
from octoprint.server.util import noCachingResponseHandler, apiKeyRequestHandler, corsResponseHandler
|
||||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
|
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
|
||||||
|
|
||||||
|
|
||||||
@@ -42,6 +42,8 @@ from . import languages as api_languages
|
|||||||
|
|
||||||
VERSION = "0.1"
|
VERSION = "0.1"
|
||||||
|
|
||||||
|
api.after_request(noCachingResponseHandler)
|
||||||
|
|
||||||
api.before_request(apiKeyRequestHandler)
|
api.before_request(apiKeyRequestHandler)
|
||||||
api.after_request(corsResponseHandler)
|
api.after_request(corsResponseHandler)
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
|||||||
|
|
||||||
from flask import request, jsonify, make_response, url_for
|
from flask import request, jsonify, make_response, url_for
|
||||||
|
|
||||||
import octoprint.util as util
|
|
||||||
from octoprint.filemanager.destinations import FileDestinations
|
from octoprint.filemanager.destinations import FileDestinations
|
||||||
from octoprint.settings import settings, valid_boolean_trues
|
from octoprint.settings import settings, valid_boolean_trues
|
||||||
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
|
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
|
||||||
@@ -18,6 +17,8 @@ import octoprint.filemanager
|
|||||||
import octoprint.filemanager.util
|
import octoprint.filemanager.util
|
||||||
import octoprint.slicing
|
import octoprint.slicing
|
||||||
|
|
||||||
|
import psutil
|
||||||
|
|
||||||
|
|
||||||
#~~ GCODE file handling
|
#~~ GCODE file handling
|
||||||
|
|
||||||
@@ -29,7 +30,8 @@ def readGcodeFiles():
|
|||||||
filter = request.values["filter"]
|
filter = request.values["filter"]
|
||||||
files = _getFileList(FileDestinations.LOCAL, filter=filter)
|
files = _getFileList(FileDestinations.LOCAL, filter=filter)
|
||||||
files.extend(_getFileList(FileDestinations.SDCARD))
|
files.extend(_getFileList(FileDestinations.SDCARD))
|
||||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
|
||||||
|
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||||
|
|
||||||
|
|
||||||
@api.route("/files/<string:origin>", methods=["GET"])
|
@api.route("/files/<string:origin>", methods=["GET"])
|
||||||
@@ -40,7 +42,8 @@ def readGcodeFilesForOrigin(origin):
|
|||||||
files = _getFileList(origin)
|
files = _getFileList(origin)
|
||||||
|
|
||||||
if origin == FileDestinations.LOCAL:
|
if origin == FileDestinations.LOCAL:
|
||||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
|
||||||
|
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||||
else:
|
else:
|
||||||
return jsonify(files=files)
|
return jsonify(files=files)
|
||||||
|
|
||||||
|
|||||||
@@ -15,15 +15,18 @@ from octoprint.settings import settings
|
|||||||
from octoprint.server import NO_CONTENT, admin_permission
|
from octoprint.server import NO_CONTENT, admin_permission
|
||||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||||
from octoprint.server.api import api
|
from octoprint.server.api import api
|
||||||
from octoprint.util import get_free_bytes
|
|
||||||
|
|
||||||
|
|
||||||
@api.route("/logs", methods=["GET"])
|
@api.route("/logs", methods=["GET"])
|
||||||
@restricted_access
|
@restricted_access
|
||||||
@admin_permission.require(403)
|
@admin_permission.require(403)
|
||||||
def getLogFiles():
|
def getLogFiles():
|
||||||
|
import psutil
|
||||||
|
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
|
||||||
|
|
||||||
files = _getLogFiles()
|
files = _getLogFiles()
|
||||||
return jsonify(files=files, free=get_free_bytes(settings().getBaseFolder("logs")))
|
|
||||||
|
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||||
|
|
||||||
|
|
||||||
@api.route("/logs/<path:filename>", methods=["GET"])
|
@api.route("/logs/<path:filename>", methods=["GET"])
|
||||||
|
|||||||
@@ -69,7 +69,8 @@ def getSettings():
|
|||||||
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
|
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
|
||||||
"externalHeatupDetection": s.getBoolean(["feature", "externalHeatupDetection"]),
|
"externalHeatupDetection": s.getBoolean(["feature", "externalHeatupDetection"]),
|
||||||
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
|
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
|
||||||
"pollWatched": s.getBoolean(["feature", "pollWatched"])
|
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
|
||||||
|
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"])
|
||||||
},
|
},
|
||||||
"serial": {
|
"serial": {
|
||||||
"port": connectionOptions["portPreference"],
|
"port": connectionOptions["portPreference"],
|
||||||
@@ -112,6 +113,17 @@ def getSettings():
|
|||||||
"afterPrintResumed": None,
|
"afterPrintResumed": None,
|
||||||
"snippets": dict()
|
"snippets": dict()
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"server": {
|
||||||
|
"commands": {
|
||||||
|
"systemShutdownCommand": s.get(["server", "commands", "systemShutdownCommand"]),
|
||||||
|
"systemRestartCommand": s.get(["server", "commands", "systemRestartCommand"]),
|
||||||
|
"serverRestartCommand": s.get(["server", "commands", "serverRestartCommand"])
|
||||||
|
},
|
||||||
|
"diskspace": {
|
||||||
|
"warning": s.getInt(["server", "diskspace", "warning"]),
|
||||||
|
"critical": s.getInt(["server", "diskspace", "critical"])
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,6 +213,7 @@ def setSettings():
|
|||||||
if "externalHeatupDetection" in data["feature"].keys(): s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
|
if "externalHeatupDetection" in data["feature"].keys(): s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
|
||||||
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
|
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
|
||||||
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
|
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 "serial" in data.keys():
|
if "serial" in data.keys():
|
||||||
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||||
@@ -250,6 +263,15 @@ def setSettings():
|
|||||||
continue
|
continue
|
||||||
s.saveScript("gcode", name, script.replace("\r\n", "\n").replace("\r", "\n"))
|
s.saveScript("gcode", name, script.replace("\r\n", "\n").replace("\r", "\n"))
|
||||||
|
|
||||||
|
if "server" in data:
|
||||||
|
if "commands" in data["server"]:
|
||||||
|
if "systemShutdownCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
|
||||||
|
if "systemRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
|
||||||
|
if "serverRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
|
||||||
|
if "diskspace" in data["server"]:
|
||||||
|
if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"])
|
||||||
|
if "critical" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"])
|
||||||
|
|
||||||
if "plugins" in data:
|
if "plugins" in data:
|
||||||
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
|
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
|
||||||
plugin_id = plugin._identifier
|
plugin_id = plugin._identifier
|
||||||
|
|||||||
@@ -29,14 +29,14 @@ def getTimelapseData():
|
|||||||
config = {"type": "off"}
|
config = {"type": "off"}
|
||||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||||
config["type"] = "zchange"
|
config["type"] = "zchange"
|
||||||
config["postRoll"] = timelapse.postRoll()
|
config["postRoll"] = timelapse.post_roll
|
||||||
config["fps"] = timelapse.fps()
|
config["fps"] = timelapse.fps
|
||||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||||
config["type"] = "timed"
|
config["type"] = "timed"
|
||||||
config["postRoll"] = timelapse.postRoll()
|
config["postRoll"] = timelapse.post_roll
|
||||||
config["fps"] = timelapse.fps()
|
config["fps"] = timelapse.fps
|
||||||
config.update({
|
config.update({
|
||||||
"interval": timelapse.interval()
|
"interval": timelapse.interval
|
||||||
})
|
})
|
||||||
|
|
||||||
files = octoprint.timelapse.getFinishedTimelapses()
|
files = octoprint.timelapse.getFinishedTimelapses()
|
||||||
|
|||||||
@@ -10,10 +10,15 @@ from flask import Blueprint, request, make_response, jsonify
|
|||||||
|
|
||||||
import octoprint.server
|
import octoprint.server
|
||||||
import octoprint.plugin
|
import octoprint.plugin
|
||||||
|
|
||||||
|
from octoprint.server.util import noCachingResponseHandler, corsResponseHandler
|
||||||
from octoprint.settings import settings as s
|
from octoprint.settings import settings as s
|
||||||
|
|
||||||
apps = Blueprint("apps", __name__)
|
apps = Blueprint("apps", __name__)
|
||||||
|
|
||||||
|
apps.after_request(noCachingResponseHandler)
|
||||||
|
apps.after_request(corsResponseHandler)
|
||||||
|
|
||||||
@apps.route("/auth", methods=["GET"])
|
@apps.route("/auth", methods=["GET"])
|
||||||
def getSessionKey():
|
def getSessionKey():
|
||||||
unverified_key, valid_until = octoprint.server.appSessionManager.create()
|
unverified_key, valid_until = octoprint.server.appSessionManager.create()
|
||||||
|
|||||||
@@ -80,6 +80,18 @@ def corsResponseHandler(resp):
|
|||||||
return resp
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
def noCachingResponseHandler(resp):
|
||||||
|
"""
|
||||||
|
``after_request`` handler for blueprints which shall set no caching headers
|
||||||
|
on their responses.
|
||||||
|
|
||||||
|
Sets ``Cache-Control``, ``Pragma`` and ``Expires`` headers accordingly
|
||||||
|
to prevent all client side caching from taking place.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return flask.add_non_caching_response_headers(resp)
|
||||||
|
|
||||||
|
|
||||||
def optionsAllowOrigin(request):
|
def optionsAllowOrigin(request):
|
||||||
"""
|
"""
|
||||||
Shortcut for request handling for CORS OPTIONS requests to set CORS headers.
|
Shortcut for request handling for CORS OPTIONS requests to set CORS headers.
|
||||||
|
|||||||
@@ -123,12 +123,19 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
|
|||||||
|
|
||||||
def fix_webassets_cache():
|
def fix_webassets_cache():
|
||||||
from webassets import cache
|
from webassets import cache
|
||||||
import os
|
|
||||||
import tempfile
|
error_logger = logging.getLogger(__name__ + ".fix_webassets_cache")
|
||||||
import pickle
|
|
||||||
import shutil
|
|
||||||
|
|
||||||
def fixed_set(self, key, data):
|
def fixed_set(self, key, data):
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import pickle
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
if not os.path.exists(self.directory):
|
||||||
|
error_logger.warn("Cache directory {} doesn't exist, not going "
|
||||||
|
"to attempt to write cache file".format(self.directory))
|
||||||
|
|
||||||
md5 = '%s' % cache.make_md5(self.V, key)
|
md5 = '%s' % cache.make_md5(self.V, key)
|
||||||
filename = os.path.join(self.directory, md5)
|
filename = os.path.join(self.directory, md5)
|
||||||
fd, temp_filename = tempfile.mkstemp(prefix='.' + md5,
|
fd, temp_filename = tempfile.mkstemp(prefix='.' + md5,
|
||||||
@@ -148,6 +155,11 @@ def fix_webassets_cache():
|
|||||||
import warnings
|
import warnings
|
||||||
from webassets.cache import make_md5
|
from webassets.cache import make_md5
|
||||||
|
|
||||||
|
if not os.path.exists(self.directory):
|
||||||
|
error_logger.warn("Cache directory {} doesn't exist, not going "
|
||||||
|
"to attempt to read cache file".format(self.directory))
|
||||||
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
hash = make_md5(self.V, key)
|
hash = make_md5(self.V, key)
|
||||||
except IOError as e:
|
except IOError as e:
|
||||||
@@ -194,12 +206,15 @@ def fix_webassets_filtertool():
|
|||||||
try:
|
try:
|
||||||
content = func().getvalue()
|
content = func().getvalue()
|
||||||
if self.cache:
|
if self.cache:
|
||||||
log.debug('Storing result in cache with key %s', key,)
|
try:
|
||||||
self.cache.set(key, content)
|
log.debug('Storing result in cache with key %s', key,)
|
||||||
|
self.cache.set(key, content)
|
||||||
|
except:
|
||||||
|
error_logger.exception("Got an exception while trying to save file to cache, not caching")
|
||||||
return MemoryHunk(content)
|
return MemoryHunk(content)
|
||||||
except:
|
except:
|
||||||
error_logger.exception("Got an exception while trying to apply filter, ignoring file")
|
error_logger.exception("Got an exception while trying to apply filter, ignoring file")
|
||||||
return MemoryHunk("")
|
return MemoryHunk(u"")
|
||||||
|
|
||||||
FilterTool._wrap_cache = fixed_wrap_cache
|
FilterTool._wrap_cache = fixed_wrap_cache
|
||||||
|
|
||||||
@@ -212,8 +227,10 @@ def passive_login():
|
|||||||
user = flask.ext.login.current_user
|
user = flask.ext.login.current_user
|
||||||
|
|
||||||
if user is not None and not user.is_anonymous():
|
if user is not None and not user.is_anonymous():
|
||||||
flask.g.user = user
|
|
||||||
flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id()))
|
flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id()))
|
||||||
|
if hasattr(user, "get_session"):
|
||||||
|
flask.session["usersession.id"] = user.get_session()
|
||||||
|
flask.g.user = user
|
||||||
return flask.jsonify(user.asDict())
|
return flask.jsonify(user.asDict())
|
||||||
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
|
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
|
||||||
and settings().get(["accessControl", "autologinAs"]) is not None \
|
and settings().get(["accessControl", "autologinAs"]) is not None \
|
||||||
@@ -237,7 +254,7 @@ def passive_login():
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
|
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
|
||||||
|
|
||||||
return ("", 204)
|
return "", 204
|
||||||
|
|
||||||
|
|
||||||
#~~ cache decorator for cacheable views
|
#~~ cache decorator for cacheable views
|
||||||
@@ -307,6 +324,14 @@ def cache_check_response_headers(response):
|
|||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def add_non_caching_response_headers(response):
|
||||||
|
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0"
|
||||||
|
response.headers["Pragma"] = "no-cache"
|
||||||
|
response.headers["Expires"] = "-1"
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
#~~ access validators for use with tornado
|
#~~ access validators for use with tornado
|
||||||
|
|
||||||
|
|
||||||
@@ -505,7 +530,8 @@ def get_remote_address(request):
|
|||||||
|
|
||||||
|
|
||||||
def get_json_command_from_request(request, valid_commands):
|
def get_json_command_from_request(request, valid_commands):
|
||||||
if not "application/json" in request.headers["Content-Type"]:
|
content_type = request.headers.get("Content-Type", None)
|
||||||
|
if content_type is None or not "application/json" in content_type:
|
||||||
return None, None, make_response("Expected content-type JSON", 400)
|
return None, None, make_response("Expected content-type JSON", 400)
|
||||||
|
|
||||||
data = request.json
|
data = request.json
|
||||||
@@ -585,7 +611,7 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
|
|||||||
|
|
||||||
##~~ plugin assets collector
|
##~~ plugin assets collector
|
||||||
|
|
||||||
def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, preferred_stylesheet="css"):
|
def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||||
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
|
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
|
||||||
|
|
||||||
supported_stylesheets = ("css", "less")
|
supported_stylesheets = ("css", "less")
|
||||||
@@ -608,6 +634,7 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
|||||||
'js/app/viewmodels/slicing.js',
|
'js/app/viewmodels/slicing.js',
|
||||||
'js/app/viewmodels/temperature.js',
|
'js/app/viewmodels/temperature.js',
|
||||||
'js/app/viewmodels/terminal.js',
|
'js/app/viewmodels/terminal.js',
|
||||||
|
'js/app/viewmodels/timelapse.js',
|
||||||
'js/app/viewmodels/users.js',
|
'js/app/viewmodels/users.js',
|
||||||
'js/app/viewmodels/log.js',
|
'js/app/viewmodels/log.js',
|
||||||
'js/app/viewmodels/usersettings.js'
|
'js/app/viewmodels/usersettings.js'
|
||||||
@@ -619,8 +646,6 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
|||||||
'gcodeviewer/js/gCodeReader.js',
|
'gcodeviewer/js/gCodeReader.js',
|
||||||
'gcodeviewer/js/renderer.js'
|
'gcodeviewer/js/renderer.js'
|
||||||
]
|
]
|
||||||
if enable_timelapse:
|
|
||||||
assets["js"].append('js/app/viewmodels/timelapse.js')
|
|
||||||
|
|
||||||
if preferred_stylesheet == "less":
|
if preferred_stylesheet == "less":
|
||||||
assets["less"].append('less/octoprint.less')
|
assets["less"].append('less/octoprint.less')
|
||||||
|
|||||||
@@ -59,7 +59,13 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
|
|||||||
plugin_hash.update(",".join(ui_plugins))
|
plugin_hash.update(",".join(ui_plugins))
|
||||||
|
|
||||||
# connected => update the API key, might be necessary if the client was left open while the server restarted
|
# connected => update the API key, might be necessary if the client was left open while the server restarted
|
||||||
self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION, "plugin_hash": plugin_hash.hexdigest()})
|
self._emit("connected", {
|
||||||
|
"apikey": octoprint.server.UI_API_KEY,
|
||||||
|
"version": octoprint.server.VERSION,
|
||||||
|
"display_version": octoprint.server.DISPLAY_VERSION,
|
||||||
|
"branch": octoprint.server.BRANCH,
|
||||||
|
"plugin_hash": plugin_hash.hexdigest()
|
||||||
|
})
|
||||||
|
|
||||||
self._printer.register_callback(self)
|
self._printer.register_callback(self)
|
||||||
self._fileManager.register_slicingprogress_callback(self)
|
self._fileManager.register_slicingprogress_callback(self)
|
||||||
|
|||||||
@@ -360,13 +360,24 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
|||||||
for name, part in self._parts.iteritems():
|
for name, part in self._parts.iteritems():
|
||||||
if "filename" in part:
|
if "filename" in part:
|
||||||
# add form fields for filename, path, size and content_type for all files contained in the request
|
# add form fields for filename, path, size and content_type for all files contained in the request
|
||||||
fields = dict((self._suffixes[key], value) for (key, value) in dict(name=part["filename"], path=part["path"], size=str(os.stat(part["path"]).st_size), content_type=part["content_type"]).iteritems())
|
if not "path" in part:
|
||||||
|
continue
|
||||||
|
|
||||||
|
parameters = dict(
|
||||||
|
name=part["filename"],
|
||||||
|
path=part["path"],
|
||||||
|
size=str(os.stat(part["path"]).st_size)
|
||||||
|
)
|
||||||
|
if "content_type" in part:
|
||||||
|
parameters["content_type"] = part["content_type"]
|
||||||
|
|
||||||
|
fields = dict((self._suffixes[key], value) for (key, value) in parameters.iteritems())
|
||||||
for n, p in fields.iteritems():
|
for n, p in fields.iteritems():
|
||||||
key = name + "." + n
|
key = name + "." + n
|
||||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||||
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key
|
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key
|
||||||
self._new_body += b"\r\n"
|
self._new_body += b"\r\n"
|
||||||
self._new_body += p + b"\r\n"
|
self._new_body += b"%s\r\n" % p
|
||||||
elif "data" in part:
|
elif "data" in part:
|
||||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||||
value = part["data"]
|
value = part["data"]
|
||||||
@@ -757,6 +768,8 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
|||||||
:class:``~tornado.web.StaticFileHandler`` as the ``default_filename`` keyword parameter). Defaults to ``None``.
|
:class:``~tornado.web.StaticFileHandler`` as the ``default_filename`` keyword parameter). Defaults to ``None``.
|
||||||
as_attachment (bool): Whether to serve requested files with ``Content-Disposition: attachment`` header (``True``)
|
as_attachment (bool): Whether to serve requested files with ``Content-Disposition: attachment`` header (``True``)
|
||||||
or not. Defaults to ``False``.
|
or not. Defaults to ``False``.
|
||||||
|
allow_client_caching (bool): Whether to allow the client to cache (by not setting any ``Cache-Control`` or
|
||||||
|
``Expires`` headers on the response) or not.
|
||||||
access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will
|
access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will
|
||||||
be called with ``self.request`` as parameter which contains the full tornado request object. Should raise
|
be called with ``self.request`` as parameter which contains the full tornado request object. Should raise
|
||||||
a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed.
|
a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed.
|
||||||
@@ -765,13 +778,22 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
|||||||
with the requested path as parameter. Should raise a ``tornado.web.HTTPError`` (e.g. an 404) if the requested
|
with the requested path as parameter. Should raise a ``tornado.web.HTTPError`` (e.g. an 404) if the requested
|
||||||
path does not pass validation in which case the request will not be further processed.
|
path does not pass validation in which case the request will not be further processed.
|
||||||
Defaults to ``None`` and hence no path validation being performed.
|
Defaults to ``None`` and hence no path validation being performed.
|
||||||
|
etag_generator (function): Callback to call for generating the value of the ETag response header. Will be
|
||||||
|
called with the response handler as parameter. May return ``None`` to prevent the ETag response header
|
||||||
|
from being set. If not provided the last modified time of the file in question will be used as returned
|
||||||
|
by ``get_content_version``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None, path_validation=None):
|
def initialize(self, path, default_filename=None, as_attachment=False, allow_client_caching=True,
|
||||||
|
access_validation=None, path_validation=None, etag_generator=None,
|
||||||
|
mime_type_guesser=None):
|
||||||
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
|
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
|
||||||
self._as_attachment = as_attachment
|
self._as_attachment = as_attachment
|
||||||
|
self._allow_client_caching = allow_client_caching
|
||||||
self._access_validation = access_validation
|
self._access_validation = access_validation
|
||||||
self._path_validation = path_validation
|
self._path_validation = path_validation
|
||||||
|
self._etag_generator = etag_generator
|
||||||
|
self._mime_type_guesser = mime_type_guesser
|
||||||
|
|
||||||
def get(self, path, include_body=True):
|
def get(self, path, include_body=True):
|
||||||
if self._access_validation is not None:
|
if self._access_validation is not None:
|
||||||
@@ -785,6 +807,24 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
|||||||
if self._as_attachment:
|
if self._as_attachment:
|
||||||
self.set_header("Content-Disposition", "attachment")
|
self.set_header("Content-Disposition", "attachment")
|
||||||
|
|
||||||
|
if not self._allow_client_caching:
|
||||||
|
self.set_header("Cache-Control", "max-age=0, must-revalidate, private")
|
||||||
|
self.set_header("Expires", "-1")
|
||||||
|
|
||||||
|
def compute_etag(self):
|
||||||
|
if self._etag_generator is not None:
|
||||||
|
return self._etag_generator(self)
|
||||||
|
else:
|
||||||
|
return self.get_content_version(self.absolute_path)
|
||||||
|
|
||||||
|
def get_content_type(self):
|
||||||
|
if self._mime_type_guesser is not None:
|
||||||
|
type = self._mime_type_guesser(self.absolute_path)
|
||||||
|
if type is not None:
|
||||||
|
return type
|
||||||
|
|
||||||
|
return tornado.web.StaticFileHandler.get_content_type(self)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_content_version(cls, abspath):
|
def get_content_version(cls, abspath):
|
||||||
import os
|
import os
|
||||||
@@ -794,7 +834,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
|||||||
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
|
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
|
||||||
|
|
||||||
|
|
||||||
class UrlForwardHandler(tornado.web.RequestHandler):
|
class UrlProxyHandler(tornado.web.RequestHandler):
|
||||||
"""
|
"""
|
||||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies
|
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies
|
||||||
requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment
|
requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment
|
||||||
@@ -804,7 +844,7 @@ class UrlForwardHandler(tornado.web.RequestHandler):
|
|||||||
for making the request to the configured endpoint and return the body of the client response with the status code
|
for making the request to the configured endpoint and return the body of the client response with the status code
|
||||||
from the client response and the following headers:
|
from the client response and the following headers:
|
||||||
|
|
||||||
* ``Date``, ``Cache-Control``, ``Server``, ``Content-Type`` and ``Location`` will be copied over.
|
* ``Date``, ``Cache-Control``, ``Expires``, ``ETag``, ``Server``, ``Content-Type`` and ``Location`` will be copied over.
|
||||||
* If ``as_attachment`` is set to True, ``Content-Disposition`` will be set to ``attachment``. If ``basename`` is
|
* If ``as_attachment`` is set to True, ``Content-Disposition`` will be set to ``attachment``. If ``basename`` is
|
||||||
set including the attachement's ``filename`` attribute will be set to the base name followed by the extension
|
set including the attachement's ``filename`` attribute will be set to the base name followed by the extension
|
||||||
guessed based on the MIME type from the ``Content-Type`` header of the response. If no extension can be guessed
|
guessed based on the MIME type from the ``Content-Type`` header of the response. If no extension can be guessed
|
||||||
@@ -854,7 +894,7 @@ class UrlForwardHandler(tornado.web.RequestHandler):
|
|||||||
filename = None
|
filename = None
|
||||||
|
|
||||||
self.set_status(response.code)
|
self.set_status(response.code)
|
||||||
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location"):
|
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location", "Expires", "ETag"):
|
||||||
value = response.headers.get(name)
|
value = response.headers.get(name)
|
||||||
if value:
|
if value:
|
||||||
self.set_header(name, value)
|
self.set_header(name, value)
|
||||||
@@ -924,4 +964,4 @@ def path_validation_factory(path_filter, status_code=404):
|
|||||||
def f(path):
|
def f(path):
|
||||||
if not path_filter(path):
|
if not path_filter(path):
|
||||||
raise tornado.web.HTTPError(status_code)
|
raise tornado.web.HTTPError(status_code)
|
||||||
return f
|
return f
|
||||||
@@ -12,14 +12,20 @@ from flask import request, g, url_for, make_response, render_template, send_from
|
|||||||
|
|
||||||
import octoprint.plugin
|
import octoprint.plugin
|
||||||
|
|
||||||
from octoprint.server import app, userManager, pluginManager, gettext, debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY
|
from octoprint.server import app, userManager, pluginManager, gettext, \
|
||||||
|
debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH
|
||||||
from octoprint.settings import settings
|
from octoprint.settings import settings
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
from . import util
|
from . import util
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_valid_id_re = re.compile("[a-z_]+")
|
||||||
|
_valid_div_re = re.compile("[a-zA-Z_-]+")
|
||||||
|
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
|
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
|
||||||
key=lambda: "view/%s/%s" % (request.path, g.locale),
|
key=lambda: "view/%s/%s" % (request.path, g.locale),
|
||||||
@@ -150,6 +156,7 @@ def index():
|
|||||||
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
|
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
|
||||||
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
|
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
|
||||||
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
|
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
|
||||||
|
server=(gettext("Server"), dict(template="dialogs/settings/server.jinja2", _div="settings_server", custom_bindings=False)),
|
||||||
)
|
)
|
||||||
if enable_accesscontrol:
|
if enable_accesscontrol:
|
||||||
templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False))
|
templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False))
|
||||||
@@ -229,9 +236,30 @@ def index():
|
|||||||
# finally add anything that's not included in our order yet
|
# finally add anything that's not included in our order yet
|
||||||
sorted_missing = list(missing_in_order)
|
sorted_missing = list(missing_in_order)
|
||||||
if template_sorting[t]["key"] is not None:
|
if template_sorting[t]["key"] is not None:
|
||||||
# anything but navbar and generic components get sorted by their name
|
# default extractor: works with entries that are dicts and entries that are 2-tuples with the
|
||||||
if template_sorting[t]["key"] == "name":
|
# entry data at index 1
|
||||||
sorted_missing = sorted(missing_in_order, key=lambda x: templates[t]["entries"][x][0])
|
def extractor(item, key):
|
||||||
|
if isinstance(item, dict) and key in item:
|
||||||
|
return item[key]
|
||||||
|
elif isinstance(item, tuple) and len(item) > 1 and isinstance(item[1], dict) and key in item[1]:
|
||||||
|
return item[1][key]
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
# if template type provides custom extractor, make sure its exceptions are handled
|
||||||
|
if "key_extractor" in template_sorting[t] and callable(template_sorting[t]["key_extractor"]):
|
||||||
|
def create_safe_extractor(extractor):
|
||||||
|
def f(x, k):
|
||||||
|
try:
|
||||||
|
return extractor(x, k)
|
||||||
|
except:
|
||||||
|
_logger.exception("Error while extracting sorting keys for template {}".format(t))
|
||||||
|
return None
|
||||||
|
return f
|
||||||
|
extractor = create_safe_extractor(template_sorting[t]["key_extractor"])
|
||||||
|
|
||||||
|
sort_key = template_sorting[t]["key"]
|
||||||
|
sorted_missing = sorted(missing_in_order, key=lambda x: extractor(templates[t]["entries"][x], sort_key))
|
||||||
|
|
||||||
if template_sorting[t]["add"] == "prepend":
|
if template_sorting[t]["add"] == "prepend":
|
||||||
templates[t]["order"] = sorted_missing + templates[t]["order"]
|
templates[t]["order"] = sorted_missing + templates[t]["order"]
|
||||||
@@ -256,6 +284,7 @@ def index():
|
|||||||
debug=debug,
|
debug=debug,
|
||||||
version=VERSION,
|
version=VERSION,
|
||||||
display_version=DISPLAY_VERSION,
|
display_version=DISPLAY_VERSION,
|
||||||
|
branch=BRANCH,
|
||||||
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
|
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
|
||||||
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
|
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
|
||||||
uiApiKey=UI_API_KEY,
|
uiApiKey=UI_API_KEY,
|
||||||
@@ -276,9 +305,7 @@ def index():
|
|||||||
response.headers["Last-Modified"] = datetime.datetime.now()
|
response.headers["Last-Modified"] = datetime.datetime.now()
|
||||||
|
|
||||||
if first_run:
|
if first_run:
|
||||||
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0"
|
response = util.flask.add_non_caching_response_headers(response)
|
||||||
response.headers["Pragma"] = "no-cache"
|
|
||||||
response.headers["Expires"] = "-1"
|
|
||||||
|
|
||||||
return response
|
return response
|
||||||
|
|
||||||
@@ -319,6 +346,8 @@ def _process_template_configs(name, implementation, configs, rules):
|
|||||||
app.jinja_env.get_or_select_template(data["template"])
|
app.jinja_env.get_or_select_template(data["template"])
|
||||||
except TemplateNotFound:
|
except TemplateNotFound:
|
||||||
pass
|
pass
|
||||||
|
except:
|
||||||
|
_logger.exception("Error in template {}, not going to include it".format(data["template"]))
|
||||||
else:
|
else:
|
||||||
includes[template_type].append(rule["to_entry"](data))
|
includes[template_type].append(rule["to_entry"](data))
|
||||||
|
|
||||||
@@ -343,6 +372,9 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
|||||||
data["_div"] = rule["div"](name)
|
data["_div"] = rule["div"](name)
|
||||||
if "suffix" in data:
|
if "suffix" in data:
|
||||||
data["_div"] = data["_div"] + data["suffix"]
|
data["_div"] = data["_div"] + data["suffix"]
|
||||||
|
if not _valid_div_re.match(data["_div"]):
|
||||||
|
_logger.warn("Template config {} contains invalid div identifier {}, skipping it".format(name, data["_div"]))
|
||||||
|
return None
|
||||||
|
|
||||||
if not "template" in data:
|
if not "template" in data:
|
||||||
data["template"] = rule["template"](name)
|
data["template"] = rule["template"](name)
|
||||||
@@ -354,6 +386,7 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
|||||||
data_bind = "allowBindings: true"
|
data_bind = "allowBindings: true"
|
||||||
if "data_bind" in data:
|
if "data_bind" in data:
|
||||||
data_bind = data_bind + ", " + data["data_bind"]
|
data_bind = data_bind + ", " + data["data_bind"]
|
||||||
|
data_bind = data_bind.replace("\"", "\\\"")
|
||||||
data["data_bind"] = data_bind
|
data["data_bind"] = data_bind
|
||||||
|
|
||||||
data["_key"] = "plugin_" + name
|
data["_key"] = "plugin_" + name
|
||||||
|
|||||||
+33
-12
@@ -30,6 +30,8 @@ import logging
|
|||||||
import re
|
import re
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
|
from octoprint.util import atomic_write
|
||||||
|
|
||||||
_APPNAME = "OctoPrint"
|
_APPNAME = "OctoPrint"
|
||||||
|
|
||||||
_instance = None
|
_instance = None
|
||||||
@@ -104,6 +106,15 @@ default_settings = {
|
|||||||
"pathSuffix": "path"
|
"pathSuffix": "path"
|
||||||
},
|
},
|
||||||
"maxSize": 100 * 1024, # 100 KB
|
"maxSize": 100 * 1024, # 100 KB
|
||||||
|
"commands": {
|
||||||
|
"systemShutdownCommand": None,
|
||||||
|
"systemRestartCommand": None,
|
||||||
|
"serverRestartCommand": None
|
||||||
|
},
|
||||||
|
"diskspace": {
|
||||||
|
"warning": 500 * 1024 * 1024, # 500 MB
|
||||||
|
"critical": 200 * 1024 * 1024, # 200 MB
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"webcam": {
|
"webcam": {
|
||||||
"stream": None,
|
"stream": None,
|
||||||
@@ -143,7 +154,9 @@ default_settings = {
|
|||||||
"externalHeatupDetection": True,
|
"externalHeatupDetection": True,
|
||||||
"supportWait": True,
|
"supportWait": True,
|
||||||
"keyboardControl": True,
|
"keyboardControl": True,
|
||||||
"pollWatched": False
|
"pollWatched": False,
|
||||||
|
"ignoreIdenticalResends": False,
|
||||||
|
"identicalResendsCountdown": 7
|
||||||
},
|
},
|
||||||
"folder": {
|
"folder": {
|
||||||
"uploads": None,
|
"uploads": None,
|
||||||
@@ -188,7 +201,7 @@ default_settings = {
|
|||||||
"settings": [
|
"settings": [
|
||||||
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
|
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
|
||||||
"section_features", "features", "webcam", "accesscontrol", "api",
|
"section_features", "features", "webcam", "accesscontrol", "api",
|
||||||
"section_octoprint", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
|
"section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
|
||||||
],
|
],
|
||||||
"usersettings": ["access", "interface"],
|
"usersettings": ["access", "interface"],
|
||||||
"generic": []
|
"generic": []
|
||||||
@@ -271,6 +284,7 @@ default_settings = {
|
|||||||
},
|
},
|
||||||
"hasBed": True,
|
"hasBed": True,
|
||||||
"repetierStyleTargetTemperature": False,
|
"repetierStyleTargetTemperature": False,
|
||||||
|
"repetierStyleResends": False,
|
||||||
"okBeforeCommandOutput": False,
|
"okBeforeCommandOutput": False,
|
||||||
"smoothieTemperatureReporting": False,
|
"smoothieTemperatureReporting": False,
|
||||||
"extendedSdFileList": False,
|
"extendedSdFileList": False,
|
||||||
@@ -280,7 +294,8 @@ default_settings = {
|
|||||||
"txBuffer": 40,
|
"txBuffer": 40,
|
||||||
"commandBuffer": 4,
|
"commandBuffer": 4,
|
||||||
"sendWait": True,
|
"sendWait": True,
|
||||||
"waitInterval": 1.0
|
"waitInterval": 1.0,
|
||||||
|
"supportM112": True
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -321,14 +336,14 @@ class Settings(object):
|
|||||||
|
|
||||||
"/dev/ttyACM0"
|
"/dev/ttyACM0"
|
||||||
|
|
||||||
``["serial", "timeouts"]`` ::
|
``["serial", "timeout"]`` ::
|
||||||
|
|
||||||
communication: 20.0
|
communication: 20.0
|
||||||
temperature: 5.0
|
temperature: 5.0
|
||||||
sdStatus: 1.0
|
sdStatus: 1.0
|
||||||
connection: 10.0
|
connection: 10.0
|
||||||
|
|
||||||
``["serial", "timeouts", "temperature"]`` ::
|
``["serial", "timeout", "temperature"]`` ::
|
||||||
|
|
||||||
5.0
|
5.0
|
||||||
|
|
||||||
@@ -774,11 +789,17 @@ class Settings(object):
|
|||||||
if not self._dirty and not force:
|
if not self._dirty and not force:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
with open(self._configfile, "wb") as configFile:
|
from octoprint.util import atomic_write
|
||||||
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
|
try:
|
||||||
self._dirty = False
|
with atomic_write(self._configfile, "wb", prefix="octoprint-config-", suffix=".yaml") as configFile:
|
||||||
self.load()
|
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||||
return True
|
self._dirty = False
|
||||||
|
except:
|
||||||
|
self._logger.exception("Error while saving config.yaml!")
|
||||||
|
raise
|
||||||
|
else:
|
||||||
|
self.load()
|
||||||
|
return True
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def last_modified(self):
|
def last_modified(self):
|
||||||
@@ -970,7 +991,7 @@ class Settings(object):
|
|||||||
if not force and key in defaults and key in config and defaults[key] == value:
|
if not force and key in defaults and key in config and defaults[key] == value:
|
||||||
del config[key]
|
del config[key]
|
||||||
self._dirty = True
|
self._dirty = True
|
||||||
elif force or (not key in config and defaults[key] != value) or (key in config and config[key] != value):
|
elif force or (not key in config and key in defaults and defaults[key] != value) or (key in config and config[key] != value):
|
||||||
if value is None and key in config:
|
if value is None and key in config:
|
||||||
del config[key]
|
del config[key]
|
||||||
else:
|
else:
|
||||||
@@ -1038,7 +1059,7 @@ class Settings(object):
|
|||||||
path, _ = os.path.split(filename)
|
path, _ = os.path.split(filename)
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
os.makedirs(path)
|
os.makedirs(path)
|
||||||
with open(filename, "w+") as f:
|
with atomic_write(filename, "wb") as f:
|
||||||
f.write(script)
|
f.write(script)
|
||||||
|
|
||||||
def _default_basedir(applicationName):
|
def _default_basedir(applicationName):
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
|
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
|
||||||
@@ -122,6 +122,7 @@ function DataUpdater(allViewModels) {
|
|||||||
var oldVersion = VERSION;
|
var oldVersion = VERSION;
|
||||||
VERSION = data["version"];
|
VERSION = data["version"];
|
||||||
DISPLAY_VERSION = data["display_version"];
|
DISPLAY_VERSION = data["display_version"];
|
||||||
|
BRANCH = data["branch"];
|
||||||
$("span.version").text(DISPLAY_VERSION);
|
$("span.version").text(DISPLAY_VERSION);
|
||||||
|
|
||||||
var oldPluginHash = self._pluginHash;
|
var oldPluginHash = self._pluginHash;
|
||||||
@@ -176,6 +177,7 @@ function DataUpdater(allViewModels) {
|
|||||||
var type = data["type"];
|
var type = data["type"];
|
||||||
var payload = data["payload"];
|
var payload = data["payload"];
|
||||||
var html = "";
|
var html = "";
|
||||||
|
var format = {};
|
||||||
|
|
||||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||||
|
|
||||||
@@ -186,7 +188,31 @@ function DataUpdater(allViewModels) {
|
|||||||
} else if (type == "MovieFailed") {
|
} else if (type == "MovieFailed") {
|
||||||
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "</p>";
|
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "</p>";
|
||||||
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
|
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
|
||||||
new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false});
|
new PNotify({
|
||||||
|
title: gettext("Rendering failed"),
|
||||||
|
text: html,
|
||||||
|
type: "error",
|
||||||
|
hide: false
|
||||||
|
});
|
||||||
|
} else if (type == "PostRollStart") {
|
||||||
|
var title = gettext("Capturing timelapse postroll");
|
||||||
|
|
||||||
|
var text;
|
||||||
|
if (!payload.postroll_duration) {
|
||||||
|
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take only a moment..."), format);
|
||||||
|
} else {
|
||||||
|
if (payload.postroll_duration > 60) {
|
||||||
|
format = {duration: _.sprintf(gettext("%(minutes)d min"), {minutes: payload.postroll_duration / 60})};
|
||||||
|
} else {
|
||||||
|
format = {duration: _.sprintf(gettext("%(seconds)d sec"), {seconds: payload.postroll_duration})};
|
||||||
|
}
|
||||||
|
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s..."), format);
|
||||||
|
}
|
||||||
|
|
||||||
|
new PNotify({
|
||||||
|
title: title,
|
||||||
|
text: text
|
||||||
|
});
|
||||||
} else if (type == "SlicingStarted") {
|
} else if (type == "SlicingStarted") {
|
||||||
gcodeUploadProgress.addClass("progress-striped").addClass("active");
|
gcodeUploadProgress.addClass("progress-striped").addClass("active");
|
||||||
gcodeUploadProgressBar.css("width", "100%");
|
gcodeUploadProgressBar.css("width", "100%");
|
||||||
|
|||||||
@@ -333,6 +333,34 @@ function formatSize(bytes) {
|
|||||||
return _.sprintf("%.1f%s", bytes, "TB");
|
return _.sprintf("%.1f%s", bytes, "TB");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function bytesFromSize(size) {
|
||||||
|
if (size == undefined || size.trim() == "") return undefined;
|
||||||
|
|
||||||
|
var parsed = size.match(/^([+]?[0-9]*\.?[0-9]+)(?:\s*)?(.*)$/);
|
||||||
|
var number = parsed[1];
|
||||||
|
var unit = parsed[2].trim();
|
||||||
|
|
||||||
|
if (unit == "") return parseFloat(number);
|
||||||
|
|
||||||
|
var units = {
|
||||||
|
b: 1,
|
||||||
|
byte: 1,
|
||||||
|
bytes: 1,
|
||||||
|
kb: 1024,
|
||||||
|
mb: Math.pow(1024, 2),
|
||||||
|
gb: Math.pow(1024, 3),
|
||||||
|
tb: Math.pow(1024, 4)
|
||||||
|
};
|
||||||
|
unit = unit.toLowerCase();
|
||||||
|
|
||||||
|
if (!units.hasOwnProperty(unit)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
var factor = units[unit];
|
||||||
|
return number * factor;
|
||||||
|
}
|
||||||
|
|
||||||
function formatDuration(seconds) {
|
function formatDuration(seconds) {
|
||||||
if (!seconds) return "-";
|
if (!seconds) return "-";
|
||||||
if (seconds < 0) return "00:00:00";
|
if (seconds < 0) return "00:00:00";
|
||||||
@@ -461,3 +489,17 @@ function splitTextToArray(text, sep, stripEmpty, filter) {
|
|||||||
function(item) { return (stripEmpty ? item : true) && (filter ? filter(item) : true); }
|
function(item) { return (stripEmpty ? item : true) && (filter ? filter(item) : true); }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var sizeObservable = function(observable) {
|
||||||
|
return ko.computed({
|
||||||
|
read: function() {
|
||||||
|
return formatSize(observable());
|
||||||
|
},
|
||||||
|
write: function(value) {
|
||||||
|
var result = bytesFromSize(value);
|
||||||
|
if (result != undefined) {
|
||||||
|
observable(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
};
|
||||||
@@ -21,6 +21,15 @@ $(function() {
|
|||||||
headers: {"X-Api-Key": UI_API_KEY}
|
headers: {"X-Api-Key": UI_API_KEY}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
//~~ Initialize file upload plugin
|
||||||
|
|
||||||
|
$.widget("blueimp.fileupload", $.blueimp.fileupload, {
|
||||||
|
options: {
|
||||||
|
dropZone: null,
|
||||||
|
pasteZone: null
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
//~~ Initialize i18n
|
//~~ Initialize i18n
|
||||||
|
|
||||||
var catalog = window["BABEL_TO_LOAD_" + LOCALE];
|
var catalog = window["BABEL_TO_LOAD_" + LOCALE];
|
||||||
@@ -321,7 +330,7 @@ $(function() {
|
|||||||
.data("contextParent", $(this))
|
.data("contextParent", $(this))
|
||||||
.show()
|
.show()
|
||||||
.css({
|
.css({
|
||||||
position: "absolute",
|
position: "fixed",
|
||||||
left: getMenuPosition(e.clientX, 'width', 'scrollLeft'),
|
left: getMenuPosition(e.clientX, 'width', 'scrollLeft'),
|
||||||
top: getMenuPosition(e.clientY, 'height', 'scrollTop'),
|
top: getMenuPosition(e.clientY, 'height', 'scrollTop'),
|
||||||
"z-index": 9999
|
"z-index": 9999
|
||||||
|
|||||||
@@ -86,6 +86,15 @@ $(function() {
|
|||||||
self._processStateData(data.state);
|
self._processStateData(data.state);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
self.openOrCloseOnStateChange = function() {
|
||||||
|
var connectionTab = $("#connection");
|
||||||
|
if (self.isOperational() && connectionTab.hasClass("in")) {
|
||||||
|
connectionTab.collapse("hide");
|
||||||
|
} else if (!self.isOperational() && !connectionTab.hasClass("in")) {
|
||||||
|
connectionTab.collapse("show");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
self._processStateData = function(data) {
|
self._processStateData = function(data) {
|
||||||
self.previousIsOperational = self.isOperational();
|
self.previousIsOperational = self.isOperational();
|
||||||
|
|
||||||
@@ -97,15 +106,10 @@ $(function() {
|
|||||||
self.isReady(data.flags.ready);
|
self.isReady(data.flags.ready);
|
||||||
self.isLoading(data.flags.loading);
|
self.isLoading(data.flags.loading);
|
||||||
|
|
||||||
var connectionTab = $("#connection");
|
if (self.loginState.isAdmin() && self.previousIsOperational != self.isOperational()) {
|
||||||
if (self.previousIsOperational != self.isOperational()) {
|
// only open or close if the panel is visible (for admins) and
|
||||||
if (self.isOperational() && connectionTab.hasClass("in")) {
|
// the state just changed to avoid thwarting manual open/close
|
||||||
// connection just got established, close connection tab for now
|
self.openOrCloseOnStateChange();
|
||||||
connectionTab.collapse("hide");
|
|
||||||
} else if (!connectionTab.hasClass("in")) {
|
|
||||||
// connection just dropped, make sure connection tab is open
|
|
||||||
connectionTab.collapse("show");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -147,6 +151,16 @@ $(function() {
|
|||||||
|
|
||||||
self.onStartup = function() {
|
self.onStartup = function() {
|
||||||
self.requestData();
|
self.requestData();
|
||||||
|
|
||||||
|
// when isAdmin becomes true the first time, set the panel open or
|
||||||
|
// closed based on the connection state
|
||||||
|
var subscription = self.loginState.isAdmin.subscribe(function(newValue) {
|
||||||
|
if (newValue) {
|
||||||
|
// wait until after the isAdmin state has run through all subscriptions
|
||||||
|
setTimeout(self.openOrCloseOnStateChange, 0);
|
||||||
|
subscription.dispose();
|
||||||
|
}
|
||||||
|
});
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,9 +2,10 @@ $(function() {
|
|||||||
function GcodeFilesViewModel(parameters) {
|
function GcodeFilesViewModel(parameters) {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
self.printerState = parameters[0];
|
self.settingsViewModel = parameters[0];
|
||||||
self.loginState = parameters[1];
|
self.loginState = parameters[1];
|
||||||
self.slicing = parameters[2];
|
self.printerState = parameters[2];
|
||||||
|
self.slicing = parameters[3];
|
||||||
|
|
||||||
self.isErrorOrClosed = ko.observable(undefined);
|
self.isErrorOrClosed = ko.observable(undefined);
|
||||||
self.isOperational = ko.observable(undefined);
|
self.isOperational = ko.observable(undefined);
|
||||||
@@ -21,11 +22,35 @@ $(function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
self.freeSpace = ko.observable(undefined);
|
self.freeSpace = ko.observable(undefined);
|
||||||
|
self.totalSpace = ko.observable(undefined);
|
||||||
self.freeSpaceString = ko.computed(function() {
|
self.freeSpaceString = ko.computed(function() {
|
||||||
if (!self.freeSpace())
|
if (!self.freeSpace())
|
||||||
return "-";
|
return "-";
|
||||||
return formatSize(self.freeSpace());
|
return formatSize(self.freeSpace());
|
||||||
});
|
});
|
||||||
|
self.totalSpaceString = ko.computed(function() {
|
||||||
|
if (!self.totalSpace())
|
||||||
|
return "-";
|
||||||
|
return formatSize(self.totalSpace());
|
||||||
|
});
|
||||||
|
|
||||||
|
self.diskusageWarning = ko.computed(function() {
|
||||||
|
return self.freeSpace() != undefined
|
||||||
|
&& self.freeSpace() < self.settingsViewModel.server_diskspace_warning();
|
||||||
|
});
|
||||||
|
self.diskusageCritical = ko.computed(function() {
|
||||||
|
return self.freeSpace() != undefined
|
||||||
|
&& self.freeSpace() < self.settingsViewModel.server_diskspace_critical();
|
||||||
|
});
|
||||||
|
self.diskusageString = ko.computed(function() {
|
||||||
|
if (self.diskusageCritical()) {
|
||||||
|
return gettext("Your available free disk space is critically low.");
|
||||||
|
} else if (self.diskusageWarning()) {
|
||||||
|
return gettext("Your available free disk space is starting to run low.");
|
||||||
|
} else {
|
||||||
|
return gettext("Your current disk usage.");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
self.uploadButton = undefined;
|
self.uploadButton = undefined;
|
||||||
|
|
||||||
@@ -155,10 +180,14 @@ $(function() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (response.free) {
|
if (response.free != undefined) {
|
||||||
self.freeSpace(response.free);
|
self.freeSpace(response.free);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (response.total != undefined) {
|
||||||
|
self.totalSpace(response.total);
|
||||||
|
}
|
||||||
|
|
||||||
self.highlightFilename(self.printerState.filename());
|
self.highlightFilename(self.printerState.filename());
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -575,7 +604,7 @@ $(function() {
|
|||||||
|
|
||||||
OCTOPRINT_VIEWMODELS.push([
|
OCTOPRINT_VIEWMODELS.push([
|
||||||
GcodeFilesViewModel,
|
GcodeFilesViewModel,
|
||||||
["printerStateViewModel", "loginStateViewModel", "slicingViewModel"],
|
["settingsViewModel", "loginStateViewModel", "printerStateViewModel", "slicingViewModel"],
|
||||||
"#files_wrapper"
|
"#files_wrapper"
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
@@ -6,6 +6,10 @@ $(function() {
|
|||||||
self.users = parameters[1];
|
self.users = parameters[1];
|
||||||
self.printerProfiles = parameters[2];
|
self.printerProfiles = parameters[2];
|
||||||
|
|
||||||
|
self.receiving = ko.observable(false);
|
||||||
|
self.sending = ko.observable(false);
|
||||||
|
self.callbacks = [];
|
||||||
|
|
||||||
self.api_enabled = ko.observable(undefined);
|
self.api_enabled = ko.observable(undefined);
|
||||||
self.api_key = ko.observable(undefined);
|
self.api_key = ko.observable(undefined);
|
||||||
self.api_allowCrossOrigin = ko.observable(undefined);
|
self.api_allowCrossOrigin = ko.observable(undefined);
|
||||||
@@ -114,6 +118,7 @@ $(function() {
|
|||||||
self.feature_disableExternalHeatupDetection = ko.observable(undefined);
|
self.feature_disableExternalHeatupDetection = ko.observable(undefined);
|
||||||
self.feature_keyboardControl = ko.observable(undefined);
|
self.feature_keyboardControl = ko.observable(undefined);
|
||||||
self.feature_pollWatched = ko.observable(undefined);
|
self.feature_pollWatched = ko.observable(undefined);
|
||||||
|
self.feature_ignoreIdenticalResends = ko.observable(undefined);
|
||||||
|
|
||||||
self.serial_port = ko.observable();
|
self.serial_port = ko.observable();
|
||||||
self.serial_baudrate = ko.observable();
|
self.serial_baudrate = ko.observable();
|
||||||
@@ -149,6 +154,15 @@ $(function() {
|
|||||||
|
|
||||||
self.terminalFilters = ko.observableArray([]);
|
self.terminalFilters = ko.observableArray([]);
|
||||||
|
|
||||||
|
self.server_commands_systemShutdownCommand = ko.observable(undefined);
|
||||||
|
self.server_commands_systemRestartCommand = ko.observable(undefined);
|
||||||
|
self.server_commands_serverRestartCommand = ko.observable(undefined);
|
||||||
|
|
||||||
|
self.server_diskspace_warning = ko.observable();
|
||||||
|
self.server_diskspace_critical = ko.observable();
|
||||||
|
self.server_diskspace_warning_str = sizeObservable(self.server_diskspace_warning);
|
||||||
|
self.server_diskspace_critical_str = sizeObservable(self.server_diskspace_critical);
|
||||||
|
|
||||||
self.settings = undefined;
|
self.settings = undefined;
|
||||||
|
|
||||||
self.addTemperatureProfile = function() {
|
self.addTemperatureProfile = function() {
|
||||||
@@ -257,13 +271,42 @@ $(function() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
self.requestData = function(callback) {
|
self.requestData = function(callback) {
|
||||||
|
if (self.receiving()) {
|
||||||
|
if (callback) {
|
||||||
|
self.callbacks.push(callback);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.receiving(true);
|
||||||
$.ajax({
|
$.ajax({
|
||||||
url: API_BASEURL + "settings",
|
url: API_BASEURL + "settings",
|
||||||
type: "GET",
|
type: "GET",
|
||||||
dataType: "json",
|
dataType: "json",
|
||||||
success: function(response) {
|
success: function(response) {
|
||||||
self.fromResponse(response);
|
if (callback) {
|
||||||
if (callback) callback();
|
self.callbacks.push(callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
self.fromResponse(response);
|
||||||
|
|
||||||
|
var cb;
|
||||||
|
while (self.callbacks.length) {
|
||||||
|
cb = self.callbacks.shift();
|
||||||
|
try {
|
||||||
|
cb();
|
||||||
|
} catch(exc) {
|
||||||
|
log.error("Error calling settings callback", cb, ":", (exc.stack || exc));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
self.receiving(false);
|
||||||
|
self.callbacks = [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function(xhr) {
|
||||||
|
self.receiving(false);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -415,12 +458,18 @@ $(function() {
|
|||||||
self.system_actions(response.system.actions);
|
self.system_actions(response.system.actions);
|
||||||
|
|
||||||
self.terminalFilters(response.terminalFilters);
|
self.terminalFilters(response.terminalFilters);
|
||||||
|
|
||||||
|
self.server_commands_systemShutdownCommand(response.server.commands.systemShutdownCommand);
|
||||||
|
self.server_commands_systemRestartCommand(response.server.commands.systemRestartCommand);
|
||||||
|
self.server_commands_serverRestartCommand(response.server.commands.serverRestartCommand);
|
||||||
};
|
};
|
||||||
|
|
||||||
self.saveData = function (data, successCallback) {
|
self.saveData = function (data, successCallback) {
|
||||||
self.settingsDialog.trigger("beforeSave");
|
self.settingsDialog.trigger("beforeSave");
|
||||||
|
|
||||||
if (data == undefined) {
|
if (data == undefined) {
|
||||||
|
// we only set sending to true when we didn't include data
|
||||||
|
self.sending(true);
|
||||||
data = ko.mapping.toJS(self.settings);
|
data = ko.mapping.toJS(self.settings);
|
||||||
|
|
||||||
data = _.extend(data, {
|
data = _.extend(data, {
|
||||||
@@ -499,6 +548,13 @@ $(function() {
|
|||||||
"beforePrintResumed": self.scripts_gcode_beforePrintResumed(),
|
"beforePrintResumed": self.scripts_gcode_beforePrintResumed(),
|
||||||
"afterPrinterConnected": self.scripts_gcode_afterPrinterConnected()
|
"afterPrinterConnected": self.scripts_gcode_afterPrinterConnected()
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"server": {
|
||||||
|
"commands": {
|
||||||
|
"systemShutdownCommand": self.server_commands_systemShutdownCommand(),
|
||||||
|
"systemRestartCommand": self.server_commands_systemRestartCommand(),
|
||||||
|
"serverRestartCommand": self.server_commands_serverRestartCommand()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -510,11 +566,24 @@ $(function() {
|
|||||||
contentType: "application/json; charset=UTF-8",
|
contentType: "application/json; charset=UTF-8",
|
||||||
data: JSON.stringify(data),
|
data: JSON.stringify(data),
|
||||||
success: function(response) {
|
success: function(response) {
|
||||||
self.fromResponse(response);
|
self.receiving(true);
|
||||||
if (successCallback) successCallback(response);
|
self.sending(false);
|
||||||
|
try {
|
||||||
|
self.fromResponse(response);
|
||||||
|
if (successCallback) successCallback(response);
|
||||||
|
} finally {
|
||||||
|
self.receiving(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function(xhr) {
|
||||||
|
self.sending(false);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
self.onEventSettingsUpdated = function() {
|
||||||
|
self.requestData();
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
OCTOPRINT_VIEWMODELS.push([
|
OCTOPRINT_VIEWMODELS.push([
|
||||||
|
|||||||
@@ -611,11 +611,11 @@ ul.dropdown-menu li a {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.custom_section_horizontal .custom_control {
|
.custom_section_horizontal > .custom_control {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.custom_section_vertical .custom_control {
|
.custom_section_vertical > .custom_control {
|
||||||
display:block;
|
display:block;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<div id="settings_dialog" class="modal hide fade large" tabindex="-1" role="dialog" aria-labelledby="settings_dialog_label" aria-hidden="true">
|
<div id="settings_dialog" class="modal hide fade large" tabindex="-1" role="dialog" aria-labelledby="settings_dialog_label" aria-hidden="true">
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
<button type="button" class="close" data-dismiss="modal">×</button>
|
<button type="button" class="close" data-dismiss="modal">×</button>
|
||||||
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }}</h3>
|
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }} <i class="icon-spinner icon-spin" data-bind="visible: receiving"></i></h3>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-body">
|
<div class="modal-body">
|
||||||
<div class="full-sized-box">
|
<div class="full-sized-box">
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
|
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
|
||||||
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
||||||
>
|
>
|
||||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
|
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
|
||||||
</li>
|
</li>
|
||||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -49,6 +49,6 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
|
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
|
||||||
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }">{{ _('Save') }}</button>
|
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }, enable: !sending(), css: {disabled: sending()}"><i class="icon-spinner icon-spin" data-bind="visible: sending"></i> {{ _('Save') }}</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -48,6 +48,13 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</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>
|
||||||
|
</div>
|
||||||
<div class="control-group">
|
<div class="control-group">
|
||||||
<div class="controls">
|
<div class="controls">
|
||||||
<label class="checkbox">
|
<label class="checkbox">
|
||||||
@@ -62,11 +69,4 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="control-group">
|
|
||||||
<div class="controls">
|
|
||||||
<label class="checkbox">
|
|
||||||
<input type="checkbox" data-bind="checked: feature_swallowOkAfterResend" id="settings-swallowOkAfterResend"> {{ _('Swallow the first "ok" after a resend response') }}
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</form>
|
</form>
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
<form class="form-horizontal">
|
<form class="form-horizontal">
|
||||||
|
<h3>{{ _('Folders') }}</h3>
|
||||||
|
|
||||||
<div class="control-group">
|
<div class="control-group">
|
||||||
<label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
|
<label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
|
||||||
<div class="controls">
|
<div class="controls">
|
||||||
@@ -36,4 +38,21 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<h3>{{ _('Disk space thresholds') }}</h3>
|
||||||
|
|
||||||
|
<p>{{ _('If the free disk space falls below these thresholds, OctoPrint will warn the user.') }}</p>
|
||||||
|
|
||||||
|
<div class="control-group" title="{{ ('Threshold after which to warn about the remaining free space on disk.') }}">
|
||||||
|
<label class="control-label" for="settings.serverDiskusageWarning">{{ _('Warning') }}</label>
|
||||||
|
<div class="controls">
|
||||||
|
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_warning_str">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="control-group" title="{{ ('Threshold after which to consider remaining free space on disk as critical.') }}">
|
||||||
|
<label class="control-label" for="settings.serverDiskusageCritical">{{ _('Critical') }}</label>
|
||||||
|
<div class="controls">
|
||||||
|
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_critical_str">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</form>
|
</form>
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<form class="form-horizontal">
|
||||||
|
<h3>{{ _('Commands') }}</h3>
|
||||||
|
|
||||||
|
<div class="control-group" title="{{ _('Command to restart the OctoPrint server') }}">
|
||||||
|
<label class="control-label" for="settings-serverRestartCommand">{{ _('Restart OctoPrint') }}</label>
|
||||||
|
<div class="controls">
|
||||||
|
<input type="text" class="input-block-level" data-bind="value: server_commands_serverRestartCommand" id="settings-serverRestartCommand">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="control-group" title="{{ _('Command to restart the system OctoPrint is running on') }}">
|
||||||
|
<label class="control-label" for="settings-systemRestartCommand">{{ _('Restart system') }}</label>
|
||||||
|
<div class="controls">
|
||||||
|
<input type="text" class="input-block-level" data-bind="value: server_commands_systemRestartCommand" id="settings-systemRestartCommand">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="control-group" title="{{ _('Command to shut down the system OctoPrint is running on') }}">
|
||||||
|
<label class="control-label" for="settings-systemShutdownCommand">{{ _('Shutdown system') }}</label>
|
||||||
|
<div class="controls">
|
||||||
|
<input type="text" class="input-block-level" data-bind="value: server_commands_systemShutdownCommand" id="settings-systemShutdownCommand">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
|
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
|
||||||
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
||||||
>
|
>
|
||||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
|
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
|
||||||
</li>
|
</li>
|
||||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
@@ -55,7 +55,7 @@
|
|||||||
>
|
>
|
||||||
<div class="accordion-heading">
|
<div class="accordion-heading">
|
||||||
<a class="accordion-toggle" data-toggle="collapse" data-target="#{{ data._div }}">
|
<a class="accordion-toggle" data-toggle="collapse" data-target="#{{ data._div }}">
|
||||||
{% if "icon" in data %}<i class="icon-{{ data.icon }}"></i> {% endif %}{{ entry }}
|
{% if "icon" in data %}<i class="icon-{{ data.icon }}"></i> {% endif %}{{ entry|e }}
|
||||||
</a>
|
</a>
|
||||||
{% if "template_header" in data %}
|
{% if "template_header" in data %}
|
||||||
{% include data.template_header ignore missing %}
|
{% include data.template_header ignore missing %}
|
||||||
@@ -87,7 +87,7 @@
|
|||||||
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
|
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
|
||||||
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
||||||
>
|
>
|
||||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
|
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
|
||||||
</li>
|
</li>
|
||||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
@@ -112,7 +112,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="footer">
|
<div class="footer">
|
||||||
<ul class="pull-left muted">
|
<ul class="pull-left muted">
|
||||||
<li><small>{{ _('Version') }}: <span class="version">{{ display_version }}</span></small></li>
|
<li><small>{{ _('Version') }}: <span class="version">{{ display_version|e }}</span></small></li>
|
||||||
</ul>
|
</ul>
|
||||||
<ul class="pull-right">
|
<ul class="pull-right">
|
||||||
<li><a href="http://octoprint.org"><i class="icon-home"></i> {{ _('Homepage') }}</a></li>
|
<li><a href="http://octoprint.org"><i class="icon-home"></i> {{ _('Homepage') }}</a></li>
|
||||||
|
|||||||
@@ -10,23 +10,24 @@
|
|||||||
var CONFIG_TIMELAPSEFILESPERPAGE = 10;
|
var CONFIG_TIMELAPSEFILESPERPAGE = 10;
|
||||||
var CONFIG_LOGFILESPERPAGE = 10;
|
var CONFIG_LOGFILESPERPAGE = 10;
|
||||||
var CONFIG_USERSPERPAGE = 10;
|
var CONFIG_USERSPERPAGE = 10;
|
||||||
var CONFIG_WEBCAM_STREAM = "{{ webcamStream }}";
|
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}";
|
||||||
var CONFIG_ACCESS_CONTROL = {% if enableAccessControl -%} true; {% else %} false; {%- endif %}
|
var CONFIG_ACCESS_CONTROL = {% if enableAccessControl -%} true; {% else %} false; {%- endif %}
|
||||||
var CONFIG_SD_SUPPORT = {% if enableSdSupport -%} true; {% else %} false; {%- endif %}
|
var CONFIG_SD_SUPPORT = {% if enableSdSupport -%} true; {% else %} false; {%- endif %}
|
||||||
var CONFIG_FIRST_RUN = {% if firstRun -%} true; {% else %} false; {%- endif %}
|
var CONFIG_FIRST_RUN = {% if firstRun -%} true; {% else %} false; {%- endif %}
|
||||||
var CONFIG_TEMPERATURE_GRAPH = {% if enableTemperatureGraph -%} true; {% else %} false; {%- endif %}
|
var CONFIG_TEMPERATURE_GRAPH = {% if enableTemperatureGraph -%} true; {% else %} false; {%- endif %}
|
||||||
var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold }};
|
var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold|e }};
|
||||||
var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold }};
|
var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold|e }};
|
||||||
|
|
||||||
var SOCKJS_URI = "{{ url_for('index') }}" + "sockjs";
|
var SOCKJS_URI = "{{ url_for('index') }}" + "sockjs";
|
||||||
var SOCKJS_DEBUG = CONFIG_DEBUG;
|
var SOCKJS_DEBUG = CONFIG_DEBUG;
|
||||||
// sockjs should define CLOSE_NORMAL for us, but they don't (from ws spec)
|
// sockjs should define CLOSE_NORMAL for us, but they don't (from ws spec)
|
||||||
var SOCKJS_CLOSE_NORMAL = 1000
|
var SOCKJS_CLOSE_NORMAL = 1000;
|
||||||
|
|
||||||
var UI_API_KEY = "{{ uiApiKey }}";
|
var UI_API_KEY = "{{ uiApiKey|e }}";
|
||||||
var VERSION = "{{ version }}";
|
var VERSION = "{{ version|e }}";
|
||||||
var DISPLAY_VERSION = "{{ display_version }}";
|
var DISPLAY_VERSION = "{{ display_version|e }}";
|
||||||
var LOCALE = "{{ g.locale }}";
|
var BRANCH = "{{ branch|e }}";
|
||||||
|
var LOCALE = "{{ g.locale|e }}";
|
||||||
var AVAILABLE_LOCALES = {{ locales|tojson }};
|
var AVAILABLE_LOCALES = {{ locales|tojson }};
|
||||||
|
|
||||||
var OCTOPRINT_VIEWMODELS = [];
|
var OCTOPRINT_VIEWMODELS = [];
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
<label class="checkbox">
|
<label class="checkbox">
|
||||||
<input type="checkbox" id="login_remember" data-bind="checked: loginState.loginRemember"> {{ _('Remember me') }}
|
<input type="checkbox" id="login_remember" data-bind="checked: loginState.loginRemember"> {{ _('Remember me') }}
|
||||||
</label>
|
</label>
|
||||||
<button class="btn btn-block btn-primary" id="login_button" data-bind="click: loginState.login">{{ _('Login') }}</button>
|
<button class="btn btn-block btn-primary" id="login_button" data-bind="click: function() { loginState.login(); }">{{ _('Login') }}</button>
|
||||||
</div>
|
</div>
|
||||||
<ul id="login_dropdown_loggedin" class="hide" data-bind="css: {hide: !loginState.loggedIn(), 'dropdown-menu': loginState.loggedIn()}">
|
<ul id="login_dropdown_loggedin" class="hide" data-bind="css: {hide: !loginState.loggedIn(), 'dropdown-menu': loginState.loggedIn()}">
|
||||||
<li><a href="#" id="usersettings_button" data-bind="click: function() { usersettings.show(); }">{{ _('User Settings') }}</a></li>
|
<li><a href="#" id="usersettings_button" data-bind="click: function() { usersettings.show(); }">{{ _('User Settings') }}</a></li>
|
||||||
|
|||||||
@@ -10,11 +10,11 @@
|
|||||||
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
||||||
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
|
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
|
||||||
<div class="btn-group action-buttons">
|
<div class="btn-group action-buttons">
|
||||||
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }"><i class="icon-chevron-down"></i></div>
|
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }" title="{{ _('Additional data') }}"><i class="icon-chevron-down"></i></div>
|
||||||
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="{{ _('Download') }}"></i></a>
|
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}" title="{{ _('Download') }}"><i class="icon-download-alt"></i></a>
|
||||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
|
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="icon-trash"></i></div>
|
||||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-folder-open" title="{{ _('Load') }}"></i></div>
|
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}" title="{{ _('Load') }}"><i class="icon-folder-open"></i></div>
|
||||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-print" title="{{ _('Load and Print') }}"></i></div>
|
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}" title="{{ _('Load and Print') }}"><i class="icon-print"></i></div>
|
||||||
</div>
|
</div>
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -23,9 +23,9 @@
|
|||||||
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
|
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
|
||||||
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
||||||
<div class="btn-group action-buttons">
|
<div class="btn-group action-buttons">
|
||||||
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="{{ _('Download') }}"></i></a>
|
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}" title="{{ _('Download') }}"><i class="icon-download-alt"></i></a>
|
||||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
|
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="icon-trash"></i></div>
|
||||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSlicing($data)) { $root.sliceFile($data); } else { return; } }, css: {disabled: !$root.enableSlicing($data)}"><i class="icon-magic" title="{{ _('Slice') }}"></i></div>
|
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSlicing($data)) { $root.sliceFile($data); } else { return; } }, css: {disabled: !$root.enableSlicing($data)}" title="{{ _('Slice') }}"><i class="icon-magic"></i></div>
|
||||||
</div>
|
</div>
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -33,8 +33,8 @@
|
|||||||
<div class="title" data-bind="text: name"></div>
|
<div class="title" data-bind="text: name"></div>
|
||||||
</script>
|
</script>
|
||||||
</div>
|
</div>
|
||||||
<div class="muted text-right">
|
<div class="text-right muted" data-bind="attr: {title: diskusageString}, css: {'text-error': diskusageCritical}, style: {'font-weight': diskusageCritical() || diskusageWarning() ? 'bold' : 'normal'}">
|
||||||
<small>{{ _('Free') }}: <span data-bind="text: freeSpaceString"></span></small>
|
<small>{{ _('Free') }}: <span data-bind="text: freeSpaceString"></span> / {{ _('Total') }}: <span data-bind="text: totalSpaceString"></span> <i class="icon-exclamation-sign" data-bind="visible: diskusageWarning" style="display: none"></i></small>
|
||||||
</div>
|
</div>
|
||||||
<div style="display: none;" data-bind="visible: loginState.isUser">
|
<div style="display: none;" data-bind="visible: loginState.isUser">
|
||||||
<div class="row-fluid upload-buttons">
|
<div class="row-fluid upload-buttons">
|
||||||
|
|||||||
@@ -1,12 +1,17 @@
|
|||||||
<div style="display: none;" data-bind="visible: loginState.isUser">
|
<div style="display: none;" data-bind="visible: loginState.isUser">
|
||||||
|
<div class="alert" data-bind="visible: isPrinting()">
|
||||||
|
{{ _('Take note that timelapse configuration is disabled while your printer is printing.') }}
|
||||||
|
</div>
|
||||||
<h1>{{ _('Timelapse Configuration') }}</h1>
|
<h1>{{ _('Timelapse Configuration') }}</h1>
|
||||||
|
|
||||||
<label for="webcam_timelapse_mode">{{ _('Timelapse Mode') }}</label>
|
<label for="webcam_timelapse_mode">{{ _('Timelapse Mode') }}</label>
|
||||||
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: isOperational() && !isPrinting() && loginState.isUser()">
|
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: isOperational() && !isPrinting() && loginState.isUser()">
|
||||||
<option value="off">{{ _('Off') }}</option>
|
<option value="off">{{ _('Off') }}</option>
|
||||||
<option value="zchange">{{ _('On Z Change') }}</option>
|
|
||||||
<option value="timed">{{ _('Timed') }}</option>
|
<option value="timed">{{ _('Timed') }}</option>
|
||||||
|
<option value="zchange">{{ _('On Z Change') }}</option>
|
||||||
</select>
|
</select>
|
||||||
|
<span class="help-block" data-bind="visible: timelapseType() == 'zchange'"><span class="label label-warning">{{ _('Warning') }}</span> {{ _('Do not use with spiralized ("Joris") vases or similar continuous Z models.') }}</span>
|
||||||
|
<span class="help-block" data-bind="visible: timelapseType() == 'zchange'"><span class="label label-info">{{ _('Note') }}</span> {% trans %}Does not work when printing from the printer's SD Card (no way to detect the change in Z reliably). Use "Timed" mode for those prints instead.{% endtrans %}</span>
|
||||||
|
|
||||||
<label for="webcam_timelapse_fps">{{ _('Timelapse frame rate (in frames per second)') }}</label>
|
<label for="webcam_timelapse_fps">{{ _('Timelapse frame rate (in frames per second)') }}</label>
|
||||||
<div class="input-append">
|
<div class="input-append">
|
||||||
|
|||||||
+205
-133
@@ -6,13 +6,13 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
import urllib
|
|
||||||
import time
|
import time
|
||||||
import subprocess
|
|
||||||
import fnmatch
|
import fnmatch
|
||||||
import datetime
|
import datetime
|
||||||
import sys
|
import sys
|
||||||
import shutil
|
import shutil
|
||||||
|
import Queue
|
||||||
|
import requests
|
||||||
|
|
||||||
import octoprint.util as util
|
import octoprint.util as util
|
||||||
|
|
||||||
@@ -58,7 +58,7 @@ def notifyCallbacks(timelapse):
|
|||||||
if timelapse is None:
|
if timelapse is None:
|
||||||
config = None
|
config = None
|
||||||
else:
|
else:
|
||||||
config = timelapse.configData()
|
config = timelapse.config_data()
|
||||||
for callback in updateCallbacks:
|
for callback in updateCallbacks:
|
||||||
try: callback.sendTimelapseConfig(config)
|
try: callback.sendTimelapseConfig(config)
|
||||||
except: logging.getLogger(__name__).exception("Exception while pushing timelapse configuration")
|
except: logging.getLogger(__name__).exception("Exception while pushing timelapse configuration")
|
||||||
@@ -86,12 +86,12 @@ def configureTimelapse(config=None, persist=False):
|
|||||||
if type is None or "off" == type:
|
if type is None or "off" == type:
|
||||||
current = None
|
current = None
|
||||||
elif "zchange" == type:
|
elif "zchange" == type:
|
||||||
current = ZTimelapse(postRoll=postRoll, fps=fps)
|
current = ZTimelapse(post_roll=postRoll, fps=fps)
|
||||||
elif "timed" == type:
|
elif "timed" == type:
|
||||||
interval = 10
|
interval = 10
|
||||||
if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0:
|
if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0:
|
||||||
interval = config["options"]["interval"]
|
interval = config["options"]["interval"]
|
||||||
current = TimedTimelapse(postRoll=postRoll, interval=interval, fps=fps)
|
current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps)
|
||||||
|
|
||||||
notifyCallbacks(current)
|
notifyCallbacks(current)
|
||||||
|
|
||||||
@@ -101,72 +101,83 @@ def configureTimelapse(config=None, persist=False):
|
|||||||
|
|
||||||
|
|
||||||
class Timelapse(object):
|
class Timelapse(object):
|
||||||
def __init__(self, postRoll=0, fps=25):
|
QUEUE_ENTRY_TYPE_CAPTURE = "capture"
|
||||||
|
QUEUE_ENTRY_TYPE_CALLBACK = "callback"
|
||||||
|
|
||||||
|
def __init__(self, post_roll=0, fps=25):
|
||||||
self._logger = logging.getLogger(__name__)
|
self._logger = logging.getLogger(__name__)
|
||||||
self._imageNumber = None
|
self._image_number = None
|
||||||
self._inTimelapse = False
|
self._in_timelapse = False
|
||||||
self._gcodeFile = None
|
self._gcode_file = None
|
||||||
|
|
||||||
self._postRoll = postRoll
|
self._post_roll = post_roll
|
||||||
self._postRollStart = None
|
self._on_post_roll_done = None
|
||||||
self._onPostRollDone = None
|
|
||||||
|
|
||||||
self._captureDir = settings().getBaseFolder("timelapse_tmp")
|
self._capture_dir = settings().getBaseFolder("timelapse_tmp")
|
||||||
self._movieDir = settings().getBaseFolder("timelapse")
|
self._movie_dir = settings().getBaseFolder("timelapse")
|
||||||
self._snapshotUrl = settings().get(["webcam", "snapshot"])
|
self._snapshot_url = settings().get(["webcam", "snapshot"])
|
||||||
self._ffmpegThreads = settings().get(["webcam", "ffmpegThreads"])
|
self._ffmpeg_threads = settings().get(["webcam", "ffmpegThreads"])
|
||||||
|
|
||||||
self._fps = fps
|
self._fps = fps
|
||||||
|
|
||||||
self._renderThread = None
|
self._render_thread = None
|
||||||
self._captureMutex = threading.Lock()
|
|
||||||
|
self._capture_mutex = threading.Lock()
|
||||||
|
self._capture_queue = Queue.Queue()
|
||||||
|
self._capture_queue_active = True
|
||||||
|
|
||||||
|
self._capture_queue_thread = threading.Thread(target=self._capture_queue_worker)
|
||||||
|
self._capture_queue_thread.daemon = True
|
||||||
|
self._capture_queue_thread.start()
|
||||||
|
|
||||||
# subscribe events
|
# subscribe events
|
||||||
eventManager().subscribe(Events.PRINT_STARTED, self.onPrintStarted)
|
eventManager().subscribe(Events.PRINT_STARTED, self.on_print_started)
|
||||||
eventManager().subscribe(Events.PRINT_FAILED, self.onPrintDone)
|
eventManager().subscribe(Events.PRINT_FAILED, self.on_print_done)
|
||||||
eventManager().subscribe(Events.PRINT_DONE, self.onPrintDone)
|
eventManager().subscribe(Events.PRINT_DONE, self.on_print_done)
|
||||||
eventManager().subscribe(Events.PRINT_RESUMED, self.onPrintResumed)
|
eventManager().subscribe(Events.PRINT_RESUMED, self.on_print_resumed)
|
||||||
for (event, callback) in self.eventSubscriptions():
|
for (event, callback) in self.event_subscriptions():
|
||||||
eventManager().subscribe(event, callback)
|
eventManager().subscribe(event, callback)
|
||||||
|
|
||||||
def postRoll(self):
|
@property
|
||||||
return self._postRoll
|
def post_roll(self):
|
||||||
|
return self._post_roll
|
||||||
|
|
||||||
|
@property
|
||||||
def fps(self):
|
def fps(self):
|
||||||
return self._fps
|
return self._fps
|
||||||
|
|
||||||
def unload(self):
|
def unload(self):
|
||||||
if self._inTimelapse:
|
if self._in_timelapse:
|
||||||
self.stopTimelapse(doCreateMovie=False)
|
self.stop_timelapse(doCreateMovie=False)
|
||||||
|
|
||||||
# unsubscribe events
|
# unsubscribe events
|
||||||
eventManager().unsubscribe(Events.PRINT_STARTED, self.onPrintStarted)
|
eventManager().unsubscribe(Events.PRINT_STARTED, self.on_print_started)
|
||||||
eventManager().unsubscribe(Events.PRINT_FAILED, self.onPrintDone)
|
eventManager().unsubscribe(Events.PRINT_FAILED, self.on_print_done)
|
||||||
eventManager().unsubscribe(Events.PRINT_DONE, self.onPrintDone)
|
eventManager().unsubscribe(Events.PRINT_DONE, self.on_print_done)
|
||||||
eventManager().unsubscribe(Events.PRINT_RESUMED, self.onPrintResumed)
|
eventManager().unsubscribe(Events.PRINT_RESUMED, self.on_print_resumed)
|
||||||
for (event, callback) in self.eventSubscriptions():
|
for (event, callback) in self.event_subscriptions():
|
||||||
eventManager().unsubscribe(event, callback)
|
eventManager().unsubscribe(event, callback)
|
||||||
|
|
||||||
def onPrintStarted(self, event, payload):
|
def on_print_started(self, event, payload):
|
||||||
"""
|
"""
|
||||||
Override this to perform additional actions upon start of a print job.
|
Override this to perform additional actions upon start of a print job.
|
||||||
"""
|
"""
|
||||||
self.startTimelapse(payload["file"])
|
self.start_timelapse(payload["file"])
|
||||||
|
|
||||||
def onPrintDone(self, event, payload):
|
def on_print_done(self, event, payload):
|
||||||
"""
|
"""
|
||||||
Override this to perform additional actions upon the stop of a print job.
|
Override this to perform additional actions upon the stop of a print job.
|
||||||
"""
|
"""
|
||||||
self.stopTimelapse(success=(event==Events.PRINT_DONE))
|
self.stop_timelapse(success=(event==Events.PRINT_DONE))
|
||||||
|
|
||||||
def onPrintResumed(self, event, payload):
|
def on_print_resumed(self, event, payload):
|
||||||
"""
|
"""
|
||||||
Override this to perform additional actions upon the pausing of a print job.
|
Override this to perform additional actions upon the pausing of a print job.
|
||||||
"""
|
"""
|
||||||
if not self._inTimelapse:
|
if not self._in_timelapse:
|
||||||
self.startTimelapse(payload["file"])
|
self.start_timelapse(payload["file"])
|
||||||
|
|
||||||
def eventSubscriptions(self):
|
def event_subscriptions(self):
|
||||||
"""
|
"""
|
||||||
Override this method to subscribe to additional events by returning an array of (event, callback) tuples.
|
Override this method to subscribe to additional events by returning an array of (event, callback) tuples.
|
||||||
|
|
||||||
@@ -178,7 +189,7 @@ class Timelapse(object):
|
|||||||
"""
|
"""
|
||||||
return []
|
return []
|
||||||
|
|
||||||
def configData(self):
|
def config_data(self):
|
||||||
"""
|
"""
|
||||||
Override this method to return the current timelapse configuration data. The data should have the following
|
Override this method to return the current timelapse configuration data. The data should have the following
|
||||||
form:
|
form:
|
||||||
@@ -188,94 +199,142 @@ class Timelapse(object):
|
|||||||
"""
|
"""
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def startTimelapse(self, gcodeFile):
|
def start_timelapse(self, gcodeFile):
|
||||||
self._logger.debug("Starting timelapse for %s" % gcodeFile)
|
self._logger.debug("Starting timelapse for %s" % gcodeFile)
|
||||||
self.cleanCaptureDir()
|
self.clean_capture_dir()
|
||||||
|
|
||||||
self._imageNumber = 0
|
self._image_number = 0
|
||||||
self._inTimelapse = True
|
self._in_timelapse = True
|
||||||
self._gcodeFile = os.path.basename(gcodeFile)
|
self._gcode_file = os.path.basename(gcodeFile)
|
||||||
|
|
||||||
def stopTimelapse(self, doCreateMovie=True, success=True):
|
def stop_timelapse(self, doCreateMovie=True, success=True):
|
||||||
self._logger.debug("Stopping timelapse")
|
self._logger.debug("Stopping timelapse")
|
||||||
|
|
||||||
self._inTimelapse = False
|
self._in_timelapse = False
|
||||||
|
|
||||||
def resetImageNumber():
|
def resetImageNumber():
|
||||||
self._imageNumber = None
|
self._image_number = None
|
||||||
|
|
||||||
def createMovie():
|
def createMovie():
|
||||||
self._renderThread = threading.Thread(target=self._createMovie, kwargs={"success": success})
|
self._render_thread = threading.Thread(target=self._create_movie, kwargs={"success": success})
|
||||||
self._renderThread.daemon = True
|
self._render_thread.daemon = True
|
||||||
self._renderThread.start()
|
self._render_thread.start()
|
||||||
|
|
||||||
def resetAndCreate():
|
def resetAndCreate():
|
||||||
resetImageNumber()
|
resetImageNumber()
|
||||||
createMovie()
|
createMovie()
|
||||||
|
|
||||||
if self._postRoll > 0:
|
def waitForCaptures(callback):
|
||||||
self._postRollStart = time.time()
|
self._capture_queue.put(dict(type=self.__class__.QUEUE_ENTRY_TYPE_CALLBACK, callback=callback))
|
||||||
|
|
||||||
|
def getWaitForCaptures(callback):
|
||||||
|
def f():
|
||||||
|
waitForCaptures(callback)
|
||||||
|
return f
|
||||||
|
|
||||||
|
if self._post_roll > 0:
|
||||||
|
eventManager().fire(Events.POSTROLL_START, dict(postroll_duration=self.calculate_post_roll(), postroll_length=self.post_roll, postroll_fps=self.fps))
|
||||||
|
self._post_roll_start = time.time()
|
||||||
if doCreateMovie:
|
if doCreateMovie:
|
||||||
self._onPostRollDone = resetAndCreate
|
self._on_post_roll_done = getWaitForCaptures(resetAndCreate)
|
||||||
else:
|
else:
|
||||||
self._onPostRollDone = resetImageNumber
|
self._on_post_roll_done = resetImageNumber
|
||||||
self.processPostRoll()
|
self.process_post_roll()
|
||||||
else:
|
else:
|
||||||
self._postRollStart = None
|
self._post_roll_start = None
|
||||||
if doCreateMovie:
|
if doCreateMovie:
|
||||||
resetAndCreate()
|
waitForCaptures(resetAndCreate)
|
||||||
else:
|
else:
|
||||||
resetImageNumber()
|
resetImageNumber()
|
||||||
|
|
||||||
def processPostRoll(self):
|
def calculate_post_roll(self):
|
||||||
pass
|
return None
|
||||||
|
|
||||||
|
def process_post_roll(self):
|
||||||
|
self.post_roll_finished()
|
||||||
|
|
||||||
|
def post_roll_finished(self):
|
||||||
|
if self.post_roll:
|
||||||
|
eventManager().fire(Events.POSTROLL_END)
|
||||||
|
if self._on_post_roll_done is not None:
|
||||||
|
self._on_post_roll_done()
|
||||||
|
|
||||||
def captureImage(self):
|
def captureImage(self):
|
||||||
if self._captureDir is None:
|
if self._capture_dir is None:
|
||||||
self._logger.warn("Cannot capture image, capture directory is unset")
|
self._logger.warn("Cannot capture image, capture directory is unset")
|
||||||
return
|
return
|
||||||
|
|
||||||
if self._imageNumber is None:
|
with self._capture_mutex:
|
||||||
self._logger.warn("Cannot capture image, image number is unset")
|
if self._image_number is None:
|
||||||
return
|
self._logger.warn("Cannot capture image, image number is unset")
|
||||||
|
return
|
||||||
|
|
||||||
|
filename = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
|
||||||
|
self._image_number += 1
|
||||||
|
|
||||||
with self._captureMutex:
|
|
||||||
filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber)
|
|
||||||
self._imageNumber += 1
|
|
||||||
self._logger.debug("Capturing image to %s" % filename)
|
self._logger.debug("Capturing image to %s" % filename)
|
||||||
captureThread = threading.Thread(target=self._captureWorker, kwargs={"filename": filename})
|
entry = dict(type=self.__class__.QUEUE_ENTRY_TYPE_CAPTURE,
|
||||||
captureThread.daemon = True
|
filename=filename,
|
||||||
captureThread.start()
|
onerror=self._on_capture_error)
|
||||||
|
self._capture_queue.put(entry)
|
||||||
return filename
|
return filename
|
||||||
|
|
||||||
def _captureWorker(self, filename):
|
def _on_capture_error(self):
|
||||||
|
with self._capture_mutex:
|
||||||
|
if self._image_number is not None and self._image_number > 0:
|
||||||
|
self._image_number -= 1
|
||||||
|
|
||||||
|
def _capture_queue_worker(self):
|
||||||
|
while self._capture_queue_active:
|
||||||
|
entry = self._capture_queue.get(block=True)
|
||||||
|
|
||||||
|
if entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CAPTURE and "filename" in entry:
|
||||||
|
filename = entry["filename"]
|
||||||
|
onerror = entry.pop("onerror", None)
|
||||||
|
self._perform_capture(filename, onerror=onerror)
|
||||||
|
|
||||||
|
elif entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CALLBACK and "callback" in entry:
|
||||||
|
args = entry.pop("args", [])
|
||||||
|
kwargs = entry.pop("kwargs", dict())
|
||||||
|
entry["callback"](*args, **kwargs)
|
||||||
|
|
||||||
|
def _perform_capture(self, filename, onerror=None):
|
||||||
eventManager().fire(Events.CAPTURE_START, {"file": filename})
|
eventManager().fire(Events.CAPTURE_START, {"file": filename})
|
||||||
try:
|
try:
|
||||||
urllib.urlretrieve(self._snapshotUrl, filename)
|
self._logger.debug("Going to capture %s from %s" % (filename, self._snapshot_url))
|
||||||
self._logger.debug("Image %s captured from %s" % (filename, self._snapshotUrl))
|
r = requests.get(self._snapshot_url, stream=True)
|
||||||
|
with open (filename, "wb") as f:
|
||||||
|
for chunk in r.iter_content(chunk_size=1024):
|
||||||
|
if chunk:
|
||||||
|
f.write(chunk)
|
||||||
|
f.flush()
|
||||||
|
self._logger.debug("Image %s captured from %s" % (filename, self._snapshot_url))
|
||||||
except:
|
except:
|
||||||
self._logger.exception("Could not capture image %s from %s, decreasing image counter again" % (filename, self._snapshotUrl))
|
self._logger.exception("Could not capture image %s from %s" % (filename, self._snapshot_url))
|
||||||
with self._captureMutex:
|
if callable(onerror):
|
||||||
if self._imageNumber is not None and self._imageNumber > 0:
|
onerror()
|
||||||
self._imageNumber -= 1
|
eventManager().fire(Events.CAPTURE_FAILED, {"file": filename})
|
||||||
eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
|
return False
|
||||||
|
else:
|
||||||
|
eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
|
||||||
|
return True
|
||||||
|
|
||||||
def _createMovie(self, success=True):
|
def _create_movie(self, success=True):
|
||||||
ffmpeg = settings().get(["webcam", "ffmpeg"])
|
ffmpeg = settings().get(["webcam", "ffmpeg"])
|
||||||
bitrate = settings().get(["webcam", "bitrate"])
|
bitrate = settings().get(["webcam", "bitrate"])
|
||||||
if ffmpeg is None or bitrate is None:
|
if ffmpeg is None or bitrate is None:
|
||||||
self._logger.warn("Cannot create movie, path to ffmpeg or desired bitrate is unset")
|
self._logger.warn("Cannot create movie, path to ffmpeg or desired bitrate is unset")
|
||||||
return
|
return
|
||||||
|
|
||||||
input = os.path.join(self._captureDir, "tmp_%05d.jpg")
|
input = os.path.join(self._capture_dir, "tmp_%05d.jpg")
|
||||||
if success:
|
if success:
|
||||||
output = os.path.join(self._movieDir, "%s_%s.mpg" % (os.path.splitext(self._gcodeFile)[0], time.strftime("%Y%m%d%H%M%S")))
|
output = os.path.join(self._movie_dir, "%s_%s.mpg" % (os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S")))
|
||||||
else:
|
else:
|
||||||
output = os.path.join(self._movieDir, "%s_%s-failed.mpg" % (os.path.splitext(self._gcodeFile)[0], time.strftime("%Y%m%d%H%M%S")))
|
output = os.path.join(self._movie_dir, "%s_%s-failed.mpg" % (os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S")))
|
||||||
|
|
||||||
# prepare ffmpeg command
|
# prepare ffmpeg command
|
||||||
command = [
|
command = [
|
||||||
ffmpeg, '-framerate', str(self._fps), '-loglevel', 'error', '-i', input, '-vcodec', 'mpeg2video', '-threads', str(self._ffmpegThreads), '-pix_fmt', 'yuv420p', '-r', str(self._fps), '-y', '-b', bitrate,
|
ffmpeg, '-framerate', str(self._fps), '-loglevel', 'error', '-i', input, '-vcodec', 'mpeg2video', '-threads', str(self._ffmpeg_threads), '-pix_fmt', 'yuv420p', '-r', str(self._fps), '-y', '-b', bitrate,
|
||||||
'-f', 'vob']
|
'-f', 'vob']
|
||||||
|
|
||||||
filters = []
|
filters = []
|
||||||
@@ -315,7 +374,7 @@ class Timelapse(object):
|
|||||||
# finalize command with output file
|
# finalize command with output file
|
||||||
self._logger.debug("Rendering movie to %s" % output)
|
self._logger.debug("Rendering movie to %s" % output)
|
||||||
command.append("\"" + output + "\"")
|
command.append("\"" + output + "\"")
|
||||||
eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
|
eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output)})
|
||||||
|
|
||||||
command_str = " ".join(command)
|
command_str = " ".join(command)
|
||||||
self._logger.debug("Executing command: %s" % command_str)
|
self._logger.debug("Executing command: %s" % command_str)
|
||||||
@@ -323,75 +382,74 @@ class Timelapse(object):
|
|||||||
try:
|
try:
|
||||||
p = sarge.run(command_str, stderr=sarge.Capture())
|
p = sarge.run(command_str, stderr=sarge.Capture())
|
||||||
if p.returncode == 0:
|
if p.returncode == 0:
|
||||||
eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
|
eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output)})
|
||||||
else:
|
else:
|
||||||
returncode = p.returncode
|
returncode = p.returncode
|
||||||
stderr_text = p.stderr.text
|
stderr_text = p.stderr.text
|
||||||
self._logger.warn("Could not render movie, got return code %r: %s" % (returncode, stderr_text))
|
self._logger.warn("Could not render movie, got return code %r: %s" % (returncode, stderr_text))
|
||||||
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
|
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
|
||||||
except:
|
except:
|
||||||
self._logger.exception("Could not render movie due to unknown error")
|
self._logger.exception("Could not render movie due to unknown error")
|
||||||
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"})
|
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"})
|
||||||
|
|
||||||
def cleanCaptureDir(self):
|
def clean_capture_dir(self):
|
||||||
if not os.path.isdir(self._captureDir):
|
if not os.path.isdir(self._capture_dir):
|
||||||
self._logger.warn("Cannot clean capture directory, it is unset")
|
self._logger.warn("Cannot clean capture directory, it is unset")
|
||||||
return
|
return
|
||||||
|
|
||||||
for filename in os.listdir(self._captureDir):
|
for filename in os.listdir(self._capture_dir):
|
||||||
if not fnmatch.fnmatch(filename, "*.jpg"):
|
if not fnmatch.fnmatch(filename, "*.jpg"):
|
||||||
continue
|
continue
|
||||||
os.remove(os.path.join(self._captureDir, filename))
|
os.remove(os.path.join(self._capture_dir, filename))
|
||||||
|
|
||||||
|
|
||||||
class ZTimelapse(Timelapse):
|
class ZTimelapse(Timelapse):
|
||||||
def __init__(self, postRoll=0, fps=25):
|
def __init__(self, post_roll=0, fps=25):
|
||||||
Timelapse.__init__(self, postRoll=postRoll, fps=fps)
|
Timelapse.__init__(self, post_roll=post_roll, fps=fps)
|
||||||
self._logger.debug("ZTimelapse initialized")
|
self._logger.debug("ZTimelapse initialized")
|
||||||
|
|
||||||
def eventSubscriptions(self):
|
def event_subscriptions(self):
|
||||||
return [
|
return [
|
||||||
(Events.Z_CHANGE, self._onZChange)
|
(Events.Z_CHANGE, self._on_z_change)
|
||||||
]
|
]
|
||||||
|
|
||||||
def configData(self):
|
def config_data(self):
|
||||||
return {
|
return {
|
||||||
"type": "zchange"
|
"type": "zchange"
|
||||||
}
|
}
|
||||||
|
|
||||||
def processPostRoll(self):
|
def process_post_roll(self):
|
||||||
Timelapse.processPostRoll(self)
|
with self._capture_mutex:
|
||||||
|
filename = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
|
||||||
|
self._image_number += 1
|
||||||
|
|
||||||
filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber)
|
if self._perform_capture(filename):
|
||||||
self._imageNumber += 1
|
for _ in range(self._post_roll * self._fps):
|
||||||
with self._captureMutex:
|
newFile = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
|
||||||
self._captureWorker(filename)
|
self._image_number += 1
|
||||||
|
shutil.copyfile(filename, newFile)
|
||||||
|
|
||||||
for i in range(self._postRoll * self._fps):
|
Timelapse.process_post_roll(self)
|
||||||
newFile = os.path.join(self._captureDir, "tmp_%05d.jpg" % (self._imageNumber))
|
|
||||||
self._imageNumber += 1
|
|
||||||
shutil.copyfile(filename, newFile)
|
|
||||||
|
|
||||||
if self._onPostRollDone is not None:
|
def _on_z_change(self, event, payload):
|
||||||
self._onPostRollDone()
|
|
||||||
|
|
||||||
def _onZChange(self, event, payload):
|
|
||||||
self.captureImage()
|
self.captureImage()
|
||||||
|
|
||||||
|
|
||||||
class TimedTimelapse(Timelapse):
|
class TimedTimelapse(Timelapse):
|
||||||
def __init__(self, postRoll=0, interval=1, fps=25):
|
def __init__(self, post_roll=0, interval=1, fps=25):
|
||||||
Timelapse.__init__(self, postRoll=postRoll, fps=fps)
|
Timelapse.__init__(self, post_roll=post_roll, fps=fps)
|
||||||
self._interval = interval
|
self._interval = interval
|
||||||
if self._interval < 1:
|
if self._interval < 1:
|
||||||
self._interval = 1 # force minimum interval of 1s
|
self._interval = 1 # force minimum interval of 1s
|
||||||
self._timerThread = None
|
self._postroll_captures = 0
|
||||||
|
self._timer = None
|
||||||
self._logger.debug("TimedTimelapse initialized")
|
self._logger.debug("TimedTimelapse initialized")
|
||||||
|
|
||||||
|
@property
|
||||||
def interval(self):
|
def interval(self):
|
||||||
return self._interval
|
return self._interval
|
||||||
|
|
||||||
def configData(self):
|
def config_data(self):
|
||||||
return {
|
return {
|
||||||
"type": "timed",
|
"type": "timed",
|
||||||
"options": {
|
"options": {
|
||||||
@@ -399,25 +457,39 @@ class TimedTimelapse(Timelapse):
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
def onPrintStarted(self, event, payload):
|
def on_print_started(self, event, payload):
|
||||||
Timelapse.onPrintStarted(self, event, payload)
|
Timelapse.on_print_started(self, event, payload)
|
||||||
if self._timerThread is not None:
|
if self._timer is not None:
|
||||||
return
|
return
|
||||||
|
|
||||||
self._timerThread = threading.Thread(target=self._timerWorker)
|
|
||||||
self._timerThread.daemon = True
|
|
||||||
self._timerThread.start()
|
|
||||||
|
|
||||||
def onPrintDone(self, event, payload):
|
|
||||||
Timelapse.onPrintDone(self, event, payload)
|
|
||||||
self._timerThread = None
|
|
||||||
|
|
||||||
def _timerWorker(self):
|
|
||||||
self._logger.debug("Starting timer for interval based timelapse")
|
self._logger.debug("Starting timer for interval based timelapse")
|
||||||
while self._inTimelapse or (self._postRollStart and time.time() - self._postRollStart <= self._postRoll * self._fps):
|
from octoprint.util import RepeatedTimer
|
||||||
self.captureImage()
|
self._timer = RepeatedTimer(self._interval, self._timer_task,
|
||||||
time.sleep(self._interval)
|
run_first=True, condition=self._timer_active,
|
||||||
|
on_finish=self._on_timer_finished)
|
||||||
|
self._timer.start()
|
||||||
|
|
||||||
if self._postRollStart is not None and self._onPostRollDone is not None:
|
def on_print_done(self, event, payload):
|
||||||
self._onPostRollDone()
|
self._postroll_captures = self.post_roll * self.fps
|
||||||
self._postRollStart = None
|
Timelapse.on_print_done(self, event, payload)
|
||||||
|
|
||||||
|
def calculate_post_roll(self):
|
||||||
|
return self.post_roll * self.fps * self.interval
|
||||||
|
|
||||||
|
def process_post_roll(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def post_roll_finished(self):
|
||||||
|
Timelapse.post_roll_finished(self)
|
||||||
|
self._timer = None
|
||||||
|
|
||||||
|
def _timer_active(self):
|
||||||
|
return self._in_timelapse or self._postroll_captures > 0
|
||||||
|
|
||||||
|
def _timer_task(self):
|
||||||
|
self.captureImage()
|
||||||
|
if self._postroll_captures > 0:
|
||||||
|
self._postroll_captures -= 1
|
||||||
|
|
||||||
|
def _on_timer_finished(self):
|
||||||
|
self.post_roll_finished()
|
||||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
+38
-28
@@ -17,29 +17,37 @@ import logging
|
|||||||
|
|
||||||
from octoprint.settings import settings
|
from octoprint.settings import settings
|
||||||
|
|
||||||
|
from octoprint.util import atomic_write
|
||||||
|
|
||||||
class UserManager(object):
|
class UserManager(object):
|
||||||
valid_roles = ["user", "admin"]
|
valid_roles = ["user", "admin"]
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._logger = logging.getLogger(__name__)
|
self._logger = logging.getLogger(__name__)
|
||||||
self._session_users_by_session = dict()
|
self._session_users_by_session = dict()
|
||||||
self._session_users_by_username = dict()
|
self._session_users_by_userid = dict()
|
||||||
|
|
||||||
def login_user(self, user):
|
def login_user(self, user):
|
||||||
self._cleanup_sessions()
|
self._cleanup_sessions()
|
||||||
|
|
||||||
if user is None \
|
if user is None:
|
||||||
or (isinstance(user, LocalProxy) and not isinstance(user._get_current_object(), User)) \
|
return
|
||||||
or (not isinstance(user, LocalProxy) and not isinstance(user, User)):
|
|
||||||
|
if isinstance(user, LocalProxy):
|
||||||
|
user = user._get_current_object()
|
||||||
|
|
||||||
|
if not isinstance(user, User):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
if not isinstance(user, SessionUser):
|
if not isinstance(user, SessionUser):
|
||||||
user = SessionUser(user)
|
user = SessionUser(user)
|
||||||
|
|
||||||
self._session_users_by_session[user.get_session()] = user
|
self._session_users_by_session[user.get_session()] = user
|
||||||
|
|
||||||
if not user.get_name() in self._session_users_by_username:
|
userid = user.get_id()
|
||||||
self._session_users_by_username[user.get_name()] = []
|
if not userid in self._session_users_by_userid:
|
||||||
self._session_users_by_username[user.get_name()].append(user)
|
self._session_users_by_userid[userid] = []
|
||||||
|
self._session_users_by_userid[userid].append(user)
|
||||||
|
|
||||||
self._logger.debug("Logged in user: %r" % user)
|
self._logger.debug("Logged in user: %r" % user)
|
||||||
|
|
||||||
@@ -49,14 +57,18 @@ class UserManager(object):
|
|||||||
if user is None:
|
if user is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if isinstance(user, LocalProxy):
|
||||||
|
user = user._get_current_object()
|
||||||
|
|
||||||
if not isinstance(user, SessionUser):
|
if not isinstance(user, SessionUser):
|
||||||
return
|
return
|
||||||
|
|
||||||
if user.get_name() in self._session_users_by_username:
|
userid = user.get_id()
|
||||||
users_by_username = self._session_users_by_username[user.get_name()]
|
if userid in self._session_users_by_userid:
|
||||||
for u in users_by_username:
|
users_by_userid = self._session_users_by_userid[userid]
|
||||||
|
for u in users_by_userid:
|
||||||
if u.get_session() == user.get_session():
|
if u.get_session() == user.get_session():
|
||||||
users_by_username.remove(u)
|
users_by_userid.remove(u)
|
||||||
break
|
break
|
||||||
|
|
||||||
if user.get_session() in self._session_users_by_session:
|
if user.get_session() in self._session_users_by_session:
|
||||||
@@ -137,21 +149,19 @@ class UserManager(object):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
def removeUser(self, username):
|
def removeUser(self, username):
|
||||||
if username in self._session_users_by_username:
|
if username in self._session_users_by_userid:
|
||||||
users = self._session_users_by_username[username]
|
users = self._session_users_by_userid[username]
|
||||||
sessions = [user.get_session() for user in users if isinstance(user, SessionUser)]
|
sessions = [user.get_session() for user in users if isinstance(user, SessionUser)]
|
||||||
for session in sessions:
|
for session in sessions:
|
||||||
if session in self._session_users_by_session:
|
if session in self._session_users_by_session:
|
||||||
del self._session_users_by_session[session]
|
del self._session_users_by_session[session]
|
||||||
del self._session_users_by_username[username]
|
del self._session_users_by_userid[username]
|
||||||
|
|
||||||
def findUser(self, username=None, session=None):
|
def findUser(self, userid=None, session=None):
|
||||||
if session is not None:
|
if session is not None and session in self._session_users_by_session:
|
||||||
for session in self._session_users_by_session:
|
user = self._session_users_by_session[session]
|
||||||
user = self._session_users_by_session[session]
|
if userid is None or userid == user.get_id():
|
||||||
if username is None or username == user.get_name():
|
return user
|
||||||
return user
|
|
||||||
break
|
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -209,7 +219,7 @@ class FilebasedUserManager(UserManager):
|
|||||||
"settings": user._settings
|
"settings": user._settings
|
||||||
}
|
}
|
||||||
|
|
||||||
with open(self._userfile, "wb") as f:
|
with atomic_write(self._userfile, "wb") as f:
|
||||||
yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||||
self._dirty = False
|
self._dirty = False
|
||||||
self._load()
|
self._load()
|
||||||
@@ -345,16 +355,16 @@ class FilebasedUserManager(UserManager):
|
|||||||
self._dirty = True
|
self._dirty = True
|
||||||
self._save()
|
self._save()
|
||||||
|
|
||||||
def findUser(self, username=None, apikey=None, session=None):
|
def findUser(self, userid=None, apikey=None, session=None):
|
||||||
user = UserManager.findUser(self, username=username, session=session)
|
user = UserManager.findUser(self, userid=userid, session=session)
|
||||||
|
|
||||||
if user is not None:
|
if user is not None:
|
||||||
return user
|
return user
|
||||||
|
|
||||||
if username is not None:
|
if userid is not None:
|
||||||
if username not in self._users.keys():
|
if userid not in self._users.keys():
|
||||||
return None
|
return None
|
||||||
return self._users[username]
|
return self._users[userid]
|
||||||
|
|
||||||
elif apikey is not None:
|
elif apikey is not None:
|
||||||
for user in self._users.values():
|
for user in self._users.values():
|
||||||
@@ -413,7 +423,7 @@ class User(UserMixin):
|
|||||||
return self._passwordHash == passwordHash
|
return self._passwordHash == passwordHash
|
||||||
|
|
||||||
def get_id(self):
|
def get_id(self):
|
||||||
return self._username
|
return self.get_name()
|
||||||
|
|
||||||
def get_name(self):
|
def get_name(self):
|
||||||
return self._username
|
return self._username
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import shutil
|
|||||||
import threading
|
import threading
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
import warnings
|
import warnings
|
||||||
|
import contextlib
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -197,29 +197,12 @@ def get_exception_string():
|
|||||||
return "%s: '%s' @ %s:%s:%d" % (str(sys.exc_info()[0].__name__), str(sys.exc_info()[1]), os.path.basename(locationInfo[0]), locationInfo[2], locationInfo[1])
|
return "%s: '%s' @ %s:%s:%d" % (str(sys.exc_info()[0].__name__), str(sys.exc_info()[1]), os.path.basename(locationInfo[0]), locationInfo[2], locationInfo[1])
|
||||||
|
|
||||||
|
|
||||||
|
@deprecated("get_free_bytes has been deprecated and will be removed in the future",
|
||||||
|
includedoc="Replaced by `psutil.disk_usage <http://pythonhosted.org/psutil/#psutil.disk_usage>`_.",
|
||||||
|
since="1.2.5")
|
||||||
def get_free_bytes(path):
|
def get_free_bytes(path):
|
||||||
"""
|
import psutil
|
||||||
Retrieves the number of free bytes on the partition ``path`` is located at and returns it. Works on both Windows and
|
return psutil.disk_usage(path).free
|
||||||
Unix/Linux.
|
|
||||||
|
|
||||||
Taken from http://stackoverflow.com/a/2372171/2028598
|
|
||||||
|
|
||||||
Arguments:
|
|
||||||
path (string): The path for which to check the remaining partition space.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
int: The amount of bytes still left on the partition.
|
|
||||||
"""
|
|
||||||
|
|
||||||
path = os.path.abspath(path)
|
|
||||||
if sys.platform == "win32":
|
|
||||||
import ctypes
|
|
||||||
freeBytes = ctypes.c_ulonglong(0)
|
|
||||||
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path), None, None, ctypes.pointer(freeBytes))
|
|
||||||
return freeBytes.value
|
|
||||||
else:
|
|
||||||
st = os.statvfs(path)
|
|
||||||
return st.f_bavail * st.f_frsize
|
|
||||||
|
|
||||||
|
|
||||||
def get_dos_filename(origin, existing_filenames=None, extension=None, **kwargs):
|
def get_dos_filename(origin, existing_filenames=None, extension=None, **kwargs):
|
||||||
@@ -513,6 +496,38 @@ def address_for_client(host, port):
|
|||||||
except:
|
except:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
@contextlib.contextmanager
|
||||||
|
def atomic_write(filename, mode="w+b", prefix="tmp", suffix=""):
|
||||||
|
temp_config = tempfile.NamedTemporaryFile(mode=mode, prefix=prefix, suffix=suffix, delete=False)
|
||||||
|
yield temp_config
|
||||||
|
temp_config.close()
|
||||||
|
shutil.move(temp_config.name, filename)
|
||||||
|
|
||||||
|
|
||||||
|
def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs):
|
||||||
|
import codecs
|
||||||
|
|
||||||
|
codec = codecs.lookup(encoding)
|
||||||
|
encoding = codec.name
|
||||||
|
|
||||||
|
if kwargs is None:
|
||||||
|
kwargs = dict()
|
||||||
|
|
||||||
|
potential_bom_attribute = "BOM_" + codec.name.replace("utf-", "utf").upper()
|
||||||
|
if "r" in mode and hasattr(codecs, potential_bom_attribute):
|
||||||
|
# these encodings might have a BOM, so let's see if there is one
|
||||||
|
bom = getattr(codecs, potential_bom_attribute)
|
||||||
|
|
||||||
|
with open(filename, "rb") as f:
|
||||||
|
header = f.read(4)
|
||||||
|
|
||||||
|
if header.startswith(bom):
|
||||||
|
encoding += "-sig"
|
||||||
|
|
||||||
|
return codecs.open(filename, encoding=encoding, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
class RepeatedTimer(threading.Thread):
|
class RepeatedTimer(threading.Thread):
|
||||||
"""
|
"""
|
||||||
This class represents an action that should be run repeatedly in an interval. It is similar to python's
|
This class represents an action that should be run repeatedly in an interval. It is similar to python's
|
||||||
@@ -570,10 +585,18 @@ class RepeatedTimer(threading.Thread):
|
|||||||
run_first (boolean): If set to True, the function will be run for the first time *before* the first wait period.
|
run_first (boolean): If set to True, the function will be run for the first time *before* the first wait period.
|
||||||
If set to False (the default), the function will be run for the first time *after* the first wait period.
|
If set to False (the default), the function will be run for the first time *after* the first wait period.
|
||||||
condition (callable): Condition that needs to be True for loop to continue. Defaults to ``lambda: True``.
|
condition (callable): Condition that needs to be True for loop to continue. Defaults to ``lambda: True``.
|
||||||
|
on_condition_false (callable): Callback to call when the timer finishes due to condition becoming false. Will
|
||||||
|
be called before the ``on_finish`` callback.
|
||||||
|
on_cancelled (callable): Callback to call when the timer finishes due to being cancelled. Will be called
|
||||||
|
before the ``on_finish`` callback.
|
||||||
|
on_finish (callable): Callback to call when the timer finishes, either due to being cancelled or since
|
||||||
|
the condition became false.
|
||||||
daemon (bool): daemon flag to set on underlying thread.
|
daemon (bool): daemon flag to set on underlying thread.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, interval, function, args=None, kwargs=None, run_first=False, condition=None, daemon=True):
|
def __init__(self, interval, function, args=None, kwargs=None,
|
||||||
|
run_first=False, condition=None, on_condition_false=None,
|
||||||
|
on_cancelled=None, on_finish=None, daemon=True):
|
||||||
threading.Thread.__init__(self)
|
threading.Thread.__init__(self)
|
||||||
|
|
||||||
if args is None:
|
if args is None:
|
||||||
@@ -594,10 +617,15 @@ class RepeatedTimer(threading.Thread):
|
|||||||
self.kwargs = kwargs
|
self.kwargs = kwargs
|
||||||
self.run_first = run_first
|
self.run_first = run_first
|
||||||
self.condition = condition
|
self.condition = condition
|
||||||
|
|
||||||
|
self.on_condition_false = on_condition_false
|
||||||
|
self.on_cancelled = on_cancelled
|
||||||
|
self.on_finish = on_finish
|
||||||
|
|
||||||
self.daemon = daemon
|
self.daemon = daemon
|
||||||
|
|
||||||
def cancel(self):
|
def cancel(self):
|
||||||
self.finished.set()
|
self._finish(self.on_cancelled)
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
while self.condition():
|
while self.condition():
|
||||||
@@ -612,15 +640,26 @@ class RepeatedTimer(threading.Thread):
|
|||||||
# wait, but break if we are cancelled
|
# wait, but break if we are cancelled
|
||||||
self.finished.wait(self.interval())
|
self.finished.wait(self.interval())
|
||||||
if self.finished.is_set():
|
if self.finished.is_set():
|
||||||
break
|
return
|
||||||
|
|
||||||
if not self.run_first:
|
if not self.run_first:
|
||||||
# if we are to run the function AFTER waiting for the first time
|
# if we are to run the function AFTER waiting for the first time
|
||||||
self.function(*self.args, **self.kwargs)
|
self.function(*self.args, **self.kwargs)
|
||||||
|
|
||||||
# make sure we set our finished event so we can detect that the loop was finished
|
# we'll only get here if the condition was false
|
||||||
|
self._finish(self.on_condition_false)
|
||||||
|
|
||||||
|
def _finish(self, *callbacks):
|
||||||
self.finished.set()
|
self.finished.set()
|
||||||
|
|
||||||
|
for callback in callbacks:
|
||||||
|
if not callable(callback):
|
||||||
|
continue
|
||||||
|
callback()
|
||||||
|
|
||||||
|
if callable(self.on_finish):
|
||||||
|
self.on_finish()
|
||||||
|
|
||||||
|
|
||||||
class CountedEvent(object):
|
class CountedEvent(object):
|
||||||
|
|
||||||
|
|||||||
+354
-150
@@ -24,13 +24,86 @@ from octoprint.settings import settings, default_settings
|
|||||||
from octoprint.events import eventManager, Events
|
from octoprint.events import eventManager, Events
|
||||||
from octoprint.filemanager import valid_file_type
|
from octoprint.filemanager import valid_file_type
|
||||||
from octoprint.filemanager.destinations import FileDestinations
|
from octoprint.filemanager.destinations import FileDestinations
|
||||||
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer
|
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, to_unicode, bom_aware_open
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import _winreg
|
import _winreg
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# a bunch of regexes we'll need for the communication parsing...
|
||||||
|
|
||||||
|
regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
|
||||||
|
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
|
||||||
|
regex_int_pattern = "\d+"
|
||||||
|
|
||||||
|
regex_command = re.compile("^\s*((?P<commandGM>[GM]\d+)|(?P<commandT>T)\d+)")
|
||||||
|
"""Regex for a GCODE command."""
|
||||||
|
|
||||||
|
regex_float = re.compile(regex_float_pattern)
|
||||||
|
"""Regex for a float value."""
|
||||||
|
|
||||||
|
regexes_parameters = dict(
|
||||||
|
floatP=re.compile("(^|[^A-Za-z])[Pp](?P<value>%s)" % regex_float_pattern),
|
||||||
|
floatS=re.compile("(^|[^A-Za-z])[Ss](?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)
|
||||||
|
)
|
||||||
|
"""Regexes for parsing various GCODE command parameters."""
|
||||||
|
|
||||||
|
regex_minMaxError = re.compile("Error:[0-9]\n")
|
||||||
|
"""Regex matching first line of min/max errors from the firmware."""
|
||||||
|
|
||||||
|
regex_sdPrintingByte = re.compile("(?P<current>[0-9]*)/(?P<total>[0-9]*)")
|
||||||
|
"""Regex matching SD printing status reports.
|
||||||
|
|
||||||
|
Groups will be as follows:
|
||||||
|
|
||||||
|
* ``current``: current byte position in file being printed
|
||||||
|
* ``total``: total size of file being printed
|
||||||
|
"""
|
||||||
|
|
||||||
|
regex_sdFileOpened = re.compile("File opened:\s*(?P<name>.*?)\s+Size:\s*(?P<size>%s)" % regex_int_pattern)
|
||||||
|
"""Regex matching "File opened" messages from the firmware.
|
||||||
|
|
||||||
|
Groups will be as follows:
|
||||||
|
|
||||||
|
* ``name``: name of the file reported as having been opened (str)
|
||||||
|
* ``size``: size of the file in bytes (int)
|
||||||
|
"""
|
||||||
|
|
||||||
|
regex_temp = re.compile("(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?" % (regex_positive_float_pattern, regex_positive_float_pattern))
|
||||||
|
"""Regex matching temperature entries in line.
|
||||||
|
|
||||||
|
Groups will be as follows:
|
||||||
|
|
||||||
|
* ``tool``: whole tool designator, incl. optional ``toolnum`` (str)
|
||||||
|
* ``toolnum``: tool number, if provided (int)
|
||||||
|
* ``actual``: actual temperature (float)
|
||||||
|
* ``target``: target temperature, if provided (float)
|
||||||
|
"""
|
||||||
|
|
||||||
|
regex_repetierTempExtr = re.compile("TargetExtr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern)
|
||||||
|
"""Regex for matching target temp reporting from Repetier.
|
||||||
|
|
||||||
|
Groups will be as follows:
|
||||||
|
|
||||||
|
* ``toolnum``: number of the extruder to which the target temperature
|
||||||
|
report belongs (int)
|
||||||
|
* ``target``: new target temperature (float)
|
||||||
|
"""
|
||||||
|
|
||||||
|
regex_repetierTempBed = re.compile("TargetBed:(?P<target>%s)" % regex_positive_float_pattern)
|
||||||
|
"""Regex for matching target temp reporting from Repetier for beds.
|
||||||
|
|
||||||
|
Groups will be as follows:
|
||||||
|
|
||||||
|
* ``target``: new target temperature (float)
|
||||||
|
"""
|
||||||
|
|
||||||
def serialList():
|
def serialList():
|
||||||
baselist=[]
|
baselist=[]
|
||||||
if os.name=="nt":
|
if os.name=="nt":
|
||||||
@@ -151,6 +224,7 @@ class MachineCom(object):
|
|||||||
|
|
||||||
self._long_running_command = False
|
self._long_running_command = False
|
||||||
self._heating = False
|
self._heating = False
|
||||||
|
self._connection_closing = False
|
||||||
|
|
||||||
self._timeout = None
|
self._timeout = None
|
||||||
|
|
||||||
@@ -158,12 +232,15 @@ class MachineCom(object):
|
|||||||
self._sendChecksumWithUnknownCommands = settings().getBoolean(["feature", "sendChecksumWithUnknownCommands"])
|
self._sendChecksumWithUnknownCommands = settings().getBoolean(["feature", "sendChecksumWithUnknownCommands"])
|
||||||
self._unknownCommandsNeedAck = settings().getBoolean(["feature", "unknownCommandsNeedAck"])
|
self._unknownCommandsNeedAck = settings().getBoolean(["feature", "unknownCommandsNeedAck"])
|
||||||
self._currentLine = 1
|
self._currentLine = 1
|
||||||
|
self._line_mutex = threading.RLock()
|
||||||
self._resendDelta = None
|
self._resendDelta = None
|
||||||
self._lastLines = deque([], 50)
|
self._lastLines = deque([], 50)
|
||||||
self._lastCommError = None
|
self._lastCommError = None
|
||||||
self._lastResendNumber = None
|
self._lastResendNumber = None
|
||||||
self._currentResendCount = 0
|
self._currentResendCount = 0
|
||||||
self._resendSwallowNextOk = False
|
self._resendSwallowNextOk = False
|
||||||
|
self._resendSwallowRepetitions = settings().getBoolean(["feature", "ignoreIdenticalResends"])
|
||||||
|
self._resendSwallowRepetitionsCounter = 0
|
||||||
|
|
||||||
self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
|
self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
|
||||||
self._send_queue = TypedQueue()
|
self._send_queue = TypedQueue()
|
||||||
@@ -195,28 +272,6 @@ class MachineCom(object):
|
|||||||
self._currentFile = None
|
self._currentFile = None
|
||||||
|
|
||||||
# regexes
|
# regexes
|
||||||
floatPattern = "[-+]?[0-9]*\.?[0-9]+"
|
|
||||||
positiveFloatPattern = "[+]?[0-9]*\.?[0-9]+"
|
|
||||||
intPattern = "\d+"
|
|
||||||
self._regex_command = re.compile("^\s*([GM]\d+|T)")
|
|
||||||
self._regex_float = re.compile(floatPattern)
|
|
||||||
self._regex_paramZFloat = re.compile("Z(%s)" % floatPattern)
|
|
||||||
self._regex_paramSInt = re.compile("S(%s)" % intPattern)
|
|
||||||
self._regex_paramNInt = re.compile("N(%s)" % intPattern)
|
|
||||||
self._regex_paramTInt = re.compile("T(%s)" % intPattern)
|
|
||||||
self._regex_minMaxError = re.compile("Error:[0-9]\n")
|
|
||||||
self._regex_sdPrintingByte = re.compile("([0-9]*)/([0-9]*)")
|
|
||||||
self._regex_sdFileOpened = re.compile("File opened:\s*(.*?)\s+Size:\s*(%s)" % intPattern)
|
|
||||||
|
|
||||||
# Regex matching temperature entries in line. Groups will be as follows:
|
|
||||||
# - 1: whole tool designator incl. optional toolNumber ("T", "Tn", "B")
|
|
||||||
# - 2: toolNumber, if given ("", "n", "")
|
|
||||||
# - 3: actual temperature
|
|
||||||
# - 4: whole target substring, if given (e.g. " / 22.0")
|
|
||||||
# - 5: target temperature
|
|
||||||
self._regex_temp = re.compile("(B|T(\d*)):\s*(%s)(\s*\/?\s*(%s))?" % (positiveFloatPattern, positiveFloatPattern))
|
|
||||||
self._regex_repetierTempExtr = re.compile("TargetExtr([0-9]+):(%s)" % positiveFloatPattern)
|
|
||||||
self._regex_repetierTempBed = re.compile("TargetBed:(%s)" % positiveFloatPattern)
|
|
||||||
|
|
||||||
self._long_running_commands = settings().get(["serial", "longRunningCommands"])
|
self._long_running_commands = settings().get(["serial", "longRunningCommands"])
|
||||||
|
|
||||||
@@ -383,6 +438,10 @@ class MachineCom(object):
|
|||||||
##~~ external interface
|
##~~ external interface
|
||||||
|
|
||||||
def close(self, isError = False):
|
def close(self, isError = False):
|
||||||
|
if self._connection_closing:
|
||||||
|
return
|
||||||
|
self._connection_closing = True
|
||||||
|
|
||||||
if self._temperature_timer is not None:
|
if self._temperature_timer is not None:
|
||||||
try:
|
try:
|
||||||
self._temperature_timer.cancel()
|
self._temperature_timer.cancel()
|
||||||
@@ -400,11 +459,15 @@ class MachineCom(object):
|
|||||||
|
|
||||||
printing = self.isPrinting() or self.isPaused()
|
printing = self.isPrinting() or self.isPaused()
|
||||||
if self._serial is not None:
|
if self._serial is not None:
|
||||||
|
try:
|
||||||
|
self._serial.close()
|
||||||
|
except:
|
||||||
|
self._logger.exception("Error while trying to close serial port")
|
||||||
|
isError = True
|
||||||
if isError:
|
if isError:
|
||||||
self._changeState(self.STATE_CLOSED_WITH_ERROR)
|
self._changeState(self.STATE_CLOSED_WITH_ERROR)
|
||||||
else:
|
else:
|
||||||
self._changeState(self.STATE_CLOSED)
|
self._changeState(self.STATE_CLOSED)
|
||||||
self._serial.close()
|
|
||||||
self._serial = None
|
self._serial = None
|
||||||
|
|
||||||
if settings().get(["feature", "sdSupport"]):
|
if settings().get(["feature", "sdSupport"]):
|
||||||
@@ -428,7 +491,7 @@ class MachineCom(object):
|
|||||||
self._clear_to_send.set()
|
self._clear_to_send.set()
|
||||||
|
|
||||||
def sendCommand(self, cmd, cmd_type=None, processed=False):
|
def sendCommand(self, cmd, cmd_type=None, processed=False):
|
||||||
cmd = cmd.encode('ascii', 'replace')
|
cmd = to_unicode(cmd, errors="replace")
|
||||||
if not processed:
|
if not processed:
|
||||||
cmd = process_gcode_line(cmd)
|
cmd = process_gcode_line(cmd)
|
||||||
if not cmd:
|
if not cmd:
|
||||||
@@ -708,51 +771,9 @@ class MachineCom(object):
|
|||||||
|
|
||||||
##~~ communication monitoring and handling
|
##~~ communication monitoring and handling
|
||||||
|
|
||||||
def _parseTemperatures(self, line):
|
|
||||||
result = {}
|
|
||||||
maxToolNum = 0
|
|
||||||
for match in re.finditer(self._regex_temp, line):
|
|
||||||
tool = match.group(1)
|
|
||||||
toolNumber = int(match.group(2)) if match.group(2) and len(match.group(2)) > 0 else None
|
|
||||||
if toolNumber > maxToolNum:
|
|
||||||
maxToolNum = toolNumber
|
|
||||||
|
|
||||||
try:
|
|
||||||
actual = float(match.group(3))
|
|
||||||
target = None
|
|
||||||
if match.group(4) and match.group(5):
|
|
||||||
target = float(match.group(5))
|
|
||||||
|
|
||||||
result[tool] = (toolNumber, actual, target)
|
|
||||||
except ValueError:
|
|
||||||
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
|
|
||||||
pass
|
|
||||||
|
|
||||||
if "T0" in result.keys() and "T" in result.keys():
|
|
||||||
del result["T"]
|
|
||||||
|
|
||||||
return maxToolNum, result
|
|
||||||
|
|
||||||
def _processTemperatures(self, line):
|
def _processTemperatures(self, line):
|
||||||
maxToolNum, parsedTemps = self._parseTemperatures(line)
|
current_tool = self._currentTool if self._currentTool is not None else 0
|
||||||
|
maxToolNum, parsedTemps = parse_temperature_line(line, current_tool)
|
||||||
# extruder temperatures
|
|
||||||
if not "T0" in parsedTemps.keys() and not "T1" in parsedTemps.keys() and "T" in parsedTemps.keys():
|
|
||||||
# no T1 so only single reporting, "T" is our one and only extruder temperature
|
|
||||||
toolNum, actual, target = parsedTemps["T"]
|
|
||||||
|
|
||||||
if target is not None:
|
|
||||||
self._temp[0] = (actual, target)
|
|
||||||
elif 0 in self._temp.keys() and self._temp[0] is not None and isinstance(self._temp[0], tuple):
|
|
||||||
(oldActual, oldTarget) = self._temp[0]
|
|
||||||
self._temp[0] = (actual, oldTarget)
|
|
||||||
else:
|
|
||||||
self._temp[0] = (actual, None)
|
|
||||||
elif not "T0" in parsedTemps.keys() and "T" in parsedTemps.keys():
|
|
||||||
# Smoothieware sends multi extruder temperature data this way: "T:<first extruder> T1:<second extruder> ..." and therefore needs some special treatment...
|
|
||||||
_, actual, target = parsedTemps["T"]
|
|
||||||
del parsedTemps["T"]
|
|
||||||
parsedTemps["T0"] = (0, actual, target)
|
|
||||||
|
|
||||||
if "T0" in parsedTemps.keys():
|
if "T0" in parsedTemps.keys():
|
||||||
for n in range(maxToolNum + 1):
|
for n in range(maxToolNum + 1):
|
||||||
@@ -760,18 +781,18 @@ class MachineCom(object):
|
|||||||
if not tool in parsedTemps.keys():
|
if not tool in parsedTemps.keys():
|
||||||
continue
|
continue
|
||||||
|
|
||||||
toolNum, actual, target = parsedTemps[tool]
|
actual, target = parsedTemps[tool]
|
||||||
if target is not None:
|
if target is not None:
|
||||||
self._temp[toolNum] = (actual, target)
|
self._temp[n] = (actual, target)
|
||||||
elif toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple):
|
elif n in self._temp and self._temp[n] is not None and isinstance(self._temp[n], tuple):
|
||||||
(oldActual, oldTarget) = self._temp[toolNum]
|
(oldActual, oldTarget) = self._temp[n]
|
||||||
self._temp[toolNum] = (actual, oldTarget)
|
self._temp[n] = (actual, oldTarget)
|
||||||
else:
|
else:
|
||||||
self._temp[toolNum] = (actual, None)
|
self._temp[n] = (actual, None)
|
||||||
|
|
||||||
# bed temperature
|
# bed temperature
|
||||||
if "B" in parsedTemps.keys():
|
if "B" in parsedTemps.keys():
|
||||||
toolNum, actual, target = parsedTemps["B"]
|
actual, target = parsedTemps["B"]
|
||||||
if target is not None:
|
if target is not None:
|
||||||
self._bedTemp = (actual, target)
|
self._bedTemp = (actual, target)
|
||||||
elif self._bedTemp is not None and isinstance(self._bedTemp, tuple):
|
elif self._bedTemp is not None and isinstance(self._bedTemp, tuple):
|
||||||
@@ -899,8 +920,8 @@ class MachineCom(object):
|
|||||||
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
|
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
|
||||||
|
|
||||||
elif supportRepetierTargetTemp and ('TargetExtr' in line or 'TargetBed' in line):
|
elif supportRepetierTargetTemp and ('TargetExtr' in line or 'TargetBed' in line):
|
||||||
matchExtr = self._regex_repetierTempExtr.match(line)
|
matchExtr = regex_repetierTempExtr.match(line)
|
||||||
matchBed = self._regex_repetierTempBed.match(line)
|
matchBed = regex_repetierTempBed.match(line)
|
||||||
|
|
||||||
if matchExtr is not None:
|
if matchExtr is not None:
|
||||||
toolNum = int(matchExtr.group(1))
|
toolNum = int(matchExtr.group(1))
|
||||||
@@ -954,18 +975,18 @@ class MachineCom(object):
|
|||||||
self._callback.on_comm_sd_files(self._sdFiles)
|
self._callback.on_comm_sd_files(self._sdFiles)
|
||||||
elif 'SD printing byte' in line and self.isSdPrinting():
|
elif 'SD printing byte' in line and self.isSdPrinting():
|
||||||
# answer to M27, at least on Marlin, Repetier and Sprinter: "SD printing byte %d/%d"
|
# answer to M27, at least on Marlin, Repetier and Sprinter: "SD printing byte %d/%d"
|
||||||
match = self._regex_sdPrintingByte.search(line)
|
match = regex_sdPrintingByte.search(line)
|
||||||
self._currentFile.setFilepos(int(match.group(1)))
|
self._currentFile.setFilepos(int(match.group("current")))
|
||||||
self._callback.on_comm_progress()
|
self._callback.on_comm_progress()
|
||||||
elif 'File opened' in line and not self._ignore_select:
|
elif 'File opened' in line and not self._ignore_select:
|
||||||
# answer to M23, at least on Marlin, Repetier and Sprinter: "File opened:%s Size:%d"
|
# answer to M23, at least on Marlin, Repetier and Sprinter: "File opened:%s Size:%d"
|
||||||
match = self._regex_sdFileOpened.search(line)
|
match = regex_sdFileOpened.search(line)
|
||||||
if self._sdFileToSelect:
|
if self._sdFileToSelect:
|
||||||
name = self._sdFileToSelect
|
name = self._sdFileToSelect
|
||||||
self._sdFileToSelect = None
|
self._sdFileToSelect = None
|
||||||
else:
|
else:
|
||||||
name = match.group(1)
|
name = match.group("name")
|
||||||
self._currentFile = PrintingSdFileInformation(name, int(match.group(2)))
|
self._currentFile = PrintingSdFileInformation(name, int(match.group("size")))
|
||||||
elif 'File selected' in line:
|
elif 'File selected' in line:
|
||||||
if self._ignore_select:
|
if self._ignore_select:
|
||||||
self._ignore_select = False
|
self._ignore_select = False
|
||||||
@@ -1299,10 +1320,10 @@ class MachineCom(object):
|
|||||||
# Marlin reports an MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
|
# Marlin reports an MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
|
||||||
# But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
|
# But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
|
||||||
# So we can have an extra newline in the most common case. Awesome work people.
|
# So we can have an extra newline in the most common case. Awesome work people.
|
||||||
if self._regex_minMaxError.match(line):
|
if regex_minMaxError.match(line):
|
||||||
line = line.rstrip() + self._readline()
|
line = line.rstrip() + self._readline()
|
||||||
|
|
||||||
if 'line number' in line.lower() or 'checksum' in line.lower() or 'expected line' in line.lower():
|
if 'line number' in line.lower() or 'checksum' in line.lower() or 'format error' in line.lower() or 'expected line' in line.lower():
|
||||||
#Skip the communication errors, as those get corrected.
|
#Skip the communication errors, as those get corrected.
|
||||||
self._lastCommError = line[6:] if line.startswith("Error:") else line[2:]
|
self._lastCommError = line[6:] if line.startswith("Error:") else line[2:]
|
||||||
pass
|
pass
|
||||||
@@ -1317,14 +1338,17 @@ class MachineCom(object):
|
|||||||
return line
|
return line
|
||||||
|
|
||||||
def _readline(self):
|
def _readline(self):
|
||||||
if self._serial == None:
|
if self._serial is None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ret = self._serial.readline()
|
ret = self._serial.readline()
|
||||||
except:
|
except:
|
||||||
self._log("Unexpected error while reading serial port: %s" % (get_exception_string()))
|
if not self._connection_closing:
|
||||||
self._errorValue = get_exception_string()
|
self._logger.exception("Unexpected error while reading from serial port")
|
||||||
self.close(True)
|
self._log("Unexpected error while reading serial port, please consult octoprint.log for details: %s" % (get_exception_string()))
|
||||||
|
self._errorValue = get_exception_string()
|
||||||
|
self.close(True)
|
||||||
return None
|
return None
|
||||||
if ret == '':
|
if ret == '':
|
||||||
#self._log("Recv: TIMEOUT")
|
#self._log("Recv: TIMEOUT")
|
||||||
@@ -1401,9 +1425,18 @@ class MachineCom(object):
|
|||||||
self._currentResendCount += 1
|
self._currentResendCount += 1
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# If we ignore resend repetitions (Repetier firmware...), check if we
|
||||||
|
# need to do this now. If the same line number has been requested we
|
||||||
|
# already saw and resent, we'll ignore it up to <counter> times.
|
||||||
|
if self._resendSwallowRepetitions and lineToResend == self._lastResendNumber and self._resendSwallowRepetitionsCounter > 0:
|
||||||
|
self._logger.debug("Ignoring resend request for line %d, that is probably a repetition sent by the firmware to ensure it arrives, not a real request" % lineToResend)
|
||||||
|
self._resendSwallowRepetitionsCounter -= 1
|
||||||
|
return
|
||||||
|
|
||||||
self._resendDelta = resendDelta
|
self._resendDelta = resendDelta
|
||||||
self._lastResendNumber = lineToResend
|
self._lastResendNumber = lineToResend
|
||||||
self._currentResendCount = 0
|
self._currentResendCount = 0
|
||||||
|
self._resendSwallowRepetitionsCounter = settings().getInt(["feature", "identicalResendsCountdown"])
|
||||||
|
|
||||||
if self._resendDelta > len(self._lastLines) or len(self._lastLines) == 0 or self._resendDelta < 0:
|
if self._resendDelta > len(self._lastLines) or len(self._lastLines) == 0 or self._resendDelta < 0:
|
||||||
self._errorValue = "Printer requested line %d but no sufficient history is available, can't resend" % lineToResend
|
self._errorValue = "Printer requested line %d but no sufficient history is available, can't resend" % lineToResend
|
||||||
@@ -1460,25 +1493,6 @@ class MachineCom(object):
|
|||||||
# trigger the "queued" phase only if we are not streaming to sd right now
|
# trigger the "queued" phase only if we are not streaming to sd right now
|
||||||
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
|
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
|
||||||
|
|
||||||
def gcode_command_for_cmd(self, cmd):
|
|
||||||
"""
|
|
||||||
Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0").
|
|
||||||
|
|
||||||
Arguments:
|
|
||||||
cmd (str): The command to try to parse.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str or None: The GCODE command identifier if it could be parsed, or None if not.
|
|
||||||
"""
|
|
||||||
if not cmd:
|
|
||||||
return None
|
|
||||||
|
|
||||||
gcode = self._regex_command.search(cmd)
|
|
||||||
if not gcode:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return gcode.group(1)
|
|
||||||
|
|
||||||
##~~ send loop handling
|
##~~ 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):
|
||||||
@@ -1519,7 +1533,7 @@ class MachineCom(object):
|
|||||||
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
|
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
|
||||||
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
|
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
|
||||||
# at hand here and only clear our clear_to_send flag later if that's the case
|
# at hand here and only clear our clear_to_send flag later if that's the case
|
||||||
gcode = self.gcode_command_for_cmd(command)
|
gcode = gcode_command_for_cmd(command)
|
||||||
|
|
||||||
if linenumber is not None:
|
if linenumber is not None:
|
||||||
# line number predetermined - this only happens for resends, so we'll use the number and
|
# line number predetermined - this only happens for resends, so we'll use the number and
|
||||||
@@ -1535,13 +1549,11 @@ class MachineCom(object):
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
# now comes the part where we increase line numbers and send stuff - no turning back now
|
# now comes the part where we increase line numbers and send stuff - no turning back now
|
||||||
|
command_to_send = command.encode("ascii", errors="replace")
|
||||||
if (gcode is not None or self._sendChecksumWithUnknownCommands) and (self.isPrinting() or self._alwaysSendChecksum):
|
if (gcode is not None or self._sendChecksumWithUnknownCommands) and (self.isPrinting() or self._alwaysSendChecksum):
|
||||||
linenumber = self._currentLine
|
self._doIncrementAndSendWithChecksum(command_to_send)
|
||||||
self._addToLastLines(command)
|
|
||||||
self._currentLine += 1
|
|
||||||
self._doSendWithChecksum(command, linenumber)
|
|
||||||
else:
|
else:
|
||||||
self._doSendWithoutChecksum(command)
|
self._doSendWithoutChecksum(command_to_send)
|
||||||
|
|
||||||
# trigger "sent" phase and use up one "ok"
|
# trigger "sent" phase and use up one "ok"
|
||||||
self._process_command_phase("sent", command, command_type, gcode=gcode)
|
self._process_command_phase("sent", command, command_type, gcode=gcode)
|
||||||
@@ -1567,7 +1579,7 @@ class MachineCom(object):
|
|||||||
return command, command_type, gcode
|
return command, command_type, gcode
|
||||||
|
|
||||||
if gcode is None:
|
if gcode is None:
|
||||||
gcode = self.gcode_command_for_cmd(command)
|
gcode = gcode_command_for_cmd(command)
|
||||||
|
|
||||||
# send it through the phase specific handlers provided by plugins
|
# send it through the phase specific handlers provided by plugins
|
||||||
for name, hook in self._gcode_hooks[phase].items():
|
for name, hook in self._gcode_hooks[phase].items():
|
||||||
@@ -1622,11 +1634,18 @@ class MachineCom(object):
|
|||||||
# handler returned a tuple of an unexpected length
|
# handler returned a tuple of an unexpected length
|
||||||
return original_tuple
|
return original_tuple
|
||||||
|
|
||||||
gcode = self.gcode_command_for_cmd(command)
|
gcode = gcode_command_for_cmd(command)
|
||||||
return command, command_type, gcode
|
return command, command_type, gcode
|
||||||
|
|
||||||
##~~ actual sending via serial
|
##~~ actual sending via serial
|
||||||
|
|
||||||
|
def _doIncrementAndSendWithChecksum(self, cmd):
|
||||||
|
with self._line_mutex:
|
||||||
|
linenumber = self._currentLine
|
||||||
|
self._addToLastLines(cmd)
|
||||||
|
self._currentLine += 1
|
||||||
|
self._doSendWithChecksum(cmd, linenumber)
|
||||||
|
|
||||||
def _doSendWithChecksum(self, cmd, lineNumber):
|
def _doSendWithChecksum(self, cmd, lineNumber):
|
||||||
commandToSend = "N%d %s" % (lineNumber, cmd)
|
commandToSend = "N%d %s" % (lineNumber, cmd)
|
||||||
checksum = reduce(lambda x,y:x^y, map(ord, commandToSend))
|
checksum = reduce(lambda x,y:x^y, map(ord, commandToSend))
|
||||||
@@ -1634,6 +1653,9 @@ class MachineCom(object):
|
|||||||
self._doSendWithoutChecksum(commandToSend)
|
self._doSendWithoutChecksum(commandToSend)
|
||||||
|
|
||||||
def _doSendWithoutChecksum(self, cmd):
|
def _doSendWithoutChecksum(self, cmd):
|
||||||
|
if self._serial is None:
|
||||||
|
return
|
||||||
|
|
||||||
self._log("Send: %s" % cmd)
|
self._log("Send: %s" % cmd)
|
||||||
try:
|
try:
|
||||||
self._serial.write(cmd + '\n')
|
self._serial.write(cmd + '\n')
|
||||||
@@ -1642,29 +1664,31 @@ class MachineCom(object):
|
|||||||
try:
|
try:
|
||||||
self._serial.write(cmd + '\n')
|
self._serial.write(cmd + '\n')
|
||||||
except:
|
except:
|
||||||
|
if not self._connection_closing:
|
||||||
|
self._logger.exception("Unexpected error while writing to serial port")
|
||||||
|
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
|
||||||
|
self._errorValue = get_exception_string()
|
||||||
|
self.close(True)
|
||||||
|
except:
|
||||||
|
if not self._connection_closing:
|
||||||
self._logger.exception("Unexpected error while writing to serial port")
|
self._logger.exception("Unexpected error while writing to serial port")
|
||||||
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
|
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
|
||||||
self._errorValue = get_exception_string()
|
self._errorValue = get_exception_string()
|
||||||
self.close(True)
|
self.close(True)
|
||||||
except:
|
|
||||||
self._logger.exception("Unexpected error while writing to serial port")
|
|
||||||
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
|
|
||||||
self._errorValue = get_exception_string()
|
|
||||||
self.close(True)
|
|
||||||
|
|
||||||
##~~ command handlers
|
##~~ command handlers
|
||||||
|
|
||||||
def _gcode_T_sent(self, cmd, cmd_type=None):
|
def _gcode_T_sent(self, cmd, cmd_type=None):
|
||||||
toolMatch = self._regex_paramTInt.search(cmd)
|
toolMatch = regexes_parameters["intT"].search(cmd)
|
||||||
if toolMatch:
|
if toolMatch:
|
||||||
self._currentTool = int(toolMatch.group(1))
|
self._currentTool = int(toolMatch.group("value"))
|
||||||
|
|
||||||
def _gcode_G0_sent(self, cmd, cmd_type=None):
|
def _gcode_G0_sent(self, cmd, cmd_type=None):
|
||||||
if 'Z' in cmd:
|
if 'Z' in cmd:
|
||||||
match = self._regex_paramZFloat.search(cmd)
|
match = regexes_parameters["floatZ"].search(cmd)
|
||||||
if match:
|
if match:
|
||||||
try:
|
try:
|
||||||
z = float(match.group(1))
|
z = float(match.group("value"))
|
||||||
if self._currentZ != z:
|
if self._currentZ != z:
|
||||||
self._currentZ = z
|
self._currentZ = z
|
||||||
self._callback.on_comm_z_change(z)
|
self._callback.on_comm_z_change(z)
|
||||||
@@ -1679,13 +1703,13 @@ class MachineCom(object):
|
|||||||
|
|
||||||
def _gcode_M104_sent(self, cmd, cmd_type=None):
|
def _gcode_M104_sent(self, cmd, cmd_type=None):
|
||||||
toolNum = self._currentTool
|
toolNum = self._currentTool
|
||||||
toolMatch = self._regex_paramTInt.search(cmd)
|
toolMatch = regexes_parameters["intT"].search(cmd)
|
||||||
if toolMatch:
|
if toolMatch:
|
||||||
toolNum = int(toolMatch.group(1))
|
toolNum = int(toolMatch.group("value"))
|
||||||
match = self._regex_paramSInt.search(cmd)
|
match = regexes_parameters["floatS"].search(cmd)
|
||||||
if match:
|
if match:
|
||||||
try:
|
try:
|
||||||
target = float(match.group(1))
|
target = float(match.group("value"))
|
||||||
if toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple):
|
if toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple):
|
||||||
(actual, oldTarget) = self._temp[toolNum]
|
(actual, oldTarget) = self._temp[toolNum]
|
||||||
self._temp[toolNum] = (actual, target)
|
self._temp[toolNum] = (actual, target)
|
||||||
@@ -1695,10 +1719,10 @@ class MachineCom(object):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
def _gcode_M140_sent(self, cmd, cmd_type=None):
|
def _gcode_M140_sent(self, cmd, cmd_type=None):
|
||||||
match = self._regex_paramSInt.search(cmd)
|
match = regexes_parameters["floatS"].search(cmd)
|
||||||
if match:
|
if match:
|
||||||
try:
|
try:
|
||||||
target = float(match.group(1))
|
target = float(match.group("value"))
|
||||||
if self._bedTemp is not None and isinstance(self._bedTemp, tuple):
|
if self._bedTemp is not None and isinstance(self._bedTemp, tuple):
|
||||||
(actual, oldTarget) = self._bedTemp
|
(actual, oldTarget) = self._bedTemp
|
||||||
self._bedTemp = (actual, target)
|
self._bedTemp = (actual, target)
|
||||||
@@ -1721,37 +1745,61 @@ class MachineCom(object):
|
|||||||
|
|
||||||
def _gcode_M110_sending(self, cmd, cmd_type=None):
|
def _gcode_M110_sending(self, cmd, cmd_type=None):
|
||||||
newLineNumber = None
|
newLineNumber = None
|
||||||
match = self._regex_paramNInt.search(cmd)
|
match = regexes_parameters["intN"].search(cmd)
|
||||||
if match:
|
if match:
|
||||||
try:
|
try:
|
||||||
newLineNumber = int(match.group(1))
|
newLineNumber = int(match.group("value"))
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
newLineNumber = 0
|
newLineNumber = 0
|
||||||
|
|
||||||
# send M110 command with new line number
|
with self._line_mutex:
|
||||||
self._currentLine = newLineNumber
|
# send M110 command with new line number
|
||||||
|
self._currentLine = newLineNumber
|
||||||
|
|
||||||
# after a reset of the line number we have no way to determine what line exactly the printer now wants
|
# after a reset of the line number we have no way to determine what line exactly the printer now wants
|
||||||
self._lastLines.clear()
|
self._lastLines.clear()
|
||||||
self._resendDelta = None
|
self._resendDelta = None
|
||||||
|
|
||||||
def _gcode_M112_queuing(self, cmd, cmd_type=None): # It's an emergency what todo? Canceling the print should be the minimum
|
def _gcode_M112_queuing(self, cmd, cmd_type=None):
|
||||||
self.cancelPrint()
|
# emergency stop, jump the queue with the M112
|
||||||
|
self._doSendWithoutChecksum("M112")
|
||||||
|
self._doIncrementAndSendWithChecksum("M112")
|
||||||
|
|
||||||
|
# No idea if the printer is still listening or if M112 won. Just in case
|
||||||
|
# we'll now try to also manually make sure all heaters are shut off - better
|
||||||
|
# safe than sorry. We do this ignoring the queue since at this point it
|
||||||
|
# is irrelevant whether the printer has sent enough ack's or not, we
|
||||||
|
# are going to shutdown the connection in a second anyhow.
|
||||||
|
for tool in range(self._printerProfileManager.get_current_or_default()["extruder"]["count"]):
|
||||||
|
self._doIncrementAndSendWithChecksum("M104 T{tool} S0".format(tool=tool))
|
||||||
|
self._doIncrementAndSendWithChecksum("M140 S0")
|
||||||
|
|
||||||
|
# close to reset host state
|
||||||
|
self._errorValue = "Closing serial port due to emergency stop M112."
|
||||||
|
self._log(self._errorValue)
|
||||||
|
self.close(isError=True)
|
||||||
|
|
||||||
|
# fire the M112 event since we sent it and we're going to prevent the caller from seeing it
|
||||||
|
gcode = "M112"
|
||||||
|
if gcode in gcodeToEvent:
|
||||||
|
eventManager().fire(gcodeToEvent[gcode])
|
||||||
|
|
||||||
|
# return None 1-tuple to eat the one that is queuing because we don't want to send it twice
|
||||||
|
# I hope it got it the first time because as far as I can tell, there is no way to know
|
||||||
|
return None,
|
||||||
|
|
||||||
def _gcode_G4_sent(self, cmd, cmd_type=None):
|
def _gcode_G4_sent(self, cmd, cmd_type=None):
|
||||||
# we are intending to dwell for a period of time, increase the timeout to match
|
# we are intending to dwell for a period of time, increase the timeout to match
|
||||||
cmd = cmd.upper()
|
p_match = regexes_parameters["floatP"].search(cmd)
|
||||||
p_idx = cmd.find('P')
|
s_match = regexes_parameters["floatS"].search(cmd)
|
||||||
s_idx = cmd.find('S')
|
|
||||||
_timeout = 0
|
_timeout = 0
|
||||||
if p_idx != -1:
|
if p_match:
|
||||||
# dwell time is specified in milliseconds
|
_timeout = float(p_match.group("value")) / 1000.0
|
||||||
_timeout = float(cmd[p_idx+1:]) / 1000.0
|
elif s_match:
|
||||||
elif s_idx != -1:
|
_timeout = float(s_match.group("value"))
|
||||||
# dwell time is specified in seconds
|
|
||||||
_timeout = float(cmd[s_idx+1:])
|
|
||||||
self._timeout = get_new_timeout("communication") + _timeout
|
self._timeout = get_new_timeout("communication") + _timeout
|
||||||
|
|
||||||
##~~ command phase handlers
|
##~~ command phase handlers
|
||||||
@@ -1905,7 +1953,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
|
|||||||
Opens the file for reading and determines the file size.
|
Opens the file for reading and determines the file size.
|
||||||
"""
|
"""
|
||||||
PrintingFileInformation.start(self)
|
PrintingFileInformation.start(self)
|
||||||
self._handle = open(self._filename, "r")
|
self._handle = bom_aware_open(self._filename, encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
"""
|
"""
|
||||||
@@ -1935,7 +1983,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
|
|||||||
if self._handle is None:
|
if self._handle is None:
|
||||||
# file got closed just now
|
# file got closed just now
|
||||||
return None
|
return None
|
||||||
line = self._handle.readline()
|
line = to_unicode(self._handle.readline())
|
||||||
if not line:
|
if not line:
|
||||||
self.close()
|
self.close()
|
||||||
processed = process_gcode_line(line, offsets=offsets, current_tool=current_tool)
|
processed = process_gcode_line(line, offsets=offsets, current_tool=current_tool)
|
||||||
@@ -2141,3 +2189,159 @@ def convert_feedback_controls(configured_controls):
|
|||||||
|
|
||||||
return feedback_controls, feedback_matcher
|
return feedback_controls, feedback_matcher
|
||||||
|
|
||||||
|
def canonicalize_temperatures(parsed, current):
|
||||||
|
"""
|
||||||
|
Canonicalizes the temperatures provided in parsed.
|
||||||
|
|
||||||
|
Will make sure that returned result only contains extruder keys
|
||||||
|
like Tn, so always qualified with a tool number.
|
||||||
|
|
||||||
|
The algorithm for cleaning up the parsed keys is the following:
|
||||||
|
|
||||||
|
* If ``T`` is not included with the reported extruders, return
|
||||||
|
* If more than just ``T`` is reported:
|
||||||
|
* If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove
|
||||||
|
``T`` from the result.
|
||||||
|
* Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
|
||||||
|
* If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
|
||||||
|
* return
|
||||||
|
|
||||||
|
Arguments:
|
||||||
|
parsed (dict): the parsed temperatures (mapping tool => (actual, target))
|
||||||
|
to canonicalize
|
||||||
|
current (int): the current active extruder
|
||||||
|
Returns:
|
||||||
|
dict: the canonicalized version of ``parsed``
|
||||||
|
"""
|
||||||
|
|
||||||
|
reported_extruders = filter(lambda x: x.startswith("T"), parsed.keys())
|
||||||
|
if not "T" in reported_extruders:
|
||||||
|
# Our reported_extruders are either empty or consist purely
|
||||||
|
# of Tn keys, no need for any action
|
||||||
|
return parsed
|
||||||
|
|
||||||
|
current_tool_key = "T%d" % current
|
||||||
|
result = dict(parsed)
|
||||||
|
|
||||||
|
if len(reported_extruders) > 1:
|
||||||
|
if "T0" in reported_extruders:
|
||||||
|
# Both T and T0 are present, so T contains the current
|
||||||
|
# extruder's temperature, e.g. for current_tool == 1:
|
||||||
|
#
|
||||||
|
# T:<T1> T0:<T0> T2:<T2> ... B:<B>
|
||||||
|
#
|
||||||
|
# becomes
|
||||||
|
#
|
||||||
|
# T0:<T1> T1:<T1> T2:<T2> ... B:<B>
|
||||||
|
#
|
||||||
|
# Same goes if Tc is already present, it will be overwritten:
|
||||||
|
#
|
||||||
|
# T:<T1> T0:<T0> T1:<T1> T2:<T2> ... B:<B>
|
||||||
|
#
|
||||||
|
# becomes
|
||||||
|
#
|
||||||
|
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
|
||||||
|
result[current_tool_key] = result["T"]
|
||||||
|
del result["T"]
|
||||||
|
else:
|
||||||
|
# So T is there, but T0 isn't. That looks like Smoothieware which
|
||||||
|
# always reports the first extruder T0 as T:
|
||||||
|
#
|
||||||
|
# T:<T0> T1:<T1> T2:<T2> ... B:<B>
|
||||||
|
#
|
||||||
|
# becomes
|
||||||
|
#
|
||||||
|
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
|
||||||
|
result["T0"] = result["T"]
|
||||||
|
del result["T"]
|
||||||
|
|
||||||
|
else:
|
||||||
|
# We only have T. That can mean two things:
|
||||||
|
#
|
||||||
|
# * we only have one extruder at all, or
|
||||||
|
# * we are currently parsing a response to M109/M190, which on
|
||||||
|
# some firmwares doesn't report the full M105 output while
|
||||||
|
# waiting for the target temperature to be reached but only
|
||||||
|
# reports the current tool and bed
|
||||||
|
#
|
||||||
|
# In both cases it is however safe to just move our T over
|
||||||
|
# to T<current> in the parsed data, current should always stay
|
||||||
|
# 0 for single extruder printers. E.g. for current_tool == 1:
|
||||||
|
#
|
||||||
|
# T:<T1>
|
||||||
|
#
|
||||||
|
# becomes
|
||||||
|
#
|
||||||
|
# T1:<T1>
|
||||||
|
|
||||||
|
result[current_tool_key] = result["T"]
|
||||||
|
del result["T"]
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
def parse_temperature_line(line, current):
|
||||||
|
"""
|
||||||
|
Parses the provided temperature line.
|
||||||
|
|
||||||
|
The result will be a dictionary mapping from the extruder or bed key to
|
||||||
|
a tuple with current and target temperature. The result will be canonicalized
|
||||||
|
with :func:`canonicalize_temperatures` before returning.
|
||||||
|
|
||||||
|
Arguments:
|
||||||
|
line (str): the temperature line to parse
|
||||||
|
current (int): the current active extruder
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple: a 2-tuple with the maximum tool number and a dict mapping from
|
||||||
|
key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B``
|
||||||
|
"""
|
||||||
|
|
||||||
|
result = {}
|
||||||
|
maxToolNum = 0
|
||||||
|
for match in re.finditer(regex_temp, line):
|
||||||
|
values = match.groupdict()
|
||||||
|
tool = values["tool"]
|
||||||
|
toolnum = values.get("toolnum", None)
|
||||||
|
toolNumber = int(toolnum) if toolnum is not None and len(toolnum) else None
|
||||||
|
if toolNumber > maxToolNum:
|
||||||
|
maxToolNum = toolNumber
|
||||||
|
|
||||||
|
try:
|
||||||
|
actual = float(match.group(3))
|
||||||
|
target = None
|
||||||
|
if match.group(4) and match.group(5):
|
||||||
|
target = float(match.group(5))
|
||||||
|
|
||||||
|
result[tool] = (actual, target)
|
||||||
|
except ValueError:
|
||||||
|
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
|
||||||
|
pass
|
||||||
|
|
||||||
|
return max(maxToolNum, current), canonicalize_temperatures(result, current)
|
||||||
|
|
||||||
|
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").
|
||||||
|
|
||||||
|
Arguments:
|
||||||
|
cmd (str): The command to try to parse.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str or None: The GCODE command identifier if it could be parsed, or None if not.
|
||||||
|
"""
|
||||||
|
if not cmd:
|
||||||
|
return None
|
||||||
|
|
||||||
|
gcode = regex_command.search(cmd)
|
||||||
|
if not gcode:
|
||||||
|
return None
|
||||||
|
|
||||||
|
values = gcode.groupdict()
|
||||||
|
if "commandGM" in values and values["commandGM"]:
|
||||||
|
return values["commandGM"]
|
||||||
|
elif "commandT" in values and values["commandT"]:
|
||||||
|
return values["commandT"]
|
||||||
|
else:
|
||||||
|
# this should never happen
|
||||||
|
return None
|
||||||
|
|
||||||
@@ -35,7 +35,9 @@ class gcode(object):
|
|||||||
if os.path.isfile(filename):
|
if os.path.isfile(filename):
|
||||||
self.filename = filename
|
self.filename = filename
|
||||||
self._fileSize = os.stat(filename).st_size
|
self._fileSize = os.stat(filename).st_size
|
||||||
with open(filename, "r") as f:
|
|
||||||
|
import codecs
|
||||||
|
with codecs.open(filename, encoding="utf-8", errors="replace") as f:
|
||||||
self._load(f, printer_profile, throttle=throttle)
|
self._load(f, printer_profile, throttle=throttle)
|
||||||
|
|
||||||
def abort(self):
|
def abort(self):
|
||||||
|
|||||||
@@ -21,14 +21,16 @@ class PipCaller(object):
|
|||||||
def __init__(self, configured=None):
|
def __init__(self, configured=None):
|
||||||
self._logger = logging.getLogger(__name__)
|
self._logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
self._configured = configured
|
self.configured = configured
|
||||||
|
self.refresh = False
|
||||||
|
|
||||||
self._command = None
|
self._command = None
|
||||||
self._version = None
|
self._version = None
|
||||||
|
self._version_string = None
|
||||||
|
self._use_sudo = False
|
||||||
|
|
||||||
self._command, self._version = self._find_pip()
|
self.trigger_refresh()
|
||||||
|
|
||||||
self.refresh = False
|
|
||||||
self.on_log_call = lambda *args, **kwargs: None
|
self.on_log_call = lambda *args, **kwargs: None
|
||||||
self.on_log_stdout = lambda *args, **kwargs: None
|
self.on_log_stdout = lambda *args, **kwargs: None
|
||||||
self.on_log_stderr = lambda *args, **kwargs: None
|
self.on_log_stderr = lambda *args, **kwargs: None
|
||||||
@@ -53,19 +55,37 @@ class PipCaller(object):
|
|||||||
def version(self):
|
def version(self):
|
||||||
return self._version
|
return self._version
|
||||||
|
|
||||||
|
@property
|
||||||
|
def version_string(self):
|
||||||
|
return self._version_string
|
||||||
|
|
||||||
|
@property
|
||||||
|
def use_sudo(self):
|
||||||
|
return self._use_sudo
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def available(self):
|
def available(self):
|
||||||
return self._command is not None
|
return self._command is not None
|
||||||
|
|
||||||
|
def trigger_refresh(self):
|
||||||
|
try:
|
||||||
|
self._command, self._version, self._version_string, self._use_sudo = self._find_pip()
|
||||||
|
except:
|
||||||
|
self._logger.exception("Error while discovering pip command")
|
||||||
|
self._command = None
|
||||||
|
self._version = None
|
||||||
|
self.refresh = False
|
||||||
|
|
||||||
def execute(self, *args):
|
def execute(self, *args):
|
||||||
if self.refresh:
|
if self.refresh:
|
||||||
self._command, self._version = self._find_pip()
|
self.trigger_refresh()
|
||||||
self.refresh = False
|
|
||||||
|
|
||||||
if self._command is None:
|
if self._command is None:
|
||||||
raise UnknownPip()
|
raise UnknownPip()
|
||||||
|
|
||||||
command = [self._command] + list(args)
|
command = [self._command] + list(args)
|
||||||
|
if self._use_sudo:
|
||||||
|
command = ["sudo"] + command
|
||||||
|
|
||||||
joined_command = " ".join(command)
|
joined_command = " ".join(command)
|
||||||
self._logger.debug(u"Calling: {}".format(joined_command))
|
self._logger.debug(u"Calling: {}".format(joined_command))
|
||||||
@@ -111,8 +131,16 @@ class PipCaller(object):
|
|||||||
|
|
||||||
|
|
||||||
def _find_pip(self):
|
def _find_pip(self):
|
||||||
pip_command = self._configured
|
pip_command = self.configured
|
||||||
|
|
||||||
|
if pip_command is not None and pip_command.startswith("sudo "):
|
||||||
|
pip_command = pip_command[len("sudo "):]
|
||||||
|
pip_sudo = True
|
||||||
|
else:
|
||||||
|
pip_sudo = False
|
||||||
|
|
||||||
pip_version = None
|
pip_version = None
|
||||||
|
version_segment = None
|
||||||
|
|
||||||
if pip_command is None:
|
if pip_command is None:
|
||||||
import os
|
import os
|
||||||
@@ -144,7 +172,11 @@ class PipCaller(object):
|
|||||||
|
|
||||||
if pip_command is not None:
|
if pip_command is not None:
|
||||||
self._logger.debug("Found pip at {}, going to figure out its version".format(pip_command))
|
self._logger.debug("Found pip at {}, going to figure out its version".format(pip_command))
|
||||||
p = sarge.run([pip_command, "--version"], stdout=sarge.Capture(), stderr=sarge.Capture())
|
|
||||||
|
sarge_command = [pip_command, "--version"]
|
||||||
|
if pip_sudo:
|
||||||
|
sarge_command = ["sudo"] + sarge_command
|
||||||
|
p = sarge.run(sarge_command, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||||
|
|
||||||
if p.returncode != 0:
|
if p.returncode != 0:
|
||||||
self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
|
self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
|
||||||
@@ -174,7 +206,7 @@ class PipCaller(object):
|
|||||||
else:
|
else:
|
||||||
self._logger.info("Found pip at {}, version is {}".format(pip_command, version_segment))
|
self._logger.info("Found pip at {}, version is {}".format(pip_command, version_segment))
|
||||||
|
|
||||||
return pip_command, pip_version
|
return pip_command, pip_version, version_segment, pip_sudo
|
||||||
|
|
||||||
def _log_stdout(self, *lines):
|
def _log_stdout(self, *lines):
|
||||||
self.on_log_stdout(*lines)
|
self.on_log_stdout(*lines)
|
||||||
|
|||||||
@@ -8,4 +8,3 @@ from __future__ import absolute_import
|
|||||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||||
|
|
||||||
@@ -13,6 +13,98 @@ import mock
|
|||||||
import octoprint.filemanager
|
import octoprint.filemanager
|
||||||
import octoprint.filemanager.util
|
import octoprint.filemanager.util
|
||||||
|
|
||||||
|
class FilemanagerMethodTest(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
# mock plugin manager
|
||||||
|
self.plugin_manager_patcher = mock.patch("octoprint.plugin.plugin_manager")
|
||||||
|
self.plugin_manager_getter = self.plugin_manager_patcher.start()
|
||||||
|
|
||||||
|
self.plugin_manager = mock.MagicMock()
|
||||||
|
|
||||||
|
hook_extensions = dict(
|
||||||
|
some_plugin=lambda: dict(dict(machinecode=dict(foo=["foo", "f"]))),
|
||||||
|
other_plugin=lambda: dict(dict(model=dict(amf=["amf"]))),
|
||||||
|
mime_map=lambda: dict(
|
||||||
|
mime_map=dict(
|
||||||
|
mime_map_yes=octoprint.filemanager.ContentTypeMapping(["mime_map_yes"], "application/mime_map_yes")
|
||||||
|
)
|
||||||
|
),
|
||||||
|
mime_detect=lambda: dict(
|
||||||
|
dict(
|
||||||
|
machinecode=dict(
|
||||||
|
mime_detect_yes=octoprint.filemanager.ContentTypeDetector(["mime_detect_yes"], lambda x: "application/mime_detect_yes"),
|
||||||
|
mime_detect_no=octoprint.filemanager.ContentTypeDetector(["mime_detect_no"], lambda x: None)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.plugin_manager.get_hooks.return_value = hook_extensions
|
||||||
|
|
||||||
|
self.plugin_manager_getter.return_value = self.plugin_manager
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.plugin_manager_patcher.stop()
|
||||||
|
|
||||||
|
def test_full_extension_tree(self):
|
||||||
|
full = octoprint.filemanager.full_extension_tree()
|
||||||
|
self.assertTrue("machinecode" in full)
|
||||||
|
self.assertTrue("gcode" in full["machinecode"])
|
||||||
|
self.assertTrue(isinstance(full["machinecode"]["gcode"], octoprint.filemanager.ContentTypeMapping))
|
||||||
|
self.assertItemsEqual(["gcode", "gco", "g"], full["machinecode"]["gcode"].extensions)
|
||||||
|
self.assertTrue("foo" in full["machinecode"])
|
||||||
|
self.assertTrue(isinstance(full["machinecode"]["foo"], list))
|
||||||
|
self.assertItemsEqual(["f", "foo"], full["machinecode"]["foo"])
|
||||||
|
|
||||||
|
self.assertTrue("model" in full)
|
||||||
|
self.assertTrue("stl" in full["model"])
|
||||||
|
self.assertTrue(isinstance(full["model"]["stl"], octoprint.filemanager.ContentTypeMapping))
|
||||||
|
self.assertItemsEqual(["stl"], full["model"]["stl"].extensions)
|
||||||
|
self.assertTrue("amf" in full["model"])
|
||||||
|
self.assertTrue(isinstance(full["model"]["amf"], list))
|
||||||
|
self.assertItemsEqual(["amf"], full["model"]["amf"])
|
||||||
|
|
||||||
|
def test_get_mimetype(self):
|
||||||
|
self.assertEquals(octoprint.filemanager.get_mime_type("foo.stl"), "application/sla")
|
||||||
|
self.assertEquals(octoprint.filemanager.get_mime_type("foo.gcode"), "text/plain")
|
||||||
|
self.assertEquals(octoprint.filemanager.get_mime_type("foo.unknown"), "application/octet-stream")
|
||||||
|
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_map_yes"), "application/mime_map_yes")
|
||||||
|
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_map_no"), "application/octet-stream")
|
||||||
|
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_detect_yes"), "application/mime_detect_yes")
|
||||||
|
self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_detect_no"), "application/octet-stream")
|
||||||
|
|
||||||
|
def test_valid_file_type(self):
|
||||||
|
self.assertTrue(octoprint.filemanager.valid_file_type("foo.stl", type="model"))
|
||||||
|
self.assertTrue(octoprint.filemanager.valid_file_type("foo.stl", type="stl"))
|
||||||
|
self.assertFalse(octoprint.filemanager.valid_file_type("foo.stl", type="machinecode"))
|
||||||
|
self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo", type="machinecode"))
|
||||||
|
self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo", type="foo"))
|
||||||
|
self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo"))
|
||||||
|
self.assertTrue(octoprint.filemanager.valid_file_type("foo.mime_map_yes"))
|
||||||
|
self.assertTrue(octoprint.filemanager.valid_file_type("foo.mime_detect_yes"))
|
||||||
|
self.assertFalse(octoprint.filemanager.valid_file_type("foo.unknown"))
|
||||||
|
|
||||||
|
def test_get_file_type(self):
|
||||||
|
self.assertEquals(["machinecode", "gcode"], octoprint.filemanager.get_file_type("foo.gcode"))
|
||||||
|
self.assertEquals(["machinecode", "gcode"], octoprint.filemanager.get_file_type("foo.gco"))
|
||||||
|
self.assertEquals(["machinecode", "foo"], octoprint.filemanager.get_file_type("foo.f"))
|
||||||
|
self.assertEquals(["model", "stl"], octoprint.filemanager.get_file_type("foo.stl"))
|
||||||
|
self.assertEquals(["model", "amf"], octoprint.filemanager.get_file_type("foo.amf"))
|
||||||
|
self.assertIsNone(octoprint.filemanager.get_file_type("foo.unknown"))
|
||||||
|
|
||||||
|
def test_hook_failure(self):
|
||||||
|
def hook():
|
||||||
|
raise RuntimeError("Boo!")
|
||||||
|
self.plugin_manager.get_hooks.return_value = dict(hook=hook)
|
||||||
|
|
||||||
|
with mock.patch("octoprint.filemanager.logging") as patched_logging:
|
||||||
|
logger = mock.MagicMock()
|
||||||
|
patched_logging.getLogger.return_value = logger
|
||||||
|
|
||||||
|
octoprint.filemanager.get_all_extensions()
|
||||||
|
|
||||||
|
self.assertEquals(1, len(logger.mock_calls))
|
||||||
|
|
||||||
class FileManagerTest(unittest.TestCase):
|
class FileManagerTest(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
@@ -109,13 +201,13 @@ class FileManagerTest(unittest.TestCase):
|
|||||||
self.assertEquals(metadata, expected)
|
self.assertEquals(metadata, expected)
|
||||||
self.local_storage.get_metadata.assert_called_once_with("test.file")
|
self.local_storage.get_metadata.assert_called_once_with("test.file")
|
||||||
|
|
||||||
@mock.patch("__builtin__.open", new_callable=mock.mock_open)
|
@mock.patch("octoprint.filemanager.util.atomic_write")
|
||||||
@mock.patch("io.FileIO")
|
@mock.patch("io.FileIO")
|
||||||
@mock.patch("shutil.copyfileobj")
|
@mock.patch("shutil.copyfileobj")
|
||||||
@mock.patch("os.remove")
|
@mock.patch("os.remove")
|
||||||
@mock.patch("tempfile.NamedTemporaryFile")
|
@mock.patch("tempfile.NamedTemporaryFile")
|
||||||
@mock.patch("time.time", side_effect=[1411979916.422, 1411979932.116])
|
@mock.patch("time.time", side_effect=[1411979916.422, 1411979932.116])
|
||||||
def test_slice(self, mocked_time, mocked_tempfile, mocked_os, mocked_shutil, mocked_fileio, mocked_open):
|
def test_slice(self, mocked_time, mocked_tempfile, mocked_os, mocked_shutil, mocked_fileio, mocked_atomic_write):
|
||||||
callback = mock.MagicMock()
|
callback = mock.MagicMock()
|
||||||
callback_args = ("one", "two", "three")
|
callback_args = ("one", "two", "three")
|
||||||
|
|
||||||
@@ -187,8 +279,8 @@ class FileManagerTest(unittest.TestCase):
|
|||||||
self.local_storage.add_file.assert_called_once_with("dest.file", mock.ANY, printer_profile=expected_printer_profile, allow_overwrite=True, links=expected_links)
|
self.local_storage.add_file.assert_called_once_with("dest.file", mock.ANY, printer_profile=expected_printer_profile, allow_overwrite=True, links=expected_links)
|
||||||
|
|
||||||
# assert that the generated gcode was manipulated as required
|
# assert that the generated gcode was manipulated as required
|
||||||
expected_open_calls = [mock.call("prefix/dest.file", "wb")]
|
expected_atomic_write_calls = [mock.call("prefix/dest.file", "wb")]
|
||||||
self.assertEquals(mocked_open.call_args_list, expected_open_calls)
|
self.assertEquals(mocked_atomic_write.call_args_list, expected_atomic_write_calls)
|
||||||
#mocked_open.return_value.write.assert_called_once_with(";Generated from source.file aabbccddeeff\r")
|
#mocked_open.return_value.write.assert_called_once_with(";Generated from source.file aabbccddeeff\r")
|
||||||
|
|
||||||
# assert that shutil was asked to copy the concatenated multistream
|
# assert that shutil was asked to copy the concatenated multistream
|
||||||
|
|||||||
@@ -156,3 +156,76 @@ class TestCommHelpers(unittest.TestCase):
|
|||||||
self.assertEquals(x_template, x["templates"][x_template_key])
|
self.assertEquals(x_template, x["templates"][x_template_key])
|
||||||
|
|
||||||
self.assertEquals("(?P<group{temp_key}>{temp_regex})|(?P<group{x_key}>{x_regex})".format(**locals()), matcher.pattern)
|
self.assertEquals("(?P<group{temp_key}>{temp_regex})|(?P<group{x_key}>{x_regex})".format(**locals()), matcher.pattern)
|
||||||
|
|
||||||
|
@data(
|
||||||
|
("G4 P2.0", "floatP", True, "2.0"),
|
||||||
|
("M109 S220.0", "floatS", True, "220.0"),
|
||||||
|
("G1 X10.0 Y10.0 Z0.2", "floatZ", True, "0.2"),
|
||||||
|
("G1X10.0Y10.0Z0.2", "floatZ", True, "0.2"),
|
||||||
|
("g1x10.0y10.0z0.2", "floatZ", True, "0.2"),
|
||||||
|
("M110 N0", "intN", True, "0"),
|
||||||
|
("M104 S220.0 T1", "intT", True, "1"),
|
||||||
|
("M104 T1 S220.0", "intT", True, "1"),
|
||||||
|
("N100 M110", "intN", True, "100"),
|
||||||
|
("NP100", "floatP", False, None),
|
||||||
|
)
|
||||||
|
@unpack
|
||||||
|
def test_parameter_regexes(self, line, parameter, should_match, expected_value):
|
||||||
|
from octoprint.util.comm import regexes_parameters
|
||||||
|
|
||||||
|
regex = regexes_parameters[parameter]
|
||||||
|
match = regex.search(line)
|
||||||
|
|
||||||
|
if should_match:
|
||||||
|
self.assertIsNotNone(match)
|
||||||
|
self.assertEquals(expected_value, match.group("value"))
|
||||||
|
else:
|
||||||
|
self.assertIsNone(match)
|
||||||
|
|
||||||
|
@data(
|
||||||
|
("G0 X0", "G0"),
|
||||||
|
("G28 X0 Y0", "G28"),
|
||||||
|
("M109 S220.0 T1", "M109"),
|
||||||
|
("M117 Hello World", "M117"),
|
||||||
|
("T0", "T"),
|
||||||
|
("T3", "T"),
|
||||||
|
(None, None),
|
||||||
|
("No match", None)
|
||||||
|
)
|
||||||
|
@unpack
|
||||||
|
def test_gcode_command_for_cmd(self, cmd, expected):
|
||||||
|
from octoprint.util.comm import gcode_command_for_cmd
|
||||||
|
result = gcode_command_for_cmd(cmd)
|
||||||
|
self.assertEquals(expected, result)
|
||||||
|
|
||||||
|
@data(
|
||||||
|
("T:23.0 B:60.0", 0, dict(T0=(23.0, None), B=(60.0, None)), 0),
|
||||||
|
("T:23.0 B:60.0", 1, dict(T1=(23.0, None), B=(60.0, None)), 1),
|
||||||
|
("T:23.0/220.0 B:60.0/70.0", 0, dict(T0=(23.0, 220.0), B=(60.0, 70.0)), 0),
|
||||||
|
("ok T:23.0/220.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 0, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2),
|
||||||
|
("ok T:50.2/210.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 1, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2)
|
||||||
|
)
|
||||||
|
@unpack
|
||||||
|
def test_process_temperature_line(self, line, current, expected_result, expected_max):
|
||||||
|
from octoprint.util.comm import parse_temperature_line
|
||||||
|
maxtool, result = parse_temperature_line(line, current)
|
||||||
|
self.assertDictEqual(expected_result, result)
|
||||||
|
self.assertEquals(expected_max, maxtool)
|
||||||
|
|
||||||
|
@data(
|
||||||
|
(dict(T=(23.0,None)), 0, dict(T0=(23.0, None))),
|
||||||
|
(dict(T=(23.0,None)), 1, dict(T1=(23.0, None))),
|
||||||
|
(dict(T=(23.0, None), T0=(23.0, None), T1=(42.0, None)), 0, dict(T0=(23.0, None), T1=(42.0, None))),
|
||||||
|
(dict(T=(42.0, None), T0=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(42.0, None))),
|
||||||
|
(dict(T=(21.0, None), T0=(23.0, None), T1=(42.0, None)), 0, dict(T0=(21.0, None), T1=(42.0, None))),
|
||||||
|
(dict(T=(41.0, None), T0=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(41.0, None))),
|
||||||
|
(dict(T=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(42.0, None))),
|
||||||
|
(dict(T0=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(42.0, None)))
|
||||||
|
|
||||||
|
)
|
||||||
|
@unpack
|
||||||
|
def test_canonicalize_temperatures(self, parsed, current, expected):
|
||||||
|
from octoprint.util.comm import canonicalize_temperatures
|
||||||
|
result = canonicalize_temperatures(parsed, current)
|
||||||
|
self.assertDictEqual(expected, result)
|
||||||
|
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
from __future__ import absolute_import
|
||||||
|
|
||||||
|
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||||
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||||
|
|
||||||
|
import unittest
|
||||||
|
import mock
|
||||||
|
import time
|
||||||
|
|
||||||
|
from octoprint.util import RepeatedTimer
|
||||||
|
|
||||||
|
|
||||||
|
class Countdown(object):
|
||||||
|
def __init__(self, start):
|
||||||
|
self._counter = start
|
||||||
|
|
||||||
|
def step(self):
|
||||||
|
self._counter -= 1
|
||||||
|
|
||||||
|
@property
|
||||||
|
def counter(self):
|
||||||
|
return self._counter
|
||||||
|
|
||||||
|
|
||||||
|
class IncreasingInterval(Countdown):
|
||||||
|
def __init__(self, start, factor):
|
||||||
|
Countdown.__init__(self, start)
|
||||||
|
self._start = start
|
||||||
|
self._factor = factor
|
||||||
|
|
||||||
|
def interval(self):
|
||||||
|
result = (self._start - self._counter + 1) * self._factor
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
class RepeatedTimerTest(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_condition(self):
|
||||||
|
countdown = Countdown(5)
|
||||||
|
timer_task = mock.MagicMock()
|
||||||
|
timer_task.side_effect = countdown.step
|
||||||
|
|
||||||
|
timer = RepeatedTimer(0.1, timer_task, condition=lambda: countdown.counter > 0)
|
||||||
|
timer.start()
|
||||||
|
|
||||||
|
# wait for it
|
||||||
|
timer.join()
|
||||||
|
|
||||||
|
self.assertEquals(5, timer_task.call_count)
|
||||||
|
|
||||||
|
def test_finished_callback(self):
|
||||||
|
countdown = Countdown(5)
|
||||||
|
timer_task = mock.MagicMock()
|
||||||
|
timer_task.side_effect = countdown.step
|
||||||
|
|
||||||
|
on_finished = mock.MagicMock()
|
||||||
|
|
||||||
|
timer = RepeatedTimer(0.1, timer_task, condition=lambda: countdown.counter > 0, on_finish=on_finished)
|
||||||
|
timer.start()
|
||||||
|
|
||||||
|
# wait for it
|
||||||
|
timer.join()
|
||||||
|
|
||||||
|
self.assertEquals(1, on_finished.call_count)
|
||||||
|
|
||||||
|
def test_condition_callback(self):
|
||||||
|
countdown = Countdown(5)
|
||||||
|
timer_task = mock.MagicMock()
|
||||||
|
timer_task.side_effect = countdown.step
|
||||||
|
|
||||||
|
on_cancelled = mock.MagicMock()
|
||||||
|
on_condition_false = mock.MagicMock()
|
||||||
|
|
||||||
|
timer = RepeatedTimer(0.1, timer_task,
|
||||||
|
condition=lambda: countdown.counter > 0,
|
||||||
|
on_condition_false=on_condition_false,
|
||||||
|
on_cancelled=on_cancelled)
|
||||||
|
timer.start()
|
||||||
|
|
||||||
|
# wait for it
|
||||||
|
timer.join()
|
||||||
|
|
||||||
|
self.assertEquals(1, on_condition_false.call_count)
|
||||||
|
self.assertEquals(0, on_cancelled.call_count)
|
||||||
|
|
||||||
|
def test_cancelled_callback(self):
|
||||||
|
countdown = Countdown(5)
|
||||||
|
timer_task = mock.MagicMock()
|
||||||
|
timer_task.side_effect = countdown.step
|
||||||
|
|
||||||
|
on_cancelled = mock.MagicMock()
|
||||||
|
on_condition_false = mock.MagicMock()
|
||||||
|
|
||||||
|
timer = RepeatedTimer(10, timer_task,
|
||||||
|
condition=lambda: countdown.counter > 0,
|
||||||
|
on_condition_false=on_condition_false,
|
||||||
|
on_cancelled=on_cancelled)
|
||||||
|
timer.start()
|
||||||
|
|
||||||
|
# give it some time to run
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
# then cancel it and wait for the thread to really finish
|
||||||
|
timer.cancel()
|
||||||
|
timer.join()
|
||||||
|
|
||||||
|
self.assertEquals(0, on_condition_false.call_count)
|
||||||
|
self.assertEquals(1, on_cancelled.call_count)
|
||||||
|
|
||||||
|
def test_run_first(self):
|
||||||
|
timer_task = mock.MagicMock()
|
||||||
|
|
||||||
|
timer = RepeatedTimer(60, timer_task, run_first=True)
|
||||||
|
timer.start()
|
||||||
|
|
||||||
|
# give it some time to run
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
# then cancel it and wait for the thread to really finish
|
||||||
|
timer.cancel()
|
||||||
|
timer.join()
|
||||||
|
|
||||||
|
# should have run once
|
||||||
|
self.assertEquals(1, timer_task.call_count)
|
||||||
|
|
||||||
|
def test_not_run_first(self):
|
||||||
|
timer_task = mock.MagicMock()
|
||||||
|
|
||||||
|
timer = RepeatedTimer(60, timer_task)
|
||||||
|
timer.start()
|
||||||
|
|
||||||
|
# give it some time to run - should hang in the sleep phase though
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
# then cancel it and wait for the thread to really finish
|
||||||
|
timer.cancel()
|
||||||
|
timer.join()
|
||||||
|
|
||||||
|
self.assertEquals(0, timer_task.call_count)
|
||||||
|
|
||||||
|
def test_adjusted_interval(self):
|
||||||
|
increasing_interval = IncreasingInterval(3, 1)
|
||||||
|
|
||||||
|
timer_task = mock.MagicMock()
|
||||||
|
timer_task.side_effect = increasing_interval.step
|
||||||
|
|
||||||
|
timer = RepeatedTimer(increasing_interval.interval,
|
||||||
|
timer_task,
|
||||||
|
condition=lambda: increasing_interval.counter > 0)
|
||||||
|
|
||||||
|
# this should take 1 + 2 + 3 = 6s
|
||||||
|
start_time = time.time()
|
||||||
|
timer.start()
|
||||||
|
timer.join()
|
||||||
|
duration = time.time() - start_time
|
||||||
|
|
||||||
|
self.assertEquals(3, timer_task.call_count)
|
||||||
|
self.assertGreaterEqual(duration, 6)
|
||||||
|
self.assertLess(duration, 7)
|
||||||
|
|
||||||
|
def test_condition_change_during_task(self):
|
||||||
|
def sleep():
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
timer_task = mock.MagicMock()
|
||||||
|
timer_task.side_effect = sleep
|
||||||
|
|
||||||
|
timer = RepeatedTimer(0.1, timer_task, run_first=True)
|
||||||
|
timer.start()
|
||||||
|
|
||||||
|
time.sleep(1)
|
||||||
|
timer.condition = lambda: False
|
||||||
|
timer.join()
|
||||||
|
|
||||||
|
self.assertEquals(1, timer_task.call_count)
|
||||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
+364
-232
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user