Compare commits

..
Author SHA1 Message Date
Gina Häußge f656a7b0cb First attempt at getting unit tests for the comm layer
Or maybe it would be more fitting to call these integration tests... hard to say.
2016-03-15 17:10:04 +01:00
102 changed files with 2727 additions and 6167 deletions

No files matched your search

-7
View File
@@ -1,10 +1,3 @@
src/octoprint/templates/_data/AUTHORS.md
src/octoprint/templates/_data/CHANGELOG.md
src/octoprint/templates/_data/SUPPORTERS.md
src/octoprint/templates/_data/THIRDPARTYLICENSES.md
devtools
*.tar.bz2
*.tar.gz
*.7z
+5 -7
View File
@@ -7,20 +7,18 @@
# The file is processed from top to bottom, the first matching line wins. If <tag> or <reference commit> are left out,
# the lookup table does not apply to the matched branches
# master, prerelease and rc shall not use the lookup table, only tags
# master shall not use the lookup table, only tags
master
prerelease
rc
# neither should disconnected checkouts, e.g. 'git checkout <tag>'
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.2.14
# maintenance is currently the branch for preparation of maintenance release 1.2.10
# so are any fix/... and improve/... branches
maintenance 1.2.14 cb2e0d449f607bbc89c7ad13c983a0cf11bbfdee pep440-dev
fix/.* 1.2.14 cb2e0d449f607bbc89c7ad13c983a0cf11bbfdee pep440-dev
improve/.* 1.2.14 cb2e0d449f607bbc89c7ad13c983a0cf11bbfdee pep440-dev
maintenance 1.2.10 abe68adac8f465a31bf4f3f3933190c1fc242cda pep440-dev
fix/.* 1.2.10 abe68adac8f465a31bf4f3f3933190c1fc242cda pep440-dev
improve/.* 1.2.10 abe68adac8f465a31bf4f3f3933190c1fc242cda pep440-dev
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
.* 1.3.0 198d3450d94be1a2 pep440-dev
-2
View File
@@ -60,8 +60,6 @@ date of first contribution):
* [Siim Raud](https://github.com/2ndalpha)
* ["geoporalis"](https://github.com/geoporalis)
* [Andrew Malota](https://github.com/2bitoperations)
* [Kyle Evans](https://github.com/kevans91)
* [Ovidiu Hossu](https://github.com/MoonshineSG)
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
-125
View File
@@ -1,130 +1,5 @@
# OctoPrint Changelog
## 1.2.14 (2016-07-28)
### Improvements
* [#935](https://github.com/foosel/OctoPrint/issues/935) - Support alternative source file types and target extensions in [SlicerPlugins](http://docs.octoprint.org/en/master/plugins/mixins.html#slicerplugin).
* [#1393](https://github.com/foosel/OctoPrint/issues/1393) - Added dedicated sub commands on the job API to pause and resume a print job (instead of only offering a toggle option).
* Better "upload error" message with a list of supported extensions (instead of hardcoded ones)
* Use fuzzy times for print time estimation from GCODE analysis
* Allow M23 "File opened" response with no filename (RepRapPro)
* Allow intermediary startup page to forward query parameters and fragments from initial call to actual web frontend
* More error resilience when rendering templates (e.g. from plugins)
* Make sure that all bytes of a line to send to the printer have actually been sent
* "Tickle" printer when encountering a communication timeout while idle
* Report `CLOSED`/`CLOSED_WITH_ERROR` states as "Offline" in frontend for more consistency with startup `NONE` state which already was reported as "Offline"
* Another attempt at a saner print time estimation: Force linear (way less accurate) estimate if calculation of more accurate version takes too long, sanity check calculated estimate and use linear estimate if it looks wrong, improved threshold values for calculation. Read [the second half of this post on the mailing list](https://groups.google.com/forum/#!msg/octoprint/WWpm1FCUkAs/X3HomTM5DgAJ) on why accurate print time estimation is so difficult to achieve.
* Display print job progress percentage on progress bar.
* Added an indicator for print time left prediction accuracy and explanation of its origin as tooltip.
* Improved visual distinction of "State" sidebar panel info clusters.
### Bug Fixes
* [#1385](https://github.com/foosel/OctoPrint/issues/1385) - Send all non-protocol messages from printer to clients.
* [#1388](https://github.com/foosel/OctoPrint/issues/1388) - Track consecutive timeouts even when idle and disconnect from printer when it's not responding any longer.
* [#1391](https://github.com/foosel/OctoPrint/issues/1391) - Only use the first value from the X-Scheme header for the reverse proxy setup. Otherwise there could be problems when multiple reverse proxies were configured chained together, each adding their own header to the mix.
* [#1407](https://github.com/foosel/OctoPrint/issues/1407) - If a file is uploaded with the "print" flag set to true, make sure to clear that flag after the print job has been triggered so that now all following uploaded or selected files will start printing on their own.
* [#1409](https://github.com/foosel/OctoPrint/issues/1409) - Don't report a communication timeout after a heatup triggered by a print from SD.
* Fixed scrolling to freshly uploaded files, also now highlighting the file entry for better visibility.
* Fixed overeager preemptive caching of invalid protocols.
* Fix modal background of update confirmation not vanishing
* Ensure log entries and messages from printer are sent to frontend already converted to utf-8. Otherwise even one line in the log that can't be converted automatically without error can cause updates from the backend to not arrive.
* Report correct printer state including error strings even after disconnecting
* While printing, be sure to read the next line from file and send that if the current line was filtered
* Small fixes in the GCODE analysis
* Small fixes in the documentation
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.13...1.2.14))
## 1.2.13 (2016-06-16)
### Bug Fixes
* [#1373](https://github.com/foosel/OctoPrint/issues/1373): Don't parse `B:` as bed temperature when it shows up as part of a position report from `M114`.
* [#1374](https://github.com/foosel/OctoPrint/issues/1374): Don't try to perform a passive login when the components we'd need to inform about a change in login state aren't yet available. Solves a bug that lead - among other things - to the Plugin Manager and the Software Update Plugin not showing anything but misleading errors until the user logged out and back in.
* Fixed the temperature graph staying uninitialized until a connection to a printer was established.
* Fixed an error causing issues during frontend startup if the browser doesn't support tracking browser visibility.
* Fixed an error causing issues during frontend startup if the browser doesn't support the capabilities needed for the GCODE viewer.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.12...1.2.13))
## 1.2.12 (2016-06-09)
### Improvements
* [#1338](https://github.com/foosel/OctoPrint/issues/1338): Threshold configuration fields now include information about how to specify the thresholds.
* Mark unrendered timelapses currently being processed (recording or rendering) in the list and remove action buttons so no accidental double-processing can take place.
* Removed file extension from "rendering" and "rendered" notifications, was misleading when using the [mp4 wrapper script](https://github.com/guysoft/OctoPi/issues/184).
* Added some new events for manipulation of slicing profiles.
* Small fix of the german translation.
### Bug Fixes
* [#1314](https://github.com/foosel/OctoPrint/issues/1314): Do not change the extension of `.g` files being uploaded to SD (e.g. `auto0.g`)
* [#1320](https://github.com/foosel/OctoPrint/issues/1320): Allow deletion of *.mp4 timelapse files (see [this wrapper script](https://github.com/guysoft/OctoPi/issues/184)).
* [#1324](https://github.com/foosel/OctoPrint/issues/1324): Make daemonized OctoPrint properly clean up its pid file again (see also [#1330](https://github.com/foosel/OctoPrint/pull/1330)).
* [#1326](https://github.com/foosel/OctoPrint/issues/1326): Do not try to clean up an unrendered timelapse while it is already being deleted (and produce way too much logging output in the process).
* [#1343](https://github.com/foosel/OctoPrint/issues/1343): Events are now processed in the order they are fired in, making e.g. the "timelapse rendering" message always appear before "timelapse failed" and hence not stay on forever in case of a failed timelapse.
* [#1344](https://github.com/foosel/OctoPrint/issues/1344): `ProgressPlugin`s now get also notified about a progress of 0%.
* [#1357](https://github.com/foosel/OctoPrint/issues/1357): Fixed wrongly named method call on editing access control options for a user, causing that to not work properly.
* [#1361](https://github.com/foosel/OctoPrint/issues/1361): Properly reload profile list for currently selected slicer in the slicing dialog on change of profiles.
* [#1364](https://github.com/foosel/OctoPrint/issues/1364): Fixed a race condition that could cause the UI to not initialize correctly due to 401 errors, leaving it in an unusable state until a reload.
* Fixed concurrent message pushing to the frontend being able to break push messages for the session by forcing synchronization of SockJS message sending.
* Do not require admin rights for connecting/disconnecting, like it was in 1.1.x (note that this is supposed to become configurable behaviour once [#1110](https://github.com/foosel/OctoPrint/issues/1110) gets implemented)
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.11...1.2.12))
## 1.2.11 (2016-05-04)
### Important Announcement
Due to a recent change in the financial situation of the project, the funding of OctoPrint is at stake. If you love OctoPrint and want to see its development continue at the pace of the past two years, please read on about its current funding situation and how you can help: ["I need your support"](http://octoprint.org/blog/2016/04/13/i-need-your-support/).
### Improvements
* Added option to treat resend requests as `ok` for such firmwares that do not send an `ok` after requesting a resend. If you printer communication gets stalled after a resend request from the firmware, try checking this option.
* Added an "About" dialog to properly inform about OctoPrint's license, contributors and supporters.
* Added a announcement plugin that utilizes the RSS feeds of the [OctoPrint Blog](http://octoprint.org/blog/) and the [plugin repository](http://plugins.octoprint.org) to display news to the user. By default only the "important announcement" category is enabled. This category will only be used for very rare situations such as making you aware of critical updates or important news. You can enable further categories (with more announcements to be expected) in the plugin's settings dialog.
### Bug Fixes
* [#1300](https://github.com/foosel/OctoPrint/issues/1300) - Removed possibility to accidentally disabling local file list by first limiting view to files from SD and then disabling SD support.
* [#1315](https://github.com/foosel/OctoPrint/issues/1315) - Fixed broken post roll on z-based timelapses.
* Fixed CSS data binding syntax on the download link in the files list
* Changed control distance from jQuery data into a knockout observerable and observerableArray
* Allow an unauthorized user to logout from a logedin interface state
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.10...1.2.11))
## 1.2.10 (2016-03-16)
### Improvements
* Improved performance of console output during plugin installation/deinstallation
* Slight performance improvements in the communication layer
* Log small log excerpt to `octoprint.log` upon encountering a communication error.
* Changed wording in "firmware error" notifications to better reflect that there was an error while communicating with the printer, since the error condition can also be triggered by serial errors while trying to establish a connection to the printer or when already connected.
* Support downloading ".mp4" timelapse files. You'll need a [custom wrapper script for timelapse rendering](https://github.com/guysoft/OctoPi/issues/184) for this to be relevant to you. See also [#1255](https://github.com/foosel/OctoPrint/pull/1255)
* The communication layer will now wait up to 10s after clicking disconnect in order to send any left-over lines from its buffers.
* Moved less commonly used configuration options in Serial settings into "Advanced options" roll-out.
### Bug Fixes
* [#1224](https://github.com/foosel/OctoPrint/issues/1224) - Fixed an issue introduced by the fix for [#1196](https://github.com/foosel/OctoPrint/issues/1196) that had the "Upload to SD" button stop working correctly.
* [#1226](https://github.com/foosel/OctoPrint/issues/1226) - Fixed an issue causing an error on disconnect after or cancelling of an SD print, caused by the unsuccessful attempt to record print recovery data for the file on the printer's SD card.
* [#1268](https://github.com/foosel/OctoPrint/issues/1268) - Only add bed temperature line to temperature management specific start gcode in CuraEngine invocation if a bed temperature is actually set in the slicing profile.
* [#1271](https://github.com/foosel/OctoPrint/issues/1271) - If a communication timeout occurs during an active resend request, OctoPrint will now not send an `M105` with an increased line number anymore but repeat the last resent command instead.
* [#1272](https://github.com/foosel/OctoPrint/issues/1272) - Don't add an extra `ok` for `M28` response.
* [#1273](https://github.com/foosel/OctoPrint/issues/1273) - Add an extra `ok` for `M29` response, but only if configured such in "Settings" > "Serial" > "Advanced options" > "Generate additional ok for M29"
* [#1274](https://github.com/foosel/OctoPrint/issues/1274) - Trigger `M20` only once after finishing uploading to SD
* [#1275](https://github.com/foosel/OctoPrint/issues/1275) - Prevent `M105` "cascade" due to communication timeouts
* Fixed wrong tracking of extruder heating up for `M109 Tn` commands in multi-extruder setups.
* Fixed start of SD file uploads not sending an `M110`.
* Fixed job data not being reset when disconnecting while printing.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.9...1.2.10))
## 1.2.9 (2016-02-10)
### Improvements
-9
View File
@@ -302,11 +302,6 @@ There are three main branches in OctoPrint:
the scheme `x.y.z` (e.g. `1.2.9`) or - if it's absolutely necessary to
add a commit after release to this branch - `x.y.z.post<commits since x.y.z>`
(e.g. `1.2.9.post1`).
* `prerelease`: This branch is only used during the short period where a
future release has "graduated" from the `maintenance` branch and is already
tagged, but still marked on Github as a pre-release. This is mostly used for
update testing just before new releases. Version number follows the scheme
`x.y.z` (e.g. `1.2.9`), just like the `master` branch.
* `maintenance`: Improvements and fixes of the current release that make up
the next release go here. More or less continously updated. You can consider
this a preview of the next release version. It should be very stable at all
@@ -334,9 +329,6 @@ Those usually have one of the following prefixes:
`maintenance` and `devel` branches.
* `dev/...` or `feature/...`: New functionality under development that is to be merged
into the `devel` branch.
* `rc`: A branch similar in nature to the `prerelease` branch, only that it will be
used to provide current release candidates of the next stable version to be derived
from the `devel` branch.
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a couple of
older development branches that are slowly being migrated or deleted.
@@ -375,7 +367,6 @@ the local version identifier to allow for an exact determination of the active c
* 2016-02-16: Added requirement to add information from template to existing
tickets as well, explained issue with "me too" red herrings.
* 2016-03-14: Some more requirements for PRs, and a PR template.
* 2016-06-08: New `prerelease` and `rc` branches explained.
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
+1 -2
View File
@@ -4,6 +4,5 @@ recursive-include src/octoprint/plugins *
recursive-include src/octoprint/translations *
include versioneer.py
include src/octoprint/_version.py
include README.md
include requirements.txt
include *.md
exclude CONTRIBUTING.md
+1 -4
View File
@@ -10,9 +10,6 @@ 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).
OctoPrint's development wouldn't be possible without the [financial support by its community](http://octoprint.org/support-octoprint/).
If you enjoy OctoPrint, please consider becoming a regular supporter!
![Screenshot](http://i.imgur.com/dF3noFp.png)
You are currently looking at the source code repository of OctoPrint. If you already installed it
@@ -29,7 +26,7 @@ Contributions of all kinds are welcome, not only in the form of code but also wi
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), support
of other users in the [bug tracker](https://github.com/foosel/OctoPrint/issues),
[the Mailinglist](https://groups.google.com/group/octoprint) or
[the G+ Community](https://plus.google.com/communities/102771308349328485741) and also [financially](http://octoprint.org/support-octoprint/).
[the G+ Community](https://plus.google.com/communities/102771308349328485741).
If you think something is bad as it is about OctoPrint or its documentation the way it is, please help
in any way to make it better instead of just complaining about it -- this is an Open Source Project
-71
View File
@@ -1,71 +0,0 @@
# Supporters
Development of this version of OctoPrint wouldn't have been possible without
[financial support by the community](http://octoprint.org/support-octoprint/) -
thanks to everyone who contributed!
## Patreon Patrons
* 3D Moniak
* alephobjects
* Andrew Moorby
* Arnljot Arntsen
* Aurelio Bernal Ramírez
* Bart Zudell
* Brad Jackson
* Brad Mooneyham
* Brent Fiegle
* Brian E. Tyler
* Charles Mitchell
* Christian Petropolis
* COLLE+McVOY
* CreativeTools
* D Brian Kimmel
* DeltaMaker 3D Printers
* Doug Johnson
* E3D BigBox
* Erik de Bruijn
* Ernesto Martinez
* Exovite
* Frank Sander
* georgeroblesjr
* Gregor Luetolf
* J. Eckert
* Jason Galarneau
* Joe Korzeniewski
* Joshua Gregory
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Korneel Bullens
* Kyle Gress
* Makespace Madrid
* Mark Lane
* Mark Qvist
* Mark Walker
* Masayoshi Mitsui
* Michael McDargh
* Miguel Angel Salmeron
* Mikey
* Miles Flavel
* Mohammed Khorakiwala
* Noe Ruiz
* Paul Generes
* Peter Grace
* Peter Schmehl
* PRINT3Dforum.com
* Roger Strolz
* Roy Cortes
* Samer Najia
* SD3D
* Shane Ekerbicer
* Simon Hallam
* Stefan Krister
* stefi davis
* Steven Pearson
* Sven Mueller
* Thomas Hatley
* Thomas Sanladerer
* Trent Shumay
and 844 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
-55
View File
@@ -1,55 +0,0 @@
# Third Party Licenses
## Web Interface
* [AVLTree](https://gist.github.com/viking/2424106) (modified): GPL, LGPL (dual licensed)
* [Babel JavaScript Support](https://github.com/mitsuhiko/babel/blob/master/contrib/babel.js): BSD
* [Bootstrap](http://getbootstrap.com/): Apache License 2.0
* [Bootstrap Modal](http://jschr.github.io/bootstrap-modal/): Apache License 2.0
* [Bootstrap Slider Knockout Bindings](https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding): MIT
* [Bootstrap Slider](http://seiyria.com/bootstrap-slider/): Apache License 2.0
* [Bootstrap Tabdrop](http://www.eyecon.ro/bootstrap-tabdrop): Apache License 2.0
* [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
* [Flot](http://www.flotcharts.org/): MIT
* [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT
* [JQuery](http://jquery.com/): MIT
* [JQuery Bootstrap Wizard](http://github.com/VinceG/twitter-bootstrap-wizard): MIT, GPL (dual licensed)
* [JQuery File Upload](https://github.com/blueimp/jQuery-File-Upload): MIT
* [JQuery iframe transport](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.iframe-transport.js): MIT
* [JQuery QRCode](http://larsjung.de/jquery-qrcode/): MIT
* [JQuery Slimscroll](http://rocha.la/jQuery-slimScroll): MIT, GPL (dual licensed)
* [JQuery UI Core, Mouse, Slider and Widget](http://jqueryui.com): MIT
* [Knockout](http://knockoutjs.com/): MIT
* [LESS](http://lesscss.org): Apache License 2.0
* [lodash](https://lodash.com): MIT
* [Loglevel](https://github.com/pimterry/loglevel): MIT
* [Modernizr](http://modernizr.com): MIT
* [Moment.js](http://momentjs.com/): MIT
* [PNotify](http://sciactive.com/pnotify/): GPL, LGPL, MPL (triple licensed)
* [pusher.color.js](http://cache.preserve.io/5g18q0pw/index.html) (original link dead): MIT
* [SockJS](https://github.com/sockjs/sockjs-client): MIT
* [sprintf-js](http://alexei.ro/): BSD
## Server
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
* [Flask](http://flask.pocoo.org/): BSD
* [Flask-Assets](http://github.com/miracle2k/flask-assets): BSD
* [Flask-Babel](http://github.com/mitsuhiko/flask-babel): BSD
* [Flask-Login](https://github.com/maxcountryman/flask-login): MIT
* [Flask-Markdown](http://github.com/dcolish/flask-markdown): BSD
* [Flask-Principal](http://packages.python.org/Flask-Principal/): MIT
* [netaddr](https://github.com/drkjam/netaddr/): BSD
* [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
* [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
* [psutil](https://github.com/giampaolo/psutil): BSD
* [pylru](https://github.com/jlhutch/pylru): GPLv2
* [pyserial](http://pyserial.sourceforge.net/): Python
* [PyYAML](http://pyyaml.org/wiki/PyYAML): MIT
* [requests](http://python-requests.org/): Apache License 2.0
* [rsa](http://stuvel.eu/rsa): Apache License 2.0
* [sarge](http://sarge.readthedocs.org/): BSD
* [semantic_version](https://github.com/rbarrois/python-semanticversion): BSD
* [SockJS-Tornado](http://github.com/mrjoes/sockjs-tornado/): MIT
* [Tornado](http://www.tornadoweb.org/): Apache License 2.0
* [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0
+2 -3
View File
@@ -390,9 +390,8 @@ Issue a file command
}
:param target: The target location on which the file to send the command for is located, either
``local`` (for OctoPrint's ``uploads`` folder) or ``sdcard`` for the printer's SD card
(if available)
:param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads``
folder) or ``sdcard`` for the printer's SD card (if available)
:param filename: The filename of the file for which to issue the command
:json string command: The command to issue for the file, currently only ``select`` is supported
:json boolean print: ``select`` and ``slice`` command: Optional, whether to start printing the file directly after selection
+8 -66
View File
@@ -19,38 +19,17 @@ Issue a job command
Starts the print of the currently selected file. For selecting a file, see :ref:`Issue a file command <sec-api-fileops-filecommand>`.
If a print job is already active, a :http:statuscode:`409` will be returned.
cancel
Cancels the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409`
will be returned.
restart
Restart the print of the currently selected file from the beginning. There must be an active print job for this to work
and the print job must currently be paused. If either is not the case, a :http:statuscode:`409` will be returned.
Equivalent to issuing a ``cancel`` command while paused, directly followed by a ``start`` command.
pause
Pauses/resumes/toggles the current print job. Accepts one optional additional parameter ``action``
specifying which action to take. Valid values for this parameter are:
Pauses/unpauses the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409`
will be returned.
pause
Pauses the current job if it's printing, does nothing if it's already paused.
resume
Resumes the current job if it's paused, does nothing if it's printing.
toggle
Toggles the pause state of the job, pausing it if it's printing and resuming it if it's currently paused.
In order to stay backwards compatible to earlier iterations of this API, the default
action to take if no ``action`` parameter is supplied is to toggle the print job status.
If no print job is active (either paused or printing), a :http:statuscode:`409` will be returned.
.. note::
While the approach to implement pause/resume/toggle behaviour through sub commands via the ``action``
parameter instead of having dedicated ``pause``, ``resume`` and ``toggle`` commands seems clumsy, this path
was chosen to have the API stay backwards compatible to prior versions which only offered the toggle
behaviour under the ``pause`` command.
cancel
Cancels the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409`
will be returned.
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
@@ -71,23 +50,6 @@ Issue a job command
HTTP/1.1 204 No Content
**Example Cancel Request**
.. sourcecode:: http
POST /api/job HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "cancel"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example Restart Request**
.. sourcecode:: http
@@ -115,15 +77,14 @@ Issue a job command
X-Api-Key: abcdef...
{
"command": "pause",
"action": "pause"
"command": "pause"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example Resume Request**
**Example Cancel Request**
.. sourcecode:: http
@@ -133,26 +94,7 @@ Issue a job command
X-Api-Key: abcdef...
{
"command": "pause",
"action": "resume"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example Pause Toggle Request**
.. sourcecode:: http
POST /api/job HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "pause",
"action": "toggle"
"command": "cancel"
}
.. sourcecode:: http
+1 -1
View File
@@ -32,7 +32,7 @@ List All Slicers and Slicing Profiles
.. sourcecode:: http
GET /api/slicing HTTP/1.1
GET /api/slicing/profiles HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
+3 -116
View File
@@ -244,9 +244,6 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# be fully rerendered on request to / on the server.
enabled: true
# Whether to enable the preemptive cache
preemptive: true
# Settings for stylesheet preference. OctoPrint will prefer to use the stylesheet type
# specified here. Usually (on a production install) that will be the compiled css (default).
# Developers may specify less here too.
@@ -263,9 +260,6 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# set to false, no minification will take place either.
minify: true
# Whether to delete generated web assets on server startup (forcing a regeneration)
clean_on_startup: true
# Settings for the virtual printer
virtualPrinter:
@@ -296,14 +290,6 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
includeCurrentToolInTemps: true
# Whether to include the selected filename in the M23 File opened response.
#
# True: > M23 filename.gcode
# < File opened: filename.gcode Size: 27
# False: > M23 filename.gcode
# > File opened
includeFilenameInOpened: true
# The maximum movement speeds of the simulated printer's axes, in mm/s
movementSpeed:
x: 6000
@@ -327,10 +313,6 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# < ok T0:34.3/220.0 T1:23.5/0.0 B:43.2/0.0
repetierStyleTargetTemperature: false
# If enabled, uses repetier style resends, sending multiple resends for the same line
# to make sure nothing gets lost on the line
repetierStyleResends: false
# If enabled, reports the first extruder in M105 responses as T instead of T0
#
# True: > M105
@@ -358,54 +340,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# side will block
rxBuffer: 64
# Size of simulated command buffer
# Size of
commandBuffer: 4
# Whether to support the M112 command with simulated kill
supportM112: true
# Whether to send messages received via M117 back as "echo:" lines
echoOnM117: true
# Whether to simulate broken M29 behaviour (missing ok after response)
brokenM29: true
.. _sec-configuration-config_yaml-estimation:
Estimation
----------
The following settings provide parameters for estimators within OctoPrint. Currently only
the estimation of the left print time during an active job utilizes this section.
.. code-block:: yaml
estimation:
# Parameters for the print time estmation during an ongoing print job
printTime:
# Until which percentage to do a weighted mixture of statistical duration (analysis or
# past prints) with the result from the calculated estimate if that's already available.
# Utilized to compensate for the fact that the earlier in a print job, the least accuracy
# even a stable calculated estimate provides.
statsWeighingUntil: 0.5
# Range the assumed percentage (based on current estimated statistical, calculated or mixed
# total vs elapsed print time so far) needs to be around the actual percentage for the
# result to be used
validityRange: 0.15
# If no estimate could be calculated until this percentage and no statistical data is available,
# use dumb linear estimate
forceDumbFromPercent: 0.3
# If no estimate could be calculated until this many minutes into the print and no statistical
# data is available, use dumb linear estimate
forceDumbAfterMin: 30
# Average fluctuation between individual calculated estimates to consider in stable range. Seconds
# of difference.
stableThreshold: 60
.. _sec-configuration-config_yaml-events:
Events
@@ -489,9 +426,6 @@ Use the following settings to enable or disable OctoPrint features:
# Specifies whether support for SD printing and file management should be enabled
sdSupport: true
# Specifies whether firmware expects relative paths for selecting SD files
sdRelativePath: false
# Whether to always assume that an SD card is present in the printer.
# Needed by some firmwares which don't report the SD card status properly.
sdAlwaysAvailable: false
@@ -509,16 +443,6 @@ Use the following settings to enable or disable OctoPrint features:
# Whether to enable the keyboard control feature in the control tab
keyboardControl: true
# Whether to actively poll the watched folder (true) or to rely on the OS's file system
# notifications instead (false)
pollWatched: false
# Whether to ignore identical resends from the printer (true, repetier) or not (false)
ignoreIdenticalResends: false
# If ignoredIdenticalResends is true, how many consecutive identical resends to ignore
identicalResendsCount: 7
.. _sec-configuration-config_yaml-folder:
Folder
@@ -705,24 +629,8 @@ Use the following settings to configure the serial connection to the printer:
# Command to send in order to initiate a handshake with the printer.
# Defaults to "M110 N0" which simply resets the line numbers in the firmware and which
# should be acknowledged with a simple "ok".
helloCommand: M110 N0
# Whether to disconnect on errors or not
disconnectOnErrors: true
# Whether to completely ignore errors from the firmware or not
ignoreErrorsFromFirmware: false
# Whether to log resends to octoprint.log or not. Invaluable debug tool without performance
# impact, leave on if possible please
logResends: true
# Whether to support resends without follow-up ok or not
supportResendsWithoutOk: false
# Whether to "manually" trigger an ok for M29 (a lot of versions of this command are buggy and
# the responds skips on the ok)
triggerOkForM29: true
helloCommand:
- M110 N0
.. _sec-configuration-config_yaml-server:
@@ -817,27 +725,6 @@ Use the following settings to configure the server:
# Command to shut down the system OctoPrint is running on, defaults to being unset
systemShutdownCommand: sudo shutdown -h now
# Settings of when to display what disk space warning
diskspace:
# Threshold (bytes) after which to consider disk space becoming sparse,
# defaults to 500MB
warning: 63488000
# Threshold (bytes) after which to consider disk space becoming critical,
# defaults to 200MB
critical: 209715200
# Configuration of the preemptive cache
preemptiveCache:
# which server paths to exclude from the preemptive cache
exceptions:
- /some/path
# How many days to leave unused entries in the preemptive cache config
until: 7
.. note::
-24
View File
@@ -365,30 +365,6 @@ SlicingFailed
* ``gcode``: the sliced GCODE's filename
* ``reason``: the reason for the slicing having failed
SlicingProfileAdded
A new slicing profile was added.
Payload:
* ``slicer``: the slicer for which the profile was added
* ``profile``: the profile that was added
SlicingProfileModified
A new slicing profile was modified.
Payload:
* ``slicer``: the slicer for which the profile was modified
* ``profile``: the profile that was modified
SlicingProfileDeleted
A slicing profile was deleted.
Payload:
* ``slicer``: the slicer for which the profile was deleted
* ``profile``: the profile that was deleted
Settings
--------
+25 -63
View File
@@ -2,7 +2,6 @@
# coding=utf-8
from setuptools import setup, find_packages
from distutils.command.build_py import build_py as _build_py
import os
import versioneer
@@ -15,28 +14,26 @@ import octoprint_setuptools
# Requirements for our application
INSTALL_REQUIRES = [
"flask>=0.9,<0.11",
"werkzeug>=0.8.3,<0.9",
"tornado>=4.0.1,<4.1",
"sockjs-tornado>=1.0.1,<1.1",
"PyYAML>=3.10,<3.11",
"Flask-Login>=0.2.2,<0.3",
"Flask-Principal>=0.3.5,<0.4",
"Flask-Babel>=0.9,<0.10",
"Flask-Assets>=0.10,<0.11",
"markdown>=2.6.4,<2.7",
"pyserial>=2.7,<2.8",
"netaddr>=0.7.17,<0.8",
"watchdog>=0.8.3,<0.9",
"sarge>=0.1.4,<0.2",
"netifaces>=0.10,<0.11",
"pylru>=1.0.9,<1.1",
"rsa>=3.2,<3.3",
"pkginfo>=1.2.1,<1.3",
"requests>=2.7.0,<2.8",
"semantic_version>=2.4.2,<2.5",
"psutil>=3.2.1,<3.3",
"awesome-slugify>=1.6.5,<1.7",
"feedparser>=5.2.1,<5.3"
"werkzeug==0.8.3",
"tornado==4.0.1",
"sockjs-tornado==1.0.1",
"PyYAML==3.10",
"Flask-Login==0.2.2",
"Flask-Principal==0.3.5",
"Flask-Babel==0.9",
"Flask-Assets==0.10",
"pyserial==2.7",
"netaddr==0.7.17",
"watchdog==0.8.3",
"sarge==0.1.4",
"netifaces==0.10",
"pylru==1.0.9",
"rsa==3.2",
"pkginfo==1.2.1",
"requests==2.7.0",
"semantic_version==2.4.2",
"psutil==3.2.1",
"awesome-slugify>=1.6.5,<1.7"
]
# Additional requirements for optional install options
@@ -44,12 +41,12 @@ EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
develop=[
# Testing dependencies
"mock>=1.0.1,<1.1",
"nose>=1.3.0,<1.4",
"mock>=1.0.1",
"nose>=1.3.0",
"ddt",
# Documentation dependencies
"sphinx>=1.3,<1.4",
"sphinx>=1.3",
"sphinxcontrib-httpdomain",
"sphinx_rtd_theme",
@@ -59,7 +56,7 @@ EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint plugins
plugins=[
"cookiecutter>=1.4,<1.5"
"cookiecutter"
]
)
@@ -72,32 +69,6 @@ DEPENDENCY_LINKS = []
#-----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
def data_copy_build_py_factory(files, baseclass):
class data_copy_build_py(baseclass):
files = dict()
def run(self):
import shutil
if not self.dry_run:
for directory, files in self.__class__.files.items():
target_dir = os.path.join(self.build_lib, directory)
self.mkpath(target_dir)
for entry in files:
if isinstance(entry, tuple):
if len(entry) != 2:
continue
source, dest = entry
else:
source = dest = entry
shutil.copy(source, os.path.join(target_dir, dest))
baseclass.run(self)
return type(data_copy_build_py)(data_copy_build_py.__name__,
(data_copy_build_py,),
dict(files=files))
def get_cmdclass():
cmdclass = versioneer.get_cmdclass()
@@ -110,15 +81,6 @@ def get_cmdclass():
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir))
cmdclass["build_py"] = data_copy_build_py_factory({
"octoprint/templates/_data": [
"AUTHORS.md",
"CHANGELOG.md",
"SUPPORTERS.md",
"THIRDPARTYLICENSES.md",
]
}, cmdclass["build_py"] if "build_py" in cmdclass else _build_py)
return cmdclass
@@ -169,7 +131,7 @@ def params():
packages = find_packages(where="src")
package_dir = {
"": "src",
"": "src"
}
package_data = {
"octoprint": octoprint_setuptools.package_data_dirs('src/octoprint', ['static', 'templates', 'plugins', 'translations'])
+2 -15
View File
@@ -24,14 +24,7 @@ class Main(Daemon):
self._logConf = logConf
def run(self):
octoprint = Server(configfile=self._configfile,
basedir=self._basedir,
host=self._host,
port=self._port,
debug=self._debug,
allowRoot=self._allowRoot,
logConf=self._logConf,
octoprint_daemon=self)
octoprint = Server(self._configfile, self._basedir, self._host, self._port, self._debug, self._allowRoot)
octoprint.run()
def main():
@@ -84,13 +77,7 @@ def main():
elif "restart" == args.daemon:
daemon.restart()
else:
octoprint = Server(configfile=args.config,
basedir=args.basedir,
host=args.host,
port=args.port,
debug=args.debug,
allowRoot=args.allowRoot,
logConf=args.logConf)
octoprint = Server(args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot, args.logConf)
octoprint.run()
if __name__ == "__main__":
+28 -28
View File
@@ -12,35 +12,35 @@ class Daemon:
Usage: subclass the daemon class and override the run() method."""
def __init__(self, pidfile): self.pidfile = pidfile
def daemonize(self):
"""Deamonize class. UNIX double fork mechanism."""
try:
pid = os.fork()
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #1 failed: {0}\n'.format(err))
sys.exit(1)
# decouple from parent environment
os.chdir('/')
os.setsid()
os.chdir('/')
os.setsid()
os.umask(002)
# do second fork
try:
pid = os.fork()
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #2 failed: {0}\n'.format(err))
sys.exit(1)
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
@@ -51,14 +51,18 @@ class Daemon:
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
pid = str(os.getpid())
with open(self.pidfile,'w+') as f:
f.write(pid + '\n')
def terminated(self):
self.remove_pidfile()
# register listener for SIGTERM
signal.signal(signal.SIGTERM, self.term)
def term(self, _signo, _stack_frame):
os.remove(self.pidfile)
sys.exit(0)
def start(self):
"""Start the daemon."""
@@ -70,13 +74,13 @@ class Daemon:
pid = int(pf.read().strip())
except IOError:
pid = None
if pid:
message = "pidfile {0} already exist. " + \
"Daemon already running?\n"
sys.stderr.write(message.format(self.pidfile))
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
@@ -90,14 +94,14 @@ class Daemon:
pid = int(pf.read().strip())
except IOError:
pid = None
if not pid:
message = "pidfile {0} does not exist. " + \
"Daemon not running?\n"
sys.stderr.write(message.format(self.pidfile))
return # not an error in a restart
# Try killing the daemon process
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
@@ -118,11 +122,7 @@ class Daemon:
def run(self):
"""You should override this method when you subclass Daemon.
It will be called after the process has been daemonized by
It will be called after the process has been daemonized by
start() or restart()."""
def remove_pidfile(self):
"""Removes the pidfile."""
if os.path.isfile(self.pidfile):
os.remove(self.pidfile)
+5 -12
View File
@@ -86,14 +86,6 @@ class Events(object):
SLICING_DONE = "SlicingDone"
SLICING_FAILED = "SlicingFailed"
SLICING_CANCELLED = "SlicingCancelled"
SLICING_PROFILE_ADDED = "SlicingProfileAdded"
SLICING_PROFILE_MODIFIED = "SlicingProfileModified"
SLICING_PROFILE_DELETED = "SlicingProfileDeleted"
# Printer Profiles
PRINTER_PROFILE_ADDED = "PrinterProfileAdded"
PRINTER_PROFILE_MODIFIED = "PrinterProfileModified"
PRINTER_PROFILE_DELETED = "PrinterProfileDeleted"
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
@@ -115,7 +107,7 @@ class EventManager(object):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._queue = Queue.Queue()
self._queue = Queue.PriorityQueue()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
@@ -123,7 +115,7 @@ class EventManager(object):
def _work(self):
try:
while True:
event, payload = self._queue.get(True)
(event, payload) = self._queue.get(True)
eventListeners = self._registeredListeners[event]
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
@@ -152,7 +144,7 @@ class EventManager(object):
payload being a payload object specific to the event.
"""
self._queue.put((event, payload))
self._queue.put((event, payload), 0)
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
@@ -160,7 +152,8 @@ class EventManager(object):
import copy
legacy_payload = copy.deepcopy(payload)
legacy_payload["type"] = "gcode"
self._queue.put((event, legacy_payload))
self._queue.put((event, legacy_payload), 0)
def subscribe(self, event, callback):
"""
+1 -1
View File
@@ -284,7 +284,7 @@ class FileManager(object):
import time
start_time = time.time()
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path, "progressAvailable": slicer.get_slicer_properties().get("progress_report", False) if slicer else False})
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path, "progressAvailable": slicer.get_slicer_properties()["progress_report"] if slicer else False})
import tempfile
f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False)
+2 -2
View File
@@ -398,7 +398,7 @@ class LocalFileStorage(StorageInterface):
folder_path = os.path.join(path, name)
if os.path.exists(folder_path):
if not ignore_existing:
raise RuntimeError("{name} does already exist in {path}".format(**locals()))
raise RuntimeError("{sanitized_foldername} does already exist in {virtual_path}".format(**locals()))
else:
os.mkdir(folder_path)
@@ -415,7 +415,7 @@ class LocalFileStorage(StorageInterface):
if ".metadata.yaml" in contents:
contents.remove(".metadata.yaml")
if contents and not recursive:
raise RuntimeError("{name} in {path} is not empty".format(**locals()))
raise RuntimeError("{sanitized_foldername} in {virtual_path} is not empty".format(**locals()))
import shutil
shutil.rmtree(folder_path)
+1 -10
View File
@@ -1067,13 +1067,6 @@ class SlicerPlugin(OctoPrintPlugin):
against slicers running on the same device will result in an error.
progress_report
``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise.
source_file_types
A list of file types this slicer supports as valid origin file types. These are file types as found in the
paths within the extension tree. Plugins may add additional file types through the :ref:`sec-plugins-hook-filemanager-extensiontree` hook.
The system will test source files contains in incoming slicing requests via :meth:`octoprint.filemanager.valid_file_type` against the
targeted slicer's ``source_file_types``.
destination_extension
The possible extensions of slicing result files.
Returns:
dict: A dict describing the slicer as outlined above.
@@ -1082,9 +1075,7 @@ class SlicerPlugin(OctoPrintPlugin):
type=None,
name=None,
same_device=True,
progress_report=False,
source_file_types=["model"],
destination_extensions=["gco", "gcode", "g"]
progress_report=False
)
def get_slicer_default_profile(self):
@@ -1,356 +0,0 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
import calendar
import codecs
import os
import re
import time
import threading
import feedparser
import flask
from octoprint.server import admin_permission
from octoprint.server.util.flask import restricted_access
from flask.ext.babel import gettext
class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin):
def __init__(self):
self._cached_channel_configs = None
self._cached_channel_configs_mutex = threading.RLock()
from slugify import Slugify
self._slugify = Slugify()
self._slugify.safe_chars = "-_."
# StartupPlugin
def on_after_startup(self):
self._fetch_all_channels()
# SettingsPlugin
def get_settings_defaults(self):
return dict(channels=dict(_important=dict(name="Important OctoPrint Announcements",
priority=1,
type="rss",
url="http://octoprint.org/feeds/important.xml",
read_until=1449446400),
_news=dict(name="OctoPrint News",
priority=2,
type="rss",
url="http://octoprint.org/feeds/news.xml"),
_releases=dict(name="OctoPrint Release Announcements",
priority=2,
type="rss",
url="http://octoprint.org/feeds/releases.xml"),
_spotlight=dict(name="OctoPrint Community Spotlights",
priority=2,
type="rss",
url="http://octoprint.org/feeds/spotlight.xml"),
_octopi=dict(name="OctoPi Announcements",
priority=2,
type="rss",
url="http://octoprint.org/feeds/octopi.xml"),
_plugins=dict(name="New Plugins in the Repository",
priority=2,
type="rss",
url="http://plugins.octoprint.org/feed.xml")),
enabled_channels=[],
forced_channels=["_important"],
ttl=6*60,
display_limit=3,
summary_limit=300)
# AssetPlugin
def get_assets(self):
return dict(js=["js/announcements.js"],
less=["less/announcements.less"],
css=["css/announcements.css"])
# Template Plugin
def get_template_configs(self):
return [
dict(type="settings", name=gettext("Announcements"), template="announcements_settings.jinja2", custom_bindings=True),
dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.isAdmin")
]
# Blueprint Plugin
@octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"])
@restricted_access
@admin_permission.require(403)
def get_channel_data(self):
from octoprint.settings import valid_boolean_trues
result = dict()
force = "force" in flask.request.values and flask.request.values["force"] in valid_boolean_trues
channel_data = self._fetch_all_channels(force=force)
channel_configs = self._get_channel_configs(force=force)
enabled = self._settings.get(["enabled_channels"])
forced = self._settings.get(["forced_channels"])
for key, data in channel_configs.items():
read_until = channel_configs[key].get("read_until", None)
entries = sorted(self._to_internal_feed(channel_data.get(key, []), read_until=read_until), key=lambda e: e["published"], reverse=True)
unread = len(filter(lambda e: not e["read"], entries))
if read_until is None and entries:
last = entries[0]["published"]
self._mark_read_until(key, last)
result[key] = dict(channel=data["name"],
url=data["url"],
priority=data.get("priority", 2),
enabled=key in enabled or key in forced,
forced=key in forced,
data=entries,
unread=unread)
return flask.jsonify(result)
@octoprint.plugin.BlueprintPlugin.route("/channels/<channel>", methods=["POST"])
@restricted_access
@admin_permission.require(403)
def channel_command(self, channel):
from octoprint.server.util.flask import get_json_command_from_request
from octoprint.server import NO_CONTENT
valid_commands = dict(read=["until"],
toggle=[])
command, data, response = get_json_command_from_request(flask.request, valid_commands=valid_commands)
if response is not None:
return response
if command == "read":
until = data["until"]
self._mark_read_until(channel, until)
elif command == "toggle":
self._toggle(channel)
return NO_CONTENT
# Internal Tools
def _mark_read_until(self, channel, until):
"""Set read_until timestamp of a channel."""
current_read_until = None
channel_data = self._settings.get(["channels", channel], merged=True)
if channel_data:
current_read_until = channel_data.get("read_until", None)
defaults = dict(plugins=dict(announcements=dict(channels=dict())))
defaults["plugins"]["announcements"]["channels"][channel] = dict(read_until=current_read_until)
with self._cached_channel_configs_mutex:
self._settings.set(["channels", channel, "read_until"], until, defaults=defaults)
self._settings.save()
self._cached_channel_configs = None
def _toggle(self, channel):
"""Toggle enable/disabled state of a channel."""
enabled_channels = list(self._settings.get(["enabled_channels"]))
if channel in enabled_channels:
enabled_channels.remove(channel)
else:
enabled_channels.append(channel)
self._settings.set(["enabled_channels"], enabled_channels)
self._settings.save()
def _get_channel_configs(self, force=False):
"""Retrieve all channel configs with sanitized keys."""
with self._cached_channel_configs_mutex:
if self._cached_channel_configs is None or force:
configs = self._settings.get(["channels"], merged=True)
result = dict()
for key, config in configs.items():
if "url" not in config or "name" not in config:
# strip invalid entries
continue
result[self._slugify(key)] = config
self._cached_channel_configs = result
return self._cached_channel_configs
def _get_channel_config(self, key, force=False):
"""Retrieve specific channel config for channel."""
safe_key = self._slugify(key)
return self._get_channel_configs(force=force).get(safe_key)
def _fetch_all_channels(self, force=False):
"""Fetch all channel feeds from cache or network."""
channels = self._get_channel_configs(force=force)
enabled = self._settings.get(["enabled_channels"])
forced = self._settings.get(["forced_channels"])
all_channels = dict()
for key, config in channels.items():
if not key in enabled and not key in forced:
continue
if not "url" in config:
continue
data = self._get_channel_data(key, config, force=force)
if data is not None:
all_channels[key] = data
return all_channels
def _get_channel_data(self, key, config, force=False):
"""Fetch individual channel feed from cache/network."""
data = None
if not force:
# we may use the cache, see if we have something in there
data = self._get_channel_data_from_cache(key, config)
if data is None:
# cache not allowed or empty, fetch from network
data = self._get_channel_data_from_network(key, config)
return data
def _get_channel_data_from_cache(self, key, config):
"""Fetch channel feed from cache."""
channel_path = self._get_channel_cache_path(key)
if os.path.exists(channel_path):
if "ttl" in config and isinstance(config["ttl"], int):
ttl = config["ttl"]
else:
ttl = self._settings.get_int(["ttl"])
ttl *= 60
now = time.time()
if os.stat(channel_path).st_mtime + ttl > now:
d = feedparser.parse(channel_path)
self._logger.debug(u"Loaded channel {} from cache at {}".format(key, channel_path))
return d
return None
def _get_channel_data_from_network(self, key, config):
"""Fetch channel feed from network."""
import requests
url = config["url"]
try:
start = time.time()
r = requests.get(url)
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start))
except Exception as e:
self._logger.exception(
u"Could not fetch channel {} from {}: {}".format(key, config["url"], str(e)))
return None
response = r.text
channel_path = self._get_channel_cache_path(key)
with codecs.open(channel_path, mode="w", encoding="utf-8") as f:
f.write(response)
return feedparser.parse(response)
def _to_internal_feed(self, feed, read_until=None):
"""Convert feed to internal data structure."""
result = []
if "entries" in feed:
for entry in feed["entries"]:
internal_entry = self._to_internal_entry(entry, read_until=read_until)
if internal_entry:
result.append(internal_entry)
return result
def _to_internal_entry(self, entry, read_until=None):
"""Convert feed entries to internal data structure."""
published = calendar.timegm(entry["published_parsed"])
read = True
if read_until is not None:
read = published <= read_until
return dict(title=entry["title"],
title_without_tags=_strip_tags(entry["title"]),
summary=entry["summary"],
summary_without_images=_strip_images(entry["summary"]),
published=published,
link=entry["link"],
read=read)
def _get_channel_cache_path(self, key):
"""Retrieve cache path for channel key."""
safe_key = self._slugify(key)
return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key))
_image_tag_re = re.compile(r'<img.*?/?>')
def _strip_images(text):
return _image_tag_re.sub('', text)
def _strip_tags(text):
"""
>>> _strip_tags(u"<a href='test.html'>Hello world</a>&lt;img src='foo.jpg'&gt;")
u"Hello world&lt;img src='foo.jpg'&gt;"
>>> _strip_tags(u"&#62; &#x3E; Foo")
u'&#62; &#x3E; Foo'
"""
from HTMLParser import HTMLParser
class TagStripper(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self._fed = []
def handle_data(self, data):
self._fed.append(data)
def handle_entityref(self, ref):
self._fed.append("&{};".format(ref))
def handle_charref(self, ref):
self._fed.append("&#{};".format(ref))
def get_data(self):
return "".join(self._fed)
tag_stripper = TagStripper()
tag_stripper.feed(text)
return tag_stripper.get_data()
__plugin_name__ = "Announcement Plugin"
__plugin_implementation__ = AnnouncementPlugin()
@@ -1 +0,0 @@
table td.settings_plugin_announcements_channels_name,table th.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_announcements_channels_actions,table th.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table td.settings_plugin_announcements_channels_actions a,table th.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table td.settings_plugin_announcements_channels_actions a.disabled,table th.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:700}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:#000}
@@ -1,304 +0,0 @@
$(function() {
function AnnouncementsViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.settings = parameters[1];
self.channels = new ItemListHelper(
"plugin.announcements.channels",
{
"channel": function (a, b) {
// sorts ascending
if (a["channel"].toLocaleLowerCase() < b["channel"].toLocaleLowerCase()) return -1;
if (a["channel"].toLocaleLowerCase() > b["channel"].toLocaleLowerCase()) return 1;
return 0;
}
},
{
},
"name",
[],
[],
5
);
self.unread = ko.observable();
self.hiddenChannels = [];
self.channelNotifications = {};
self.announcementDialog = undefined;
self.announcementDialogContent = undefined;
self.announcementDialogTabs = undefined;
self.setupTabLink = function(item) {
$("a[data-toggle='tab']", item).on("show", self.resetContentScroll);
};
self.resetContentScroll = function() {
self.announcementDialogContent.scrollTop(0);
};
self.toggleButtonCss = function(data) {
var icon = data.enabled ? "icon-circle" : "icon-circle-blank";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
};
self.toggleButtonTitle = function(data) {
return data.forced ? gettext("Cannot be toggled") : (data.enabled ? gettext("Disable Channel") : gettext("Enable Channel"));
};
self.enableToggle = function(data) {
return !data.forced;
};
self.markRead = function(channel, until) {
if (!self.loginState.isAdmin()) return;
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
var payload = {
command: "read",
until: until
};
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: JSON.stringify(payload),
contentType: "application/json; charset=UTF-8",
success: function() {
self.retrieveData()
}
})
};
self.toggleChannel = function(channel) {
if (!self.loginState.isAdmin()) return;
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
var payload = {
command: "toggle"
};
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: JSON.stringify(payload),
contentType: "application/json; charset=UTF-8",
success: function() {
self.retrieveData()
}
})
};
self.refreshAnnouncements = function() {
self.retrieveData(true);
};
self.retrieveData = function(force) {
if (!self.loginState.isAdmin()) return;
var url = PLUGIN_BASEURL + "announcements/channels";
if (force) {
url += "?force=true";
}
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(data) {
self.fromResponse(data);
}
});
};
self.fromResponse = function(data) {
var currentTab = $("li.active a", self.announcementDialogTabs).attr("href");
var unread = 0;
var channels = [];
_.each(data, function(value, key) {
value.key = key;
value.last = value.data.length ? value.data[0].published : undefined;
value.count = value.data.length;
unread += value.unread;
channels.push(value);
});
self.channels.updateItems(channels);
self.unread(unread);
self.displayAnnouncements(channels);
self.selectTab(currentTab);
};
self.showAnnouncementDialog = function(channel) {
self.announcementDialogContent.scrollTop(0);
if (!self.announcementDialog.hasClass("in")) {
self.announcementDialog.modal({
minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
}).css({
width: 'auto',
'margin-left': function() { return -($(this).width() /2); }
});
}
var tab = undefined;
if (channel) {
tab = "#plugin_announcements_dialog_channel_" + channel;
}
self.selectTab(tab);
return false;
};
self.selectTab = function(tab) {
if (tab != undefined) {
if (!_.startsWith(tab, "#")) {
tab = "#" + tab;
}
$('a[href="' + tab + '"]', self.announcementDialogTabs).tab("show");
} else {
$('a:first', self.announcementDialogTabs).tab("show");
}
};
self.displayAnnouncements = function(channels) {
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
var cutAfterNewline = function(text) {
text = text.trim();
var firstNewlinePos = text.indexOf("\n");
if (firstNewlinePos > 0) {
text = text.substr(0, firstNewlinePos).trim();
}
return text;
};
var stripParagraphs = function(text) {
if (_.startsWith(text, "<p>")) {
text = text.substr("<p>".length);
}
if (_.endsWith(text, "</p>")) {
text = text.substr(0, text.length - "</p>".length);
}
return text.replace(/<\/p>\s*<p>/ig, "<br>");
};
_.each(channels, function(value) {
var key = value.key;
var channel = value.channel;
var priority = value.priority;
var items = value.data;
if ($.inArray(key, self.hiddenChannels) > -1) {
// channel currently ignored
return;
}
var newItems = _.filter(items, function(entry) { return !entry.read; });
if (newItems.length == 0) {
// no new items at all, we don't display anything for this channel
return;
}
var displayedItems;
if (newItems.length > displayLimit) {
displayedItems = newItems.slice(0, displayLimit);
} else {
displayedItems = newItems;
}
var rest = newItems.length - displayedItems.length;
var text = "<ul>";
_.each(displayedItems, function(item) {
var limitedSummary = stripParagraphs(item.summary_without_images.trim());
if (limitedSummary.length > maxLength) {
limitedSummary = limitedSummary.substr(0, maxLength);
limitedSummary = limitedSummary.substr(0, Math.min(limitedSummary.length, limitedSummary.lastIndexOf(" ")));
limitedSummary += "...";
}
text += "<li><a href='" + item.link + "' target='_blank' rel='noreferrer noopener'>" + cutAfterNewline(item.title) + "</a><br><small>" + formatTimeAgo(item.published) + "</small><p>" + limitedSummary + "</p></li>";
});
text += "</ul>";
if (rest) {
text += gettext(_.sprintf("... and %(rest)d more.", {rest: rest}));
}
var options = {
title: channel,
text: text,
hide: false,
confirm: {
confirm: true,
buttons: [{
text: gettext("Later"),
click: function(notice) {
self.hiddenChannels.push(key);
notice.remove();
}
}, {
text: gettext("Mark read"),
click: function(notice) {
self.markRead(key, value.last);
notice.remove();
}
}, {
text: gettext("Read..."),
addClass: "btn-primary",
click: function(notice) {
self.showAnnouncementDialog(key);
self.markRead(key, value.last);
notice.remove();
}
}]
},
buttons: {
sticker: false,
closer: false
}
};
if (priority == 1) {
options.type = "error";
}
if (self.channelNotifications[key]) {
self.channelNotifications[key].remove();
}
self.channelNotifications[key] = new PNotify(options);
});
};
self.onUserLoggedIn = function() {
self.retrieveData();
};
self.onStartup = function() {
self.announcementDialog = $("#plugin_announcements_dialog");
self.announcementDialogContent = $("#plugin_announcements_dialog_content");
self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs");
}
}
// view model class, parameters for constructor, container to bind to
ADDITIONAL_VIEWMODELS.push([
AnnouncementsViewModel,
["loginStateViewModel", "settingsViewModel"],
["#plugin_announcements_dialog", "#settings_plugin_announcements", "#navbar_plugin_announcements"]
]);
});
@@ -1,56 +0,0 @@
table {
th, td {
&.settings_plugin_announcements_channels_name {
text-overflow: ellipsis;
text-align: left;
}
&.settings_plugin_announcements_channels_actions {
text-align: center;
width: 80px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
}
}
}
#plugin_announcements_dialog {
.unread {
font-weight: bold;
}
article {
padding-right: 20px;
&.read {
opacity: 0.5;
}
&.read:hover {
opacity: 1;
}
.actions {
background-color: #f5f5f5;
border-radius: 2px;
padding: 2px 5px;
margin-top: 5px;
.markread {
float: right;
}
a {
color: black;
}
}
}
}
@@ -1,45 +0,0 @@
<div id="plugin_announcements_dialog" class="modal hide fade large" tabindex="-1" role="dialog" aria-labelledby="announcements_dialog_label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h3 id="announcements_dialog_label">{{ _('Announcements') }}</h3>
</div>
<div class="modal-body">
<div class="full-sized-box">
<div class="tabbable row-fluid">
<div class="span3 scrollable" id="plugin_announcements_dialog_menu">
<ul class="nav nav-list" id="plugin_announcements_dialog_tabs">
<!-- ko foreach: {data: channels.items, afterAdd: setupTabLink} -->
<!-- ko if: $data.enabled || $data.forced -->
<li>
<a data-toggle="tab" target="_blank" data-bind="text: $data.channel + ' (' + $data.unread + '/' + $data.count + ')', attr: {href: '#plugin_announcements_dialog_channel_' + $data.key}, css: {unread: $data.unread}"></a>
</li>
<!-- /ko -->
<!-- /ko -->
</ul>
</div>
<div class="tab-content span9 scrollable" id="plugin_announcements_dialog_content">
<!-- ko foreach: channels.items -->
<!-- ko if: $data.enabled || $data.forced -->
<div class="tab-pane" data-bind="attr: {id: 'plugin_announcements_dialog_channel_' + $data.key}">
<!-- ko foreach: $data.data -->
<article data-bind="css: {read: $data.read}">
<hr data-bind="visible: $index() > 0">
<h3><a data-bind="text: $data.title, attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a> <small data-bind="text: formatTimeAgo($data.published), attr: {title: formatDate($data.published)}"></small></h3>
<div class="content" data-bind="html: $data.summary"></div>
<div class="actions">
<span class="articlelink"><small><a data-bind="text: $data.link, attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a></small></span>
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published) }"><i class="icon-eye-open"></i> {{ _('Mark as last read') }}</a></small></span>
</div>
</article>
<!-- /ko -->
</div>
<!-- /ko -->
<!-- /ko -->
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-block" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
@@ -1,3 +0,0 @@
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements') }}">
<i data-bind="css: {'icon-bell': !unread(), 'icon-bell-alt': unread()}"></i>
</a>
@@ -1,34 +0,0 @@
<h3>{{ _('Configured Channels') }}</h3>
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_announcements_channels_name">{{ _('Name') }}</th>
<th class="settings_plugin_announcements_channels_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: channels.paginatedItems">
<tr>
<td class="settings_plugin_announcements_channels_name">
<div data-bind="text: channel, css: {muted: !enabled}"></div>
<div><small class="muted" data-bind="text: url">&nbsp;</small></div>
</td>
<td class="settings_plugin_announcements_channels_actions">
<a href="javascript:void(0)" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.toggleChannel($data.key) }"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: channels.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: channels.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: channels.pages">
<li data-bind="css: { active: $data.number === $root.channels.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.channels.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: channels.currentPage() === channels.lastPage()}"><a href="javascript:void(0)" data-bind="click: channels.nextPage">»</a></li>
</ul>
</div>
<button class="btn btn-block" data-bind="click: $root.refreshAnnouncements"><i class="icon-refresh"></i> {{ _('Refresh Announcements') }}</button>
+4 -3
View File
@@ -166,9 +166,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
type="cura",
name="CuraEngine",
same_device=True,
progress_report=True,
source_file_types=["stl"],
destination_extensions=["gco", "gcode", "g"]
progress_report=True
)
def get_slicer_default_profile(self):
@@ -193,6 +191,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
return octoprint.slicing.SlicingProfile(properties["type"], "unknown", profile_dict, display_name=display_name, description=description)
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
if os.path.exists(path) and not allow_overwrite:
raise octoprint.slicing.ProfileAlreadyExists("cura", profile.name)
new_profile = Profile.merge_profile(profile.data, overrides=overrides)
if profile.display_name is not None:
@@ -113,20 +113,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
def get_template_configs(self):
return [
dict(type="settings", name=gettext("Plugin Manager"), template="pluginmanager_settings.jinja2", custom_bindings=True),
dict(type="about", name="Plugin Licenses", template="pluginmanager_about.jinja2")
]
def get_template_vars(self):
plugins = sorted(self._get_plugins(), key=lambda x: x["name"].lower())
return dict(
all=plugins,
thirdparty=filter(lambda p: not p["bundled"], plugins)
)
def get_template_types(self, template_sorting, template_rules, *args, **kwargs):
return [
("about_thirdparty", dict(), dict(template=lambda x: x + "_about_thirdparty.jinja2"))
dict(type="settings", name=gettext("Plugin Manager"), template="pluginmanager_settings.jinja2", custom_bindings=True)
]
##~~ BlueprintPlugin
@@ -646,18 +633,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
return octoprint_version
def _get_plugins(self):
plugins = self._plugin_manager.plugins
hidden = self._settings.get(["hidden"])
result = []
for name, plugin in plugins.items():
if name in hidden:
continue
result.append(self._to_external_representation(plugin))
return result
def _to_external_representation(self, plugin):
return dict(
key=plugin.key,
@@ -688,6 +663,5 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize,
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize
}
@@ -1,18 +0,0 @@
<h3>Plugin Licenses</h3>
<ul>
{% for plugin in plugin_pluginmanager_thirdparty %}
<li>{% if plugin.url %}<a href="{{ plugin.url }}" target="_blank" rel="noreferrer noopener">{% endif %}{{ plugin.name }}{% if plugin.url %}</a>{% endif %}: {% if plugin.license %}{{ plugin.license }}{% else %}-{% endif %}</li>
{% endfor %}
</ul>
{% if templates.plugin_pluginmanager_about_thirdparty.order %}
<h3>Licenses of Plugin Dependencies</h3>
{% for key in templates.plugin_pluginmanager_about_thirdparty.order %}
{% set heading, config = templates.plugin_pluginmanager_about_thirdparty.entries[key] %}
<h4>{{ heading }}</h4>
{% include config.template ignore missing %}
{% endfor %}
{% endif %}
@@ -45,7 +45,7 @@
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i title="Restart needed" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_uninstall"></i> <i title="Uninstalled" class="icon-remove" data-bind="visible: pending_uninstall"></i></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div data-bind="css: {muted: !enabled}">
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
<small>&nbsp;</small>
@@ -342,7 +342,7 @@ $(function() {
};
self.confirmUpdate = function() {
self.confirmationDialog.modal("hide");
self.confirmationDialog.hide();
self.performUpdate(self.forceUpdate,
_.map(self.availableAndPossible(), function(info) { return info.key }));
};
@@ -11,7 +11,7 @@
<!-- ko foreach: availableAndPossible -->
<li>
<span class="name" data-bind="text: fullNameRemote, attr: {title: fullNameRemote}"></span>
<div class="releaseNotes" data-bind="visible: releaseNotes"><a data-bind="attr: {href: releaseNotes}" target="_blank" rel="noreferrer noopener">{{ _('Release Notes') }}</a></div>
<div class="releaseNotes" data-bind="visible: releaseNotes"><a data-bind="attr: {href: releaseNotes}">{{ _('Release Notes') }}</a></div>
</li>
<!-- /ko -->
</ul>
@@ -33,7 +33,7 @@
<small class="muted">
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span><br>
<span data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
<span data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank"></a></span>
</small>
</td>
</tr>
+65 -166
View File
@@ -16,7 +16,7 @@ from serial import SerialTimeoutException
from octoprint.settings import settings
from octoprint.plugin import plugin_manager
class VirtualPrinter(object):
class VirtualPrinter():
command_regex = re.compile("[GM]\d+")
sleep_regex = re.compile("sleep (\d+)")
sleep_after_regex = re.compile("sleep_after ([GM]\d+) (\d+)")
@@ -25,19 +25,17 @@ class VirtualPrinter(object):
def __init__(self, read_timeout=5.0, write_timeout=10.0):
import logging
self._logger = logging.getLogger("octoprint.plugins.virtual_printer.VirtualPrinter")
self._logger = logging.getLogger("octoprint.plugin.virtual_printer.VirtualPrinter")
self._read_timeout = read_timeout
self._write_timeout = write_timeout
self._rx_buffer_size = settings().getInt(["devel", "virtualPrinter", "rxBuffer"])
self.incoming = CharCountingQueue(self._rx_buffer_size, name="RxBuffer")
self.incoming = CharCountingQueue(settings().getInt(["devel", "virtualPrinter", "rxBuffer"]), name="RxBuffer")
self.outgoing = Queue.Queue()
self.buffered = Queue.Queue(maxsize=settings().getInt(["devel", "virtualPrinter", "commandBuffer"]))
for item in ['start\n', 'Marlin: Virtual Marlin!\n', '\x80\n', 'SD card ok\n']:
self._output(item)
self.outgoing.put(item)
self.currentExtruder = 0
self.temp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
@@ -82,8 +80,6 @@ class VirtualPrinter(object):
self._incoming_lock = threading.RLock()
self._debug_awol = False
self._debug_sleep = None
self._sleepAfterNext = dict()
self._sleepAfter = dict()
@@ -99,37 +95,19 @@ class VirtualPrinter(object):
self._triggerResendWithTimeoutAt105 = True
self._triggeredResendWithTimeoutAt105 = False
waitThread = threading.Thread(target=self._sendWaitAfterTimeout, name="octoprint.plugins.virtual_printer.wait_thread")
waitThread = threading.Thread(target=self._sendWaitAfterTimeout)
waitThread.start()
readThread = threading.Thread(target=self._processIncoming, name="octoprint.plugins.virtual_printer.read_thread")
readThread = threading.Thread(target=self._processIncoming)
readThread.start()
bufferThread = threading.Thread(target=self._processBuffer, name="octoprint.plugins.virtual_printer.buffer_thread")
bufferThread = threading.Thread(target=self._processBuffer)
bufferThread.start()
def __str__(self):
return "VIRTUAL(read_timeout={read_timeout},write_timeout={write_timeout},options={options})"\
.format(read_timeout=self._read_timeout, write_timeout=self._write_timeout, options=settings().get(["devel", "virtualPrinter"]))
@property
def timeout(self):
return self._read_timeout
@timeout.setter
def timeout(self, value):
self._logger.debug("Setting read timeout to {}s".format(value))
self._read_timeout = value
@property
def write_timeout(self):
return self._write_timeout
@write_timeout.setter
def write_timeout(self, value):
self._logger.debug("Setting write timeout to {}s".format(value))
self._write_timeout = value
def _clearQueue(self, queue):
try:
while queue.get(block=False):
@@ -139,26 +117,17 @@ class VirtualPrinter(object):
def _processIncoming(self):
next_wait_timeout = time.time() + self._waitInterval
buf = ""
while self.incoming is not None and not self._killed:
self._simulateTemps()
try:
data = self.incoming.get(timeout=0.01)
self.incoming.task_done()
except Queue.Empty:
if self._sendWait and time.time() > next_wait_timeout:
self._output("wait")
self.outgoing.put("wait")
next_wait_timeout = time.time() + self._waitInterval
continue
buf += data
if "\n" in buf:
data = buf[:buf.find("\n") + 1]
buf = buf[buf.find("\n") + 1:]
else:
continue
next_wait_timeout = time.time() + self._waitInterval
if data is None:
@@ -172,15 +141,10 @@ class VirtualPrinter(object):
# strip checksum
if "*" in data:
checksum = int(data[data.rfind("*") + 1:])
data = data[:data.rfind("*")]
if not checksum == self._calculate_checksum(data):
self._triggerResend(expected=self.currentLine + 1)
continue
self.currentLine += 1
elif settings().getBoolean(["devel", "virtualPrinter", "forceChecksum"]):
self._output("Error: Missing checksum")
self.outgoing.put("Error: Missing checksum")
continue
# track N = N + 1
@@ -226,7 +190,7 @@ class VirtualPrinter(object):
if data.strip() == "version":
from octoprint._version import get_versions
self._output("OctoPrint VirtualPrinter v" + get_versions()["version"])
self.outgoing.put("OctoPrint VirtualPrinter v" + get_versions()["version"])
continue
elif data.startswith("!!DEBUG:"):
self._debugTrigger(data[len("!!DEBUG:"):].strip())
@@ -250,7 +214,7 @@ class VirtualPrinter(object):
self._listSd()
elif 'M21' in data:
self._sdCardReady = True
self._output("SD card ok")
self.outgoing.put("SD card ok")
elif 'M22' in data:
self._sdCardReady = False
elif 'M23' in data:
@@ -285,21 +249,21 @@ class VirtualPrinter(object):
self._deleteSdFile(filename)
elif "M114" in data:
# send dummy position report
output = "X:10.00 Y:3.20 Z:5.20 E:1.24 Count: A:1000 B:320 C:1040"
output = "C: X:10.00 Y:3.20 Z:5.20 E:1.24"
if not self._okBeforeCommandOutput:
output = "ok " + output
self._output(output)
self.outgoing.put(output)
continue
elif "M117" in data:
# we'll just use this to echo a message, to allow playing around with pause triggers
if self._echoOnM117:
self._output("echo:%s" % re.search("M117\s+(.*)", data).group(1))
self.outgoing.put("echo:%s" % re.search("M117\s+(.*)", data).group(1))
elif "M999" in data:
# mirror Marlin behaviour
self._output("Resend: 1")
self.outgoing.put("Resend: 1")
elif data.startswith("T"):
self.currentExtruder = int(re.search("T(\d+)", data).group(1))
self._output("Active Extruder: %d" % self.currentExtruder)
self.outgoing.put("Active Extruder: %d" % self.currentExtruder)
elif "G20" in data:
self._unitModifier = 1.0 / 2.54
if self._lastX is not None:
@@ -347,25 +311,17 @@ class VirtualPrinter(object):
del self._sleepAfterNext[command]
if interval is not None:
self._output("// sleeping for {interval} seconds".format(interval=interval))
self.outgoing.put("// sleeping for {interval} seconds".format(interval=interval))
time.sleep(interval)
if len(data.strip()) > 0 and not self._okBeforeCommandOutput:
self._sendOk()
self._logger.info("Closing down read loop")
def _calculate_checksum(self, line):
checksum = 0
for c in line:
checksum ^= ord(c)
return checksum
def _kill(self):
if not self._supportM112:
return
self._killed = True
self._output("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
self.outgoing.put("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
def _triggerResend(self, expected=None, actual=None):
with self._incoming_lock:
@@ -375,13 +331,13 @@ class VirtualPrinter(object):
self.lastN = expected - 1
if actual is None:
self._output("Error: Wrong checksum")
self.outgoing.put("Error: Wrong checksum")
else:
self._output("Error: expected line %d got %d" % (expected, actual))
self.outgoing.put("Error: expected line %d got %d" % (expected, actual))
def request_resend():
self._output("Resend:%d" % expected)
self._output("ok")
self.outgoing.put("Resend:%d" % expected)
self.outgoing.put("ok")
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
request_resend()
@@ -389,11 +345,11 @@ class VirtualPrinter(object):
def _debugTrigger(self, data):
if data == "action_pause":
self._output("// action:pause")
self.outgoing.put("// action:pause")
elif data == "action_resume":
self._output("// action:resume")
self.outgoing.put("// action:resume")
elif data == "action_disconnect":
self._output("// action:disconnect")
self.outgoing.put("// action:disconnect")
elif data == "dont_answer":
self._dont_answer = True
elif data == "trigger_resend_lineno":
@@ -403,10 +359,7 @@ class VirtualPrinter(object):
elif data == "drop_connection":
self._debug_drop_connection = True
elif data == "maxtemp_error":
self._output("Error: MAXTEMP triggered!")
elif data == "go_awol":
self._output("// Going AWOL")
self._debug_awol = True
self.outgoing.put("Error: MAXTEMP triggered!")
else:
try:
sleep_match = VirtualPrinter.sleep_regex.match(data)
@@ -416,28 +369,28 @@ class VirtualPrinter(object):
if sleep_match is not None:
interval = int(sleep_match.group(1))
self._output("// sleeping for {interval} seconds".format(interval=interval))
self._debug_sleep = interval
self.outgoing.put("// sleeping for {interval} seconds".format(interval=interval))
time.sleep(interval)
elif sleep_after_match is not None:
command = sleep_after_match.group(1)
interval = int(sleep_after_match.group(2))
self._sleepAfter[command] = interval
self._output("// going to sleep {interval} seconds after each {command}".format(**locals()))
self.outgoing.put("// going to sleep {interval} seconds after each {command}".format(**locals()))
elif sleep_after_next_match is not None:
command = sleep_after_next_match.group(1)
interval = int(sleep_after_next_match.group(2))
self._sleepAfterNext[command] = interval
self._output("// going to sleep {interval} seconds after next {command}".format(**locals()))
self.outgoing.put("// going to sleep {interval} seconds after next {command}".format(**locals()))
elif custom_action_match is not None:
action = custom_action_match.group(1)
params = custom_action_match.group(2)
params = params.strip() if params is not None else ""
self._output("// action:{action} {params}".format(**locals()).strip())
self.outgoing.put("// action:{action} {params}".format(**locals()).strip())
except:
pass
def _listSd(self):
self._output("Begin file list")
self.outgoing.put("Begin file list")
if settings().getBoolean(["devel", "virtualPrinter", "extendedSdFileList"]):
items = map(
lambda x: "%s %d" % (x.upper(), os.stat(os.path.join(self._virtualSd, x)).st_size),
@@ -449,23 +402,20 @@ class VirtualPrinter(object):
os.listdir(self._virtualSd)
)
for item in items:
self._output(item)
self._output("End file list")
self.outgoing.put(item)
self.outgoing.put("End file list")
def _selectSdFile(self, filename):
if filename.startswith("/"):
filename = filename[1:]
file = os.path.join(self._virtualSd, filename.lower())
if not os.path.exists(file) or not os.path.isfile(file):
self._output("open failed, File: %s." % filename)
self.outgoing.put("open failed, File: %s." % filename)
else:
self._selectedSdFile = file
self._selectedSdFileSize = os.stat(file).st_size
if settings().getBoolean(["devel", "virtualPrinter", "includeFilenameInOpened"]):
self._output("File opened: %s Size: %d" % (filename, self._selectedSdFileSize))
else:
self._output("File opened")
self._output("File selected")
self.outgoing.put("File opened: %s Size: %d" % (filename, self._selectedSdFileSize))
self.outgoing.put("File selected")
def _startSdPrint(self):
if self._selectedSdFile is not None:
@@ -482,9 +432,9 @@ class VirtualPrinter(object):
def _reportSdStatus(self):
if self._sdPrinter is not None and self._sdPrintingSemaphore.is_set:
self._output("SD printing byte %d/%d" % (self._selectedSdFilePos, self._selectedSdFileSize))
self.outgoing.put("SD printing byte %d/%d" % (self._selectedSdFilePos, self._selectedSdFileSize))
else:
self._output("Not SD printing")
self.outgoing.put("Not SD printing")
def _processTemperatureQuery(self):
includeTarget = not settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"])
@@ -521,7 +471,7 @@ class VirtualPrinter(object):
if includeOk:
output = "ok " + output
self._output(output)
self.outgoing.put(output)
def _parseHotendCommand(self, line):
tool = 0
@@ -543,7 +493,7 @@ class VirtualPrinter(object):
if "M109" in line:
self._waitForHeatup("tool%d" % tool)
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
self._output("TargetExtr%d:%d" % (tool, self.targetTemp[tool]))
self.outgoing.put("TargetExtr%d:%d" % (tool, self.targetTemp[tool]))
def _parseBedCommand(self, line):
try:
@@ -554,7 +504,7 @@ class VirtualPrinter(object):
if "M190" in line:
self._waitForHeatup("bed")
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
self._output("TargetBed:%d" % self.bedTargetTemp)
self.outgoing.put("TargetBed:%d" % self.bedTargetTemp)
def _performMove(self, line):
matchX = re.search("X([0-9.]+)", line)
@@ -605,13 +555,10 @@ class VirtualPrinter(object):
pass
if duration:
if duration > self._read_timeout:
slept = 0
while duration - slept > self._read_timeout and not self._killed:
time.sleep(self._read_timeout)
slept += self._read_timeout
else:
time.sleep(duration)
slept = 0
while duration - slept > self._read_timeout and not self._killed:
time.sleep(self._read_timeout)
slept += self._read_timeout
def _setPosition(self, line):
matchX = re.search("X([0-9.]+)", line)
@@ -651,13 +598,13 @@ class VirtualPrinter(object):
if os.path.isfile(file):
os.remove(file)
else:
self._output("error writing to file")
self.outgoing.put("error writing to file")
handle = None
try:
handle = open(file, "w")
except:
self._output("error writing to file")
self.outgoing.put("error writing to file")
if handle is not None:
try:
handle.close()
@@ -666,7 +613,7 @@ class VirtualPrinter(object):
self._writingToSdHandle = handle
self._writingToSd = True
self._selectedSdFile = file
self._output("Writing to file: %s" % filename)
self.outgoing.put("Writing to file: %s" % filename)
def _finishSdFile(self):
try:
@@ -677,7 +624,7 @@ class VirtualPrinter(object):
self._writingToSdHandle = None
self._writingToSd = False
self._selectedSdFile = None
self._output("Done saving file")
self.outgoing.put("Done saving file")
def _sdPrintingWorker(self):
self._selectedSdFilePos = 0
@@ -715,7 +662,7 @@ class VirtualPrinter(object):
self._sdPrintingSemaphore.clear()
self._selectedSdFilePos = 0
self._sdPrinter = None
self._output("Done printing file")
self.outgoing.put("Done printing file")
def _waitForHeatup(self, heater):
delta = 1
@@ -726,12 +673,12 @@ class VirtualPrinter(object):
toolNum = int(heater[len("tool"):])
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._output("T:%0.2f" % self.temp[toolNum])
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
time.sleep(delay)
elif heater == "bed":
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta):
self._simulateTemps(delta=delta)
self._output("B:%0.2f" % self.bedTemp)
self.outgoing.put("B:%0.2f" % self.bedTemp)
time.sleep(delay)
except AttributeError:
if self.outgoing is not None:
@@ -774,73 +721,34 @@ class VirtualPrinter(object):
continue
self._performMove(line)
self.buffered.task_done()
self._logger.info("Closing down buffer loop")
def _output(self, line):
try:
self.outgoing.put(line)
except:
if self.outgoing is None:
pass
def write(self, data):
if self._debug_awol:
return len(data)
if self._debug_drop_connection:
self._logger.info("Debug drop of connection requested, raising SerialTimeoutException")
raise SerialTimeoutException()
with self._incoming_lock:
if self.incoming is None or self.outgoing is None:
return 0
return
if "M112" in data and self._supportM112:
self._kill()
return len(data)
return
try:
return self.incoming.put(data, timeout=self._write_timeout, partial=True)
self.incoming.put(data, timeout=self._write_timeout)
except Queue.Full:
self._logger.info("Incoming queue is full, raising SerialTimeoutException")
raise SerialTimeoutException()
def readline(self):
if self._debug_awol:
time.sleep(self._read_timeout)
return ""
if self._debug_drop_connection:
raise SerialTimeoutException()
if self._debug_sleep > 0:
# if we are supposed to sleep, we sleep not longer than the read timeout
# (and then on the next call sleep again if there's time to sleep left)
sleep_for = min(self._debug_sleep, self._read_timeout)
self._debug_sleep -= sleep_for
time.sleep(sleep_for)
if self._debug_sleep > 0:
# we slept the full read timeout, return an empty line
return ""
# otherwise our left over timeout is the read timeout minus what we already
# slept for
timeout = self._read_timeout - sleep_for
else:
# use the full read timeout as timeout
timeout = self._read_timeout
try:
# fetch a line from the queue, wait no longer than timeout
line = self.outgoing.get(timeout=timeout)
self.outgoing.task_done()
line = self.outgoing.get(timeout=self._read_timeout)
return line
except Queue.Empty:
# queue empty? return empty line
return ""
def close(self):
@@ -854,14 +762,14 @@ class VirtualPrinter(object):
return
if settings().getBoolean(["devel", "virtualPrinter", "okWithLinenumber"]):
self._output("ok %d" % self.lastN)
self.outgoing.put("ok %d" % self.lastN)
else:
self._output("ok")
self.outgoing.put("ok")
def _sendWaitAfterTimeout(self, timeout=5):
time.sleep(timeout)
if self.outgoing is not None:
self._output("wait")
self.outgoing.put("wait")
class CharCountingQueue(Queue.Queue):
@@ -870,26 +778,22 @@ class CharCountingQueue(Queue.Queue):
self._size = 0
self._name = name
def put(self, item, block=True, timeout=None, partial=False):
def put(self, item, block=True, timeout=None):
self.not_full.acquire()
try:
if not self._will_it_fit(item) and partial:
space_left = self.maxsize - self._qsize()
if space_left:
item = item[:space_left]
item_size = self._len(item)
if not block:
if not self._will_it_fit(item):
if self._qsize() + item_size >= self.maxsize:
raise Queue.Full
elif timeout is None:
while not self._will_it_fit(item):
while self._qsize() + item_size >= self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = time.time() + timeout
while not self._will_it_fit(item):
while self._qsize() + item_size >= self.maxsize:
remaining = endtime - time.time()
if remaining <= 0.0:
raise Queue.Full
@@ -898,8 +802,6 @@ class CharCountingQueue(Queue.Queue):
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
return self._len(item)
finally:
self.not_full.release()
@@ -919,6 +821,3 @@ class CharCountingQueue(Queue.Queue):
item = self.queue.popleft()
self._size -= self._len(item)
return item
def _will_it_fit(self, item):
return self.maxsize - self._qsize() >= self._len(item)
+1 -16
View File
@@ -236,26 +236,11 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def pause_print(self):
"""
Pauses the current print job if it is currently running, does nothing otherwise.
"""
raise NotImplementedError()
def resume_print(self):
"""
Resumes the current print job if it is currently paused, does nothing otherwise.
"""
raise NotImplementedError()
def toggle_pause_print(self):
"""
Pauses the current print job if it is currently running or resumes it if it is currently paused.
"""
if self.is_printing():
self.pause_print()
elif self.is_paused():
self.resume_print()
raise NotImplementedError()
def cancel_print(self):
"""
+37 -174
View File
@@ -24,7 +24,6 @@ from octoprint.printer.estimation import TimeEstimationHelper
from octoprint.settings import settings
from octoprint.util import comm as comm
from octoprint.util import InvariantContainer
from octoprint.util import to_unicode
class Printer(PrinterInterface, comm.MachineComPrintCallback):
@@ -51,9 +50,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._temps = TemperatureHistory(cutoff=settings().getInt(["temperature", "cutoff"])*60)
self._tempBacklog = []
self._latestMessage = None
self._messages = deque([], 300)
self._messageBacklog = []
self._latestLog = None
self._log = deque([], 300)
self._logBacklog = []
@@ -72,10 +73,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._selectedFile = None
self._timeEstimationData = None
self._timeEstimationStatsWeighingUntil = settings().getFloat(["estimation", "printTime", "statsWeighingUntil"])
self._timeEstimationValidityRange = settings().getFloat(["estimation", "printTime", "validityRange"])
self._timeEstimationForceDumbFromPercent = settings().getFloat(["estimation", "printTime", "forceDumbFromPercent"])
self._timeEstimationForceDumbAfterMin = settings().getFloat(["estimation", "printTime", "forceDumbAfterMin"])
# comm
self._comm = None
@@ -363,7 +360,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._printAfterSelect = printAfterSelect
self._posAfterSelect = pos
self._comm.selectFile("/" + path if sd and not settings().getBoolean(["feature", "sdRelativePath"]) else path, sd)
self._comm.selectFile("/" + path if sd else path, sd)
self._setProgressData(completion=0)
self._setCurrentZ(None)
@@ -385,21 +382,20 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._selectedFile is None:
return
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = settings().getFloat(["estimation", "printTime", "stableThreshold"])
rolling_window = None
threshold = None
countdown = None
if self._selectedFile["sd"]:
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
# by that divided by the sd status polling interval
rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"])
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = 60
# we are happy when one rolling window has been stable
countdown = rolling_window
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window,
threshold=threshold,
countdown=countdown)
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
self._fileManager.delete_recovery_data()
@@ -408,29 +404,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setCurrentZ(None)
self._comm.startPrint(pos=pos)
def pause_print(self):
def toggle_pause_print(self):
"""
Pause the current printjob.
Pause the current printjob.
"""
if self._comm is None:
return
if self._comm.isPaused():
return
self._comm.setPause(True)
def resume_print(self):
"""
Resume the current printjob.
"""
if self._comm is None:
return
if not self._comm.isPaused():
return
self._comm.setPause(False)
self._comm.setPause(not self._comm.isPaused())
def cancel_print(self):
"""
@@ -547,10 +528,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self.refresh_sd_files(blocking=True)
existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles())
remoteName = util.get_dos_filename(filename,
existing_filenames=existingSdFiles,
extension="gco",
whitelisted_extensions=["gco", "g"])
remoteName = util.get_dos_filename(filename, existing_filenames=existingSdFiles, extension="gco")
self._timeEstimationData = TimeEstimationHelper()
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName)
@@ -590,12 +568,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._currentZ = currentZ
self._stateMonitor.set_current_z(self._currentZ)
def _setState(self, state, state_string=None):
if state_string is None:
state_string = self.get_state_string()
def _setState(self, state):
self._state = state
self._stateMonitor.set_state({"text": state_string, "flags": self._getStateFlags()})
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
def _addLog(self, log):
self._log.append(log)
@@ -637,16 +612,24 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
printTime = self._comm.getPrintTime()
cleanedPrintTime = self._comm.getCleanedPrintTime()
statisticalTotalPrintTime = None
statisticalTotalPrintTimeType = None
if self._selectedFile and "estimatedPrintTime" in self._selectedFile \
and self._selectedFile["estimatedPrintTime"]:
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
totalPrintTime = estimatedTotalPrintTime
if self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"]:
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None)
if progress and cleanedPrintTime:
if estimatedTotalPrintTime is None:
totalPrintTime = statisticalTotalPrintTime
else:
if progress < 0.5:
sub_progress = progress * 2
else:
sub_progress = 1.0
totalPrintTime = (1 - sub_progress) * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime
printTimeLeft, printTimeLeftOrigin = self._estimatePrintTimeLeft(progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType)
printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None
if progress is not None:
if progress:
progress_int = int(progress * 100)
if self._lastProgressReport != progress_int:
self._lastProgressReport = progress_int
@@ -655,123 +638,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return dict(completion=progress * 100 if progress is not None else None,
filepos=filepos,
printTime=int(printTime) if printTime is not None else None,
printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None,
printTimeLeftOrigin=printTimeLeftOrigin)
def _estimatePrintTimeLeft(self, progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType):
"""
Tries to estimate the print time left for the print job
This is somewhat horrible since accurate print time estimation is pretty much impossible to
achieve, considering that we basically have only two data points (current progress in file and
time needed for that so far - former prints or a file analysis might not have happened or simply
be completely impossible e.g. if the file is stored on the printer's SD card) and
hence can only do a linear estimation of a completely non-linear process. That's a recipe
for inaccurate predictions right there. Yay.
Anyhow, here's how this implementation works. This method gets the current progress in the
printed file (percentage based on bytes read vs total bytes), the print time that elapsed,
the same print time with the heat up times subtracted (if possible) and if available also
some statistical total print time (former prints or a result from the GCODE analysis).
1. First get an "intelligent" estimate based on the :class:`~octoprint.printer.estimation.TimeEstimationHelper`.
That thing tries to detect if the estimation based on our progress and time needed for that becomes
stable over time through a rolling window and only returns a result once that appears to be the
case.
2. If we have any statistical data (former prints or a result from the GCODE analysis)
but no intelligent estimate yet, we'll use that for the next step. Otherwise, up to a certain percentage
in the print we do a percentage based weighing of the statistical data and the intelligent
estimate - the closer to the beginning of the print, the more precedence for the statistical
data, the closer to the cut off point, the more precendence for the intelligent estimate. This
is our preliminary total print time.
3. If the total print time is set, we do a sanity check for it. Based on the total print time
estimate and the time we already spent printing, we calculate at what percentage we SHOULD be
and compare that to the percentage at which we actually ARE. If it's too far off, our total
can't be trusted and we fall back on the dumb estimate. Same if the time we spent printing is
already higher than our total estimate.
4. If we do NOT have a total print time estimate yet but we've been printing for longer than
a configured amount of minutes or are further in the file than a configured percentage, we
also use the dumb estimate for now.
Yes, all this still produces horribly inaccurate results. But we have to do this live during the print and
hence can't produce to much computational overhead, we do not have any insight into the firmware implementation
with regards to planner setup and acceleration settings, we might not even have access to the printed file's
contents and such we need to find something that works "mostly" all of the time without costing too many
resources. Feel free to propose a better solution within the above limitations (and I mean that, this solution
here makes me unhappy).
Args:
progress (float or None): Current percentage in the printed file
printTime (float or None): Print time elapsed so far
cleanedPrintTime (float or None): Print time elapsed minus the time needed for getting up to temperature
(if detectable).
statisticalTotalPrintTime (float or None): Total print time of past prints against same printer profile,
or estimated total print time from GCODE analysis.
statisticalTotalPrintTimeType (str or None): Type of statistical print time, either "average" (total time
of former prints) or "analysis"
Returns:
(2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation
"""
if progress is None or printTime is None or cleanedPrintTime is None:
return None
dumbTotalPrintTime = printTime / progress
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
totalPrintTime = estimatedTotalPrintTime
printTimeLeftOrigin = "estimate"
if statisticalTotalPrintTime is not None:
if estimatedTotalPrintTime is None:
# no estimate yet, we'll use the statistical total
totalPrintTime = statisticalTotalPrintTime
printTimeLeftOrigin = statisticalTotalPrintTimeType
else:
if progress < self._timeEstimationStatsWeighingUntil:
# still inside weighing range, use part stats, part current estimate
sub_progress = progress * (1 / self._timeEstimationStatsWeighingUntil)
if sub_progress > 1.0:
sub_progress = 1.0
printTimeLeftOrigin = "mixed-" + statisticalTotalPrintTimeType
else:
# use only the current estimate
sub_progress = 1.0
printTimeLeftOrigin = "estimate"
# combine
totalPrintTime = (1.0 - sub_progress) * statisticalTotalPrintTime \
+ sub_progress * estimatedTotalPrintTime
printTimeLeft = None
if totalPrintTime is not None:
# sanity check current total print time estimate
assumed_progress = cleanedPrintTime / totalPrintTime
min_progress = progress - self._timeEstimationValidityRange
max_progress = progress + self._timeEstimationValidityRange
if min_progress <= assumed_progress <= max_progress and totalPrintTime > cleanedPrintTime:
# appears sane, we'll use it
printTimeLeft = totalPrintTime - cleanedPrintTime
else:
# too far from the actual progress or negative,
# we use the dumb print time instead
printTimeLeft = dumbTotalPrintTime - cleanedPrintTime
printTimeLeftOrigin = "linear"
elif progress > self._timeEstimationForceDumbFromPercent or \
cleanedPrintTime * 60 >= self._timeEstimationForceDumbAfterMin:
# more than x% or y min printed and still no real estimate, ok, we'll use the dumb variant :/
printTimeLeft = dumbTotalPrintTime - cleanedPrintTime
printTimeLeftOrigin = "linear"
if printTimeLeft < 0:
# shouldn't actually happen, but let's make sure
return None, None
return printTimeLeft, printTimeLeftOrigin
printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None)
def _addTemperatureData(self, temp, bedTemp):
currentTimeUtc = int(time.time())
@@ -859,11 +726,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if averagePrintTime is not None:
self._selectedFile["estimatedPrintTime"] = averagePrintTime
self._selectedFile["estimatedPrintTimeType"] = "average"
elif estimatedPrintTime is not None:
# TODO apply factor which first needs to be tracked!
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
self._selectedFile["estimatedPrintTimeType"] = "analysis"
self._stateMonitor.set_job_data({
"file": {
@@ -887,8 +752,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"messages": list(self._messages)
})
callback.on_printer_send_initial_data(data)
except:
self._logger.exception("Error while trying to send inital state update")
except Exception, err:
import sys
sys.stderr.write("ERROR: %s\n" % str(err))
pass
def _getStateFlags(self):
return {
@@ -907,7 +774,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"""
Callback method for the comm object, called upon log output.
"""
self._addLog(to_unicode(message, "utf-8", errors="replace"))
self._addLog(message)
def on_comm_temperature_update(self, temp, bedTemp):
self._addTemperatureData(temp, bedTemp)
@@ -918,9 +785,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"""
oldState = self._state
if self._comm is not None:
state_string = self._comm.getStateString()
# forward relevant state changes to gcode manager
if oldState == comm.MachineCom.STATE_PRINTING:
if self._selectedFile is not None:
@@ -938,14 +802,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._setState(state, state_string=state_string)
self._setState(state)
def on_comm_message(self, message):
"""
Callback method for the comm object, called upon message exchanges via serial.
Stores the message in the message buffer, truncates buffer to the last 300 lines.
"""
self._addMessage(to_unicode(message, "utf-8", errors="replace"))
self._addMessage(message)
def on_comm_progress(self):
"""
@@ -979,7 +843,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
if self._printAfterSelect:
self._printAfterSelect = False
self.start_print(pos=self._posAfterSelect)
def on_comm_print_job_done(self):
+9 -109
View File
@@ -112,8 +112,8 @@ def load_user(id):
#~~ startup code
class Server(object):
def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False, logConf=None, octoprint_daemon=None):
class Server():
def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False, logConf=None):
self._configfile = configfile
self._basedir = basedir
self._host = host
@@ -122,7 +122,6 @@ class Server(object):
self._allowRoot = allowRoot
self._logConf = logConf
self._server = None
self._octoprint_daemon = octoprint_daemon
self._logger = None
@@ -505,11 +504,6 @@ class Server(object):
observer.join()
octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin,
"on_shutdown")
if self._octoprint_daemon is not None:
self._logger.info("Cleaning up daemon pidfile")
self._octoprint_daemon.terminated()
self._logger.info("Goodbye!")
atexit.register(on_shutdown)
@@ -648,9 +642,6 @@ class Server(object):
response.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett")
return response
from octoprint.util.jinja import MarkdownFilter
MarkdownFilter(app)
def _setup_i18n(self, app):
global babel
global LOCALES
@@ -678,56 +669,7 @@ class Server(object):
return self._get_locale()
def _setup_jinja2(self):
import re
app.jinja_env.add_extension("jinja2.ext.do")
app.jinja_env.add_extension("octoprint.util.jinja.trycatch")
def regex_replace(s, find, replace):
return re.sub(find, replace, s)
html_header_regex = re.compile("<h(?P<number>[1-6])>(?P<content>.*?)</h(?P=number)>")
def offset_html_headers(s, offset):
def repl(match):
number = int(match.group("number"))
number += offset
if number > 6:
number = 6
elif number < 1:
number = 1
return "<h{number}>{content}</h{number}>".format(number=number, content=match.group("content"))
return html_header_regex.sub(repl, s)
markdown_header_regex = re.compile("^(?P<hashs>#+)\s+(?P<content>.*)$", flags=re.MULTILINE)
def offset_markdown_headers(s, offset):
def repl(match):
number = len(match.group("hashs"))
number += offset
if number > 6:
number = 6
elif number < 1:
number = 1
return "{hashs} {content}".format(hashs="#" * number, content=match.group("content"))
return markdown_header_regex.sub(repl, s)
html_link_regex = re.compile("<(?P<tag>a.*?)>(?P<content>.*?)</a>")
def externalize_links(text):
def repl(match):
tag = match.group("tag")
if not u"href" in tag:
return match.group(0)
if not u"target=" in tag and not u"rel=" in tag:
tag += u" target=\"_blank\" rel=\"noreferrer noopener\""
content = match.group("content")
return u"<{tag}>{content}</a>".format(tag=tag, content=content)
return html_link_regex.sub(repl, text)
app.jinja_env.filters["regex_replace"] = regex_replace
app.jinja_env.filters["offset_html_headers"] = offset_html_headers
app.jinja_env.filters["offset_markdown_headers"] = offset_markdown_headers
app.jinja_env.filters["externalize_links"] = externalize_links
# configure additional template folders for jinja2
import jinja2
@@ -736,37 +678,12 @@ class Server(object):
path_filter=lambda x: not octoprint.util.is_hidden_path(x))
filesystem_loader.searchpath = self._template_searchpaths
loaders = [app.jinja_loader, filesystem_loader]
if octoprint.util.is_running_from_source():
root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
allowed = ["AUTHORS.md", "CHANGELOG.md", "SUPPORTERS.md", "THIRDPARTYLICENSES.md"]
class SourceRootFilesystemLoader(jinja2.FileSystemLoader):
def __init__(self, template_filter, prefix, *args, **kwargs):
jinja2.FileSystemLoader.__init__(self, *args, **kwargs)
self._filter = template_filter
if not prefix.endswith("/"):
prefix += "/"
self._prefix = prefix
def get_source(self, environment, template):
if not template.startswith(self._prefix):
raise jinja2.TemplateNotFound(template)
template = template[len(self._prefix):]
if not self._filter(template):
raise jinja2.TemplateNotFound(template)
return jinja2.FileSystemLoader.get_source(self, environment, template)
def list_templates(self):
templates = jinja2.FileSystemLoader.list_templates(self)
return map(lambda t: self._prefix + t, filter(self._filter, templates))
loaders.append(SourceRootFilesystemLoader(lambda t: t in allowed, "_data/", root))
jinja_loader = jinja2.ChoiceLoader(loaders)
jinja_loader = jinja2.ChoiceLoader([
app.jinja_loader,
filesystem_loader
])
app.jinja_loader = jinja_loader
del jinja2
self._register_template_plugins()
@@ -779,25 +696,10 @@ class Server(object):
preemptive_cache_timeout = settings().getInt(["server", "preemptiveCache", "until"])
cutoff_timestamp = time.time() - preemptive_cache_timeout * 24 * 60 * 60
def filter_current_entries(entry):
"""Returns True for entries younger than the cutoff date"""
def filter_old_entries(entry):
return "_timestamp" in entry and entry["_timestamp"] > cutoff_timestamp
def filter_http_entries(entry):
"""Returns True for entries targeting http or https."""
return "base_url" in entry \
and entry["base_url"] \
and (entry["base_url"].startswith("http://")
or entry["base_url"].startswith("https://"))
def filter_entries(entry):
"""Combined filter."""
filters = (filter_current_entries,
filter_http_entries)
return all([f(entry) for f in filters])
# filter out all old and non-http entries
cache_data = preemptive_cache.clean_all_data(lambda root, entries: filter(filter_entries, entries))
cache_data = preemptive_cache.clean_all_data(lambda root, entries: filter(filter_old_entries, entries))
if not cache_data:
return
@@ -809,7 +711,6 @@ class Server(object):
additional_request_data = kwargs.get("_additional_request_data", dict())
kwargs = dict((k, v) for k, v in kwargs.items() if not k.startswith("_") and not k == "plugin")
kwargs.update(additional_request_data)
try:
if plugin:
self._logger.info("Preemptively caching {} (plugin {}) for {!r}".format(route, plugin, kwargs))
@@ -821,7 +722,6 @@ class Server(object):
except:
self._logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
# asynchronous caching
import threading
cache_thread = threading.Thread(target=execute_caching, name="Preemptive Cache Worker")
cache_thread.daemon = True
+14 -17
View File
@@ -220,7 +220,7 @@ def uploadGcodeFile(target):
done = True
else:
filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target)
done = not sd
done = True
if userdata is not None:
# upload included userdata, add this now to the metadata
@@ -325,28 +325,25 @@ def gcodeFileCommand(filename, target):
except octoprint.slicing.UnknownSlicer as e:
return make_response("Slicer {slicer} is not available".format(slicer=e.slicer), 400)
if not any([octoprint.filemanager.valid_file_type(filename, type=source_file_type) for source_file_type in slicer_instance.get_slicer_properties().get("source_file_types", ["model"])]):
return make_response("Cannot slice {filename}, not a model file".format(**locals()), 415)
if not octoprint.filemanager.valid_file_type(filename, type="stl"):
return make_response("Cannot slice {filename}, not an STL file".format(**locals()), 415)
if slicer_instance.get_slicer_properties().get("same_device", True) and (printer.is_printing() or printer.is_paused()):
if slicer_instance.get_slicer_properties()["same_device"] and (printer.is_printing() or printer.is_paused()):
# slicer runs on same device as OctoPrint, slicing while printing is hence disabled
return make_response("Cannot slice on {slicer} while printing due to performance reasons".format(**locals()), 409)
if "destination" in data and data["destination"]:
destination = data["destination"]
del data["destination"]
elif "gcode" in data and data["gcode"]:
destination = data["gcode"]
if "gcode" in data and data["gcode"]:
gcode_name = data["gcode"]
del data["gcode"]
else:
import os
name, _ = os.path.splitext(filename)
destination = name + "." + slicer_instance.get_slicer_properties().get("destination_extensions", ["gco", "gcode", "g"])[0]
gcode_name = name + ".gco"
# prohibit overwriting the file that is currently being printed
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename == destination and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
make_response("Trying to slice into file that is currently being printed: %s" % destination, 409)
if currentFilename == gcode_name and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
make_response("Trying to slice into file that is currently being printed: %s" % gcode_name, 409)
if "profile" in data.keys() and data["profile"]:
profile = data["profile"]
@@ -394,24 +391,24 @@ def gcodeFileCommand(filename, target):
printer.select_file(filenameToSelect, sd, print_after_slicing)
try:
fileManager.slice(slicer, target, filename, target, destination,
fileManager.slice(slicer, target, filename, target, gcode_name,
profile=profile,
printer_profile_id=printerProfile,
position=position,
overrides=overrides,
callback=slicing_done,
callback_args=(target, destination, select_after_slicing, print_after_slicing))
callback_args=(target, gcode_name, select_after_slicing, print_after_slicing))
except octoprint.slicing.UnknownProfile:
return make_response("Profile {profile} doesn't exist".format(**locals()), 400)
files = {}
location = url_for(".readGcodeFile", target=target, filename=destination, _external=True)
location = url_for(".readGcodeFile", target=target, filename=gcode_name, _external=True)
result = {
"name": destination,
"name": gcode_name,
"origin": FileDestinations.LOCAL,
"refs": {
"resource": location,
"download": url_for("index", _external=True) + "downloads/files/" + target + "/" + destination
"download": url_for("index", _external=True) + "downloads/files/" + target + "/" + gcode_name
}
}
+2 -10
View File
@@ -43,15 +43,7 @@ def controlJob():
elif command == "pause":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
action = data.get("action", "toggle")
if action == "toggle":
printer.toggle_pause_print()
elif action == "pause":
printer.pause_print()
elif action == "resume":
printer.resume_print()
else:
return make_response("Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(action), 400)
printer.toggle_pause_print()
elif command == "cancel":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
@@ -66,4 +58,4 @@ def jobState():
"job": currentData["job"],
"progress": currentData["progress"],
"state": currentData["state"]["text"]
})
})
+1 -11
View File
@@ -64,7 +64,6 @@ def getSettings():
"waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]),
"alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]),
"sdSupport": s.getBoolean(["feature", "sdSupport"]),
"sdRelativePath": s.getBoolean(["feature", "sdRelativePath"]),
"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
@@ -91,11 +90,7 @@ def getSettings():
"helloCommand": s.get(["serial", "helloCommand"]),
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
"supportResendsWithoutOk": s.getBoolean(["serial", "supportResendsWithoutOk"]),
"maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]),
"maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]),
"maxTimeoutsLong": s.getInt(["serial", "maxCommunicationTimeouts", "long"])
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"])
},
"folder": {
"uploads": s.getBaseFolder("uploads"),
@@ -217,7 +212,6 @@ def setSettings():
if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
if "sdRelativePath" in data["feature"].keys(): s.setBoolean(["feature", "sdRelativePath"], data["feature"]["sdRelativePath"])
if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
@@ -242,10 +236,6 @@ def setSettings():
if "ignoreErrorsFromFirmware" in data["serial"]: s.setBoolean(["serial", "ignoreErrorsFromFirmware"], data["serial"]["ignoreErrorsFromFirmware"])
if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"])
if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"])
if "supportResendsWithoutOk" in data["serial"]: s.setBoolean(["serial", "supportResendsWithoutOk"], data["serial"]["supportResendsWithoutOk"])
if "maxTimeoutsIdle" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "idle"], data["serial"]["maxTimeoutsIdle"])
if "maxTimeoutsPrinting" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "printing"], data["serial"]["maxTimeoutsPrinting"])
if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"])
oldLog = s.getBoolean(["serial", "log"])
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
+3 -16
View File
@@ -14,13 +14,11 @@ from octoprint.server.api import api, NO_CONTENT
from octoprint.settings import settings as s, valid_boolean_trues
from octoprint.slicing import UnknownSlicer, SlicerNotConfigured, ProfileAlreadyExists, UnknownProfile, CouldNotDeleteProfile
from octoprint.slicing import UnknownSlicer, SlicerNotConfigured, ProfileAlreadyExists, UnknownProfile
@api.route("/slicing", methods=["GET"])
def slicingListAll():
from octoprint.filemanager import get_extensions
default_slicer = s().get(["slicing", "defaultSlicer"])
if "configured" in request.values and request.values["configured"] in valid_boolean_trues:
@@ -32,21 +30,12 @@ def slicingListAll():
for slicer in slicers:
try:
slicer_impl = slicingManager.get_slicer(slicer, require_configured=False)
extensions = set()
for source_file_type in slicer_impl.get_slicer_properties().get("source_file_types", ["model"]):
extensions = extensions.union(get_extensions(source_file_type))
result[slicer] = dict(
key=slicer,
displayName=slicer_impl.get_slicer_properties()["name"],
default=default_slicer == slicer,
configured=slicer_impl.is_slicer_configured(),
profiles=_getSlicingProfilesData(slicer),
extensions=dict(
source=list(extensions),
destination=slicer_impl.get_slicer_properties().get("destination_extensions", ["gco", "gcode", "g"])
)
configured = slicer_impl.is_slicer_configured(),
profiles=_getSlicingProfilesData(slicer)
)
except (UnknownSlicer, SlicerNotConfigured):
# this should never happen
@@ -158,8 +147,6 @@ def slicingDelSlicerProfile(slicer, name):
slicingManager.delete_profile(slicer, name)
except UnknownSlicer:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
except CouldNotDeleteProfile as e:
return make_response("Could not delete profile {profile} for slicer {slicer}: {cause}".format(profile=name, slicer=slicer, cause=str(e.cause)), 500)
return NO_CONTENT
+1 -1
View File
@@ -62,7 +62,7 @@ def downloadTimelapse(filename):
@api.route("/timelapse/<filename>", methods=["DELETE"])
@restricted_access
def deleteTimelapse(filename):
if util.is_allowed_file(filename, ["mpg", "mpeg", "mp4"]):
if util.is_allowed_file(filename, ["mpg"]):
timelapse_folder = settings().getBaseFolder("timelapse")
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
if full_path.startswith(timelapse_folder) and os.path.exists(full_path):
-5
View File
@@ -225,11 +225,6 @@ class ReverseProxied(object):
# determine scheme
scheme = environ.get(self._header_scheme, "")
if scheme and "," in scheme:
# Scheme might be something like "https,https" if doubly-reverse-proxied
# without stripping original scheme header first, make sure to only use
# the first entry in such a case. See #1391.
scheme, _ = map(lambda x: x.strip(), scheme.split(",", 1))
if not scheme:
scheme = self._fallback_scheme
+5 -10
View File
@@ -420,7 +420,7 @@ class PreemptiveCache(object):
self._logger.debug("Removed root {} from preemptive cache".format(root))
elif len(entries) < old_count:
all_data[root] = entries
self._logger.debug("Removed {} entries from preemptive cache for root {}".format(old_count - len(entries), root))
self._logger.debug("Removed {} from preemptive cache for root {}".format(old_count - len(entries), root))
self.set_all_data(all_data)
return all_data
@@ -488,12 +488,6 @@ class PreemptiveCache(object):
return matched, unmatched
with self._lock:
if not self._log_access:
self._logger.debug(
"Not updating timestamp and counter for {} and {!r}, currently flagged as disabled".format(root,
data))
return
cache_data = self.get_all_data()
if not root in cache_data:
@@ -515,10 +509,12 @@ class PreemptiveCache(object):
to_persist["_timestamp"] = time.time()
to_persist["_count"] = 1
self._logger.info("Adding entry for {} and {!r}".format(root, to_persist))
else:
elif self._log_access:
to_persist["_timestamp"] = time.time()
to_persist["_count"] = to_persist.get("_count", 0) + 1
self._logger.debug("Updating timestamp and counter for {} and {!r}".format(root, data))
else:
self._logger.debug("Not updating timestamp and counter for {} and {!r}, currently flagged as disabled".format(root, data))
self.set_data(root, [to_persist] + other)
@@ -911,8 +907,7 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
'js/app/viewmodels/timelapse.js',
'js/app/viewmodels/users.js',
'js/app/viewmodels/log.js',
'js/app/viewmodels/usersettings.js',
'js/app/viewmodels/about.js'
'js/app/viewmodels/usersettings.js'
]
if enable_gcodeviewer:
assets["js"] += [
+4 -10
View File
@@ -12,9 +12,6 @@ import time
import octoprint.timelapse
import octoprint.server
import octoprint.events
import octoprint.plugin
from octoprint.events import Events
import octoprint.printer
@@ -46,8 +43,6 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
self._lastCurrent = 0
self._baseRateLimit = 0.5
self._emit_mutex = threading.RLock()
def _getRemoteAddress(self, info):
forwardedFor = info.headers.get("X-Forwarded-For")
if forwardedFor is not None:
@@ -199,8 +194,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
self.sendEvent(event, payload)
def _emit(self, type, payload):
with self._emit_mutex:
try:
self.send({type: payload})
except Exception as e:
self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, str(e)))
try:
self.send({type: payload})
except Exception as e:
self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, str(e)))
+2 -18
View File
@@ -6,7 +6,6 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
import datetime
from collections import defaultdict
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect
@@ -32,7 +31,7 @@ _valid_div_re = re.compile("[a-zA-Z_-]+")
@app.route("/")
@util.flask.preemptively_cached(cache=preemptiveCache,
data=lambda: dict(path=request.path, base_url=request.url_root, query_string="l10n={}".format(g.locale.language) if g.locale else "en"),
unless=lambda: request.url_root in settings().get(["server", "preemptiveCache", "exceptions"]) or not (request.url_root.startswith("http://") or request.url_root.startswith("https://")))
unless=lambda: request.url_root in settings().get(["server", "preemptiveCache", "exceptions"]))
@util.flask.conditional(lambda: _check_etag_and_lastmodified_for_index(), NOT_MODIFIED)
@util.flask.cached(timeout=-1,
refreshif=lambda cached: _validate_cache_for_index(cached),
@@ -61,7 +60,6 @@ def index():
tab=dict(div=lambda x: "tab_plugin_" + x, template=lambda x: x + "_tab.jinja2", to_entry=lambda data: (data["name"], data)),
settings=dict(div=lambda x: "settings_plugin_" + x, template=lambda x: x + "_settings.jinja2", to_entry=lambda data: (data["name"], data)),
usersettings=dict(div=lambda x: "usersettings_plugin_" + x, template=lambda x: x + "_usersettings.jinja2", to_entry=lambda data: (data["name"], data)),
about=dict(div=lambda x: "about_plugin_" + x, template=lambda x: x + "_about.jinja2", to_entry=lambda data: (data["name"], data)),
generic=dict(template=lambda x: x + ".jinja2", to_entry=lambda data: data)
)
@@ -72,7 +70,6 @@ def index():
tab=dict(add="append", key="name"),
settings=dict(add="custom_append", key="name", custom_add_entries=lambda missing: dict(section_plugins=(gettext("Plugins"), None)), custom_add_order=lambda missing: ["section_plugins"] + missing),
usersettings=dict(add="append", key="name"),
about=dict(add="append", key="name"),
generic=dict(add="append", key=None)
)
@@ -128,7 +125,7 @@ def index():
# sidebar
templates["sidebar"]["entries"]= dict(
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.isUser")),
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.isAdmin")),
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-sign")),
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2"))
)
@@ -180,17 +177,6 @@ def index():
interface=(gettext("Interface"), dict(template="dialogs/usersettings/interface.jinja2", _div="usersettings_interface", custom_bindings=False)),
)
# about dialog
templates["about"]["entries"] = dict(
about=("About OctoPrint", dict(template="dialogs/about/about.jinja2", _div="about_about", custom_bindings=False)),
license=("OctoPrint License", dict(template="dialogs/about/license.jinja2", _div="about_license", custom_bindings=False)),
thirdparty=("Third Party Licenses", dict(template="dialogs/about/thirdparty.jinja2", _div="about_thirdparty", custom_bindings=False)),
authors=("Authors", dict(template="dialogs/about/authors.jinja2", _div="about_authors", custom_bindings=False)),
changelog=("Changelog", dict(template="dialogs/about/changelog.jinja2", _div="about_changelog", custom_bindings=False)),
supporters=("Supporters", dict(template="dialogs/about/supporters.jinja2", _div="about_sponsors", custom_bindings=False))
)
# extract data from template plugins
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
@@ -296,7 +282,6 @@ def index():
#~~ prepare full set of template vars for rendering
now = datetime.datetime.utcnow()
first_run = settings().getBoolean(["server", "firstRun"]) and userManager.enabled and not userManager.hasBeenCustomized()
render_kwargs = dict(
webcamStream=settings().get(["webcam", "stream"]),
@@ -314,7 +299,6 @@ def index():
templates=templates,
pluginNames=plugin_names,
locales=locales,
now=now,
supportedExtensions=map(lambda ext: ".{}".format(ext), get_all_extensions())
)
render_kwargs.update(plugin_vars)
+3 -23
View File
@@ -81,24 +81,16 @@ default_settings = {
"detection": 0.5,
"connection": 10,
"communication": 30,
"heatup": 2,
"temperature": 5,
"sdStatus": 1
},
"maxCommunicationTimeouts": {
"idle": 2,
"printing": 5,
"long": 5
},
"maxWritePasses": 5,
"additionalPorts": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226"],
"checksumRequiringCommands": ["M110"],
"helloCommand": "M110 N0",
"disconnectOnErrors": True,
"ignoreErrorsFromFirmware": False,
"logResends": True,
"supportResendsWithoutOk": False,
"logResends": False,
# command specific flags
"triggerOkForM29": True
@@ -169,7 +161,6 @@ default_settings = {
"sendChecksumWithUnknownCommands": False,
"unknownCommandsNeedAck": False,
"sdSupport": True,
"sdRelativePath": False,
"sdAlwaysAvailable": False,
"swallowOkAfterResend": True,
"repetierTargetTemp": False,
@@ -217,16 +208,15 @@ default_settings = {
"defaultLanguage": "_default",
"components": {
"order": {
"navbar": ["settings", "systemmenu", "login", "plugin_announcements"],
"navbar": ["settings", "systemmenu", "login"],
"sidebar": ["connection", "state", "files"],
"tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"],
"settings": [
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
"section_features", "features", "webcam", "accesscontrol", "api",
"section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate", "plugin_announcements"
"section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
],
"usersettings": ["access", "interface"],
"about": ["about", "supporters", "authors", "changelog", "license", "thirdparty", "plugin_pluginmanager"],
"generic": []
},
"disabled": {
@@ -283,15 +273,6 @@ default_settings = {
}
}
},
"estimation": {
"printTime": {
"statsWeighingUntil": 0.5,
"validityRange": 0.15,
"forceDumbFromPercent": 0.3,
"forceDumbAfterMin": 30,
"stableThreshold": 60
}
},
"devel": {
"stylesheet": "css",
"cache": {
@@ -310,7 +291,6 @@ default_settings = {
"okWithLinenumber": False,
"numExtruders": 1,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
"movementSpeed": {
"x": 6000,
"y": 6000,
+4 -23
View File
@@ -407,18 +407,7 @@ class SlicingManager(object):
profile.description = description
path = self.get_profile_path(slicer, name)
is_overwrite = os.path.exists(path)
if is_overwrite and not allow_overwrite:
raise ProfileAlreadyExists(slicer, profile.name)
self._save_profile_to_path(slicer, path, profile, overrides=overrides, allow_overwrite=allow_overwrite)
payload = dict(slicer=slicer,
profile=name)
event = octoprint.events.Events.SLICING_PROFILE_MODIFIED if is_overwrite else octoprint.events.Events.SLICING_PROFILE_ADDED
octoprint.events.eventManager().fire(event, payload)
return profile
def _temporary_profile(self, slicer, name=None, overrides=None):
@@ -447,7 +436,6 @@ class SlicingManager(object):
Raises:
~octoprint.slicing.exceptions.UnknownSlicer: The slicer ``slicer`` is unknown.
~octoprint.slicing.exceptions.CouldNotDeleteProfile: There was an error while deleting the profile.
"""
if not slicer in self.registered_slicers:
@@ -457,17 +445,10 @@ class SlicingManager(object):
raise ValueError("name must be set")
try:
try:
path = self.get_profile_path(slicer, name, must_exist=True)
except UnknownProfile:
return
os.remove(path)
except ProfileException as e:
raise e
except Exception as e:
raise CouldNotDeleteProfile(slicer, name, cause=e)
else:
octoprint.events.eventManager().fire(octoprint.events.Events.SLICING_PROFILE_DELETED, dict(slicer=slicer, profile=name))
path = self.get_profile_path(slicer, name, must_exist=True)
except UnknownProfile:
return
os.remove(path)
def all_profiles(self, slicer, require_configured=False):
"""
-13
View File
@@ -105,16 +105,3 @@ class ProfileAlreadyExists(ProfileException):
def __init__(self, slicer, profile, *args, **kwargs):
ProfileException.__init__(self, slicer, profile, *args, **kwargs)
self.message = "Profile {profile} for slicer {slicer} already exists".format(profile=profile, slicer=slicer)
class CouldNotDeleteProfile(ProfileException):
"""
Raised if there is an unexpected error trying to delete a known profile.
"""
def __init__(self, slicer, profile, cause=None, *args, **kwargs):
ProfileException.__init__(self, slicer, profile, *args, **kwargs)
self.cause = cause
if cause:
self.message = "Could not delete profile {profile} for slicer {slicer}: {cause}".format(profile=profile, slicer=slicer, cause=str(cause))
else:
self.message = "Could not delete profile {profile} for slicer {slicer}".format(profile=profile, slicer=slicer)
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
+6 -13
View File
@@ -104,11 +104,8 @@ GCODE.ui = (function(){
if(!Modernizr.webworkers)fatal.push("<li>Your browser doesn't seem to support HTML5 Web Workers, this application won't work without it.</li>");
if(!Modernizr.svg)fatal.push("<li>Your browser doesn't seem to support HTML5 SVG, this application won't work without it.</li>");
var errorList = document.getElementById("errorList");
if(fatal.length>0){
if (errorList) {
errorList.innerHTML = '<ul>' + fatal.join('') + '</ul>';
}
document.getElementById('errorList').innerHTML = '<ul>' + fatal.join('') + '</ul>';
console.log("Initialization failed: unsupported browser.")
return false;
}
@@ -120,10 +117,8 @@ GCODE.ui = (function(){
if(!Modernizr.draganddrop)warnings.push("<li>Your browser doesn't seem to support HTML5 Drag'n'Drop, Drop area will not work.</li>");
if(warnings.length>0){
if (errorList) {
errorList.innerHTML = '<ul>' + warnings.join('') + '</ul>';
}
console.log("Initialization succeeded with warnings.", warnings);
document.getElementById('errorList').innerHTML = '<ul>' + wanings.join('') + '</ul>';
console.log("Initialization succeeded with warnings.")
}
return true;
};
@@ -143,12 +138,12 @@ GCODE.ui = (function(){
init: function(options){
if (options) setOptions(options);
if (!options.container) {
return false;
return;
}
var capabilitiesResult = checkCapabilities();
if (!capabilitiesResult) {
return false;
return;
}
setProgress("", 0);
@@ -164,8 +159,6 @@ GCODE.ui = (function(){
toolOffsets: options.toolOffsets
});
GCODE.renderer.render(0, 0);
return true;
},
clear: function() {
@@ -203,4 +196,4 @@ GCODE.ui = (function(){
switchCommands(layerNum, first, last);
}
}
}());
}());
+3 -17
View File
@@ -136,17 +136,9 @@
var timeout = 1500;
var baseUrl = window.location.href;
var currentQuery = "";
var currentFragment = "";
if (baseUrl.indexOf("#") > -1) {
currentFragment = baseUrl.substring(baseUrl.indexOf("#"));
baseUrl = baseUrl.substring(0, baseUrl.indexOf("#"));
}
if (baseUrl.indexOf("?") > -1) {
currentQuery = baseUrl.substring(baseUrl.indexOf("?"));
baseUrl = baseUrl.substring(0, baseUrl.indexOf("?"));
}
if (baseUrl.indexOf("/static") > -1) {
baseUrl = baseUrl.substring(0, baseUrl.indexOf("/static"));
}
@@ -167,16 +159,10 @@
serverIsOnline = true;
message.className = "pulsate1 green";
message.innerText = "OctoPrint server online, reloading page...";
var reloadUrl = baseUrl + currentQuery + currentFragment;
if (reloadUrl == window.location.href) {
window.location.reload(false);
} else {
window.location.href = reloadUrl;
}
window.location = baseUrl;
} else {
// online.gif still not available, let's look at
var interval = 10;
var interval = 15;
if (intervals.length) {
interval = intervals.shift();
}
@@ -200,7 +186,7 @@
}
backendOfflineCounter++;
if (backendOfflineCounter > 15) {
if (backendOfflineCounter > 10) {
if (serverTimeout) {
window.clearTimeout(serverTimeout);
}
+135 -13
View File
@@ -16,16 +16,14 @@ function DataUpdater(allViewModels) {
self._lastProcessingTimes = [];
self._lastProcessingTimesSize = 20;
self._connectCallback = undefined;
self._timelapse_popup = undefined;
self.connect = function(callback) {
self.connect = function() {
var options = {};
if (SOCKJS_DEBUG) {
options["debug"] = true;
}
self._connectCallback = callback;
self._socket = new SockJS(SOCKJS_URI, undefined, options);
self._socket.onopen = self._onconnect;
self._socket.onclose = self._onclose;
@@ -140,6 +138,9 @@ function DataUpdater(allViewModels) {
var data = e.data[prop];
var gcodeUploadProgress = $("#gcode_upload_progress");
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
var start = new Date().getTime();
switch (prop) {
case "connected": {
@@ -185,13 +186,6 @@ function DataUpdater(allViewModels) {
self.setThrottle(1);
log.info("Connected to the server");
if (self._connectCallback) {
self._connectCallback();
self._connectCallback = undefined;
}
break;
}
case "history": {
@@ -211,6 +205,8 @@ function DataUpdater(allViewModels) {
break;
}
case "slicingProgress": {
gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(data["progress"])}));
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onSlicingProgress")) {
viewModel.onSlicingProgress(data["slicer"], data["model_path"], data["machinecode_path"], data["progress"]);
@@ -221,10 +217,134 @@ function DataUpdater(allViewModels) {
case "event": {
var type = data["type"];
var payload = data["payload"];
var html = "";
var format = {};
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
if (type == "PrintCancelled") {
if (type == "MovieRendering") {
if (self._timelapse_popup !== undefined) {
self._timelapse_popup.remove();
}
self._timelapse_popup = new PNotify({
title: gettext("Rendering timelapse"),
text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s. Due to performance reasons it is not recommended to start a print job while a movie is still rendering."), payload),
hide: false,
callbacks: {
before_close: function() {
self._timelapse_popup = undefined;
}
}
});
} else if (type == "MovieDone") {
if (self._timelapse_popup !== undefined) {
self._timelapse_popup.remove();
}
self._timelapse_popup = new PNotify({
title: gettext("Timelapse ready"),
text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload),
type: "success",
callbacks: {
before_close: function(notice) {
if (self._timelapse_popup == notice) {
self._timelapse_popup = undefined;
}
}
}
});
} else if (type == "MovieFailed") {
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>');
if (self._timelapse_popup !== undefined) {
self._timelapse_popup.remove();
}
self._timelapse_popup = new PNotify({
title: gettext("Rendering failed"),
text: html,
type: "error",
hide: false,
callbacks: {
before_close: function(notice) {
if (self._timelapse_popup == notice) {
self._timelapse_popup = undefined;
}
}
}
});
} 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 {
format = {
time: moment().add(payload.postroll_duration, "s").format("LT")
};
if (payload.postroll_duration > 60) {
format.duration = _.sprintf(gettext("%(minutes)d min"), {minutes: payload.postroll_duration / 60});
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s (so until %(time)s)..."), format);
} 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);
}
}
if (self._timelapse_popup !== undefined) {
self._timelapse_popup.remove();
}
self._timelapse_popup = new PNotify({
title: title,
text: text,
hide: false,
callbacks: {
before_close: function(notice) {
if (self._timelapse_popup == notice) {
self._timelapse_popup = undefined;
}
}
}
});
} else if (type == "SlicingStarted") {
gcodeUploadProgress.addClass("progress-striped").addClass("active");
gcodeUploadProgressBar.css("width", "100%");
if (payload.progressAvailable) {
gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0}));
} else {
gcodeUploadProgressBar.text(gettext("Slicing ..."));
}
} else if (type == "SlicingDone") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload), type: "success"});
} else if (type == "SlicingCancelled") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
} else if (type == "SlicingFailed") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload);
new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false});
} else if (type == "TransferStarted") {
gcodeUploadProgress.addClass("progress-striped").addClass("active");
gcodeUploadProgressBar.css("width", "100%");
gcodeUploadProgressBar.text(gettext("Streaming ..."));
} else if (type == "TransferDone") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
new PNotify({
title: gettext("Streaming done"),
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
type: "success"
});
} else if (type == "PrintCancelled") {
if (payload.firmwareError) {
new PNotify({
title: gettext("Unhandled communication error"),
@@ -236,7 +356,7 @@ function DataUpdater(allViewModels) {
} else if (type == "Error") {
new PNotify({
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
type: "error",
hide: false
});
@@ -302,4 +422,6 @@ function DataUpdater(allViewModels) {
}
}
};
self.connect();
}
+16 -63
View File
@@ -56,12 +56,12 @@ $(function() {
// register for browser visibility tracking
var prop = getHiddenProp();
if (prop) {
var eventName = prop.replace(/[H|h]idden/, "") + "visibilitychange";
document.addEventListener(eventName, updateBrowserVisibility);
if (!prop) return undefined;
updateBrowserVisibility();
}
var eventName = prop.replace(/[H|h]idden/, "") + "visibilitychange";
document.addEventListener(eventName, updateBrowserVisibility);
updateBrowserVisibility();
// exports
@@ -276,6 +276,8 @@ $(function() {
}
log.info("... dependency resolution done");
var dataUpdater = new DataUpdater(allViewModels);
//~~ Custom knockout.js bindings
ko.bindingHandlers.popover = {
@@ -348,44 +350,6 @@ $(function() {
}
};
ko.bindingHandlers.copyWidth = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var node = ko.bindingHandlers.copyWidth._getReferenceNode(element, valueAccessor);
ko.bindingHandlers.copyWidth._setWidth(node, element);
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var node = ko.bindingHandlers.copyWidth._getReferenceNode(element, valueAccessor);
ko.bindingHandlers.copyWidth._setWidth(node, element);
},
_setWidth: function(node, element) {
var width = node.width();
if (!width) return;
if ($(element).width() == width) return;
element.style.width = width + "px";
},
_getReferenceNode: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (!value) return;
var parts = value.split(" ");
var node = $(element);
while (parts.length > 0) {
var part = parts.shift();
if (part == ":parent") {
node = node.parent();
} else {
var selector = part;
if (parts.length > 0) {
selector += " " + parts.join(" ");
}
node = $(selector, node);
break;
}
}
return node;
}
};
ko.bindingHandlers.contextMenu = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var val = ko.utils.unwrapObservable(valueAccessor());
@@ -553,6 +517,14 @@ $(function() {
// reload overlay
$("#reloadui_overlay_reload").click(function() { location.reload(); });
//~~ Starting up the app
_.each(allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onStartup")) {
viewModel.onStartup();
}
});
//~~ view model binding
var bindViewModels = function() {
@@ -642,31 +614,12 @@ $(function() {
}
});
});
log.info("Application startup complete");
};
if (!_.has(viewModelMap, "settingsViewModel")) {
throw new Error("settingsViewModel is missing, can't run UI")
}
var dataUpdaterConnectCallback = function() {
log.info("Finalizing application startup");
//~~ Starting up the app
_.each(allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onStartup")) {
viewModel.onStartup();
}
});
viewModelMap["settingsViewModel"].requestData(bindViewModels);
};
log.info("Initial application setup done, connecting to server...");
var dataUpdater = new DataUpdater(allViewModels);
dataUpdater.connect(dataUpdaterConnectCallback);
viewModelMap["settingsViewModel"].requestData(bindViewModels);
}
);
@@ -1,45 +0,0 @@
$(function() {
function AboutViewModel(parameters) {
var self = this;
self.aboutDialog = undefined;
self.aboutContent = undefined;
self.aboutTabs = undefined;
self.show = function() {
$("a:first", self.aboutTabs).tab("show");
self.aboutContent.scrollTop(0);
self.aboutDialog.modal({
minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
}).css({
width: 'auto',
'margin-left': function() { return -($(this).width() /2); }
});
return false;
};
self.hide = function() {
self.aboutDialog.modal("hide");
};
self.onStartup = function() {
self.aboutDialog = $("#about_dialog");
self.aboutTabs = $("#about_dialog_tabs");
self.aboutContent = $("#about_dialog_content");
$('a[data-toggle="tab"]', self.aboutTabs).on("show", function() {
self.aboutContent.scrollTop(0);
});
};
self.showTab = function(tab) {
$("a[href=#" + tab + "]", self.aboutTabs).tab("show");
};
}
OCTOPRINT_VIEWMODELS.push([
AboutViewModel,
[],
["#about_dialog", "#footer_about"]
]);
});
@@ -93,7 +93,7 @@ $(function() {
} else if (!self.isOperational() && !connectionTab.hasClass("in")) {
connectionTab.collapse("show");
}
};
}
self._processStateData = function(data) {
self.previousIsOperational = self.isOperational();
@@ -106,7 +106,7 @@ $(function() {
self.isReady(data.flags.ready);
self.isLoading(data.flags.loading);
if (self.loginState.isUser() && self.previousIsOperational != self.isOperational()) {
if (self.loginState.isAdmin() && self.previousIsOperational != self.isOperational()) {
// only open or close if the panel is visible (for admins) and
// the state just changed to avoid thwarting manual open/close
self.openOrCloseOnStateChange();
@@ -26,9 +26,6 @@ $(function() {
self.extrusionAmount = ko.observable(undefined);
self.controls = ko.observableArray([]);
self.distances = ko.observableArray([0.1, 1, 10, 100]);
self.distance = ko.observable(10);
self.tools = ko.observableArray([]);
self.feedRate = ko.observable(100);
@@ -252,7 +249,7 @@ $(function() {
self.sendJogCommand = function (axis, multiplier, distance) {
if (typeof distance === "undefined")
distance = self.distance();
distance = $('#jog_distance button.active').data('distance');
if (self.settings.printerProfiles.currentProfileData() && self.settings.printerProfiles.currentProfileData()["axes"] && self.settings.printerProfiles.currentProfileData()["axes"][axis] && self.settings.printerProfiles.currentProfileData()["axes"][axis]["inverted"]()) {
multiplier *= -1;
}
@@ -587,10 +584,6 @@ $(function() {
}
};
self.stripDistanceDecimal = function(distance) {
return distance.toString().replace(".", "");
};
}
OCTOPRINT_VIEWMODELS.push([
+39 -152
View File
@@ -58,10 +58,6 @@ $(function() {
self.localTarget = undefined;
self.sdTarget = undefined;
self.uploadProgressText = ko.observable();
self._uploadInProgress = false;
// initialize list helper
self.listHelper = new ItemListHelper(
"gcodeFiles",
@@ -149,26 +145,22 @@ $(function() {
self.isSdReady(data.flags.sdReady);
};
self._otherRequestInProgress = undefined;
self._filenameToFocus = undefined;
self._locationToFocus = undefined;
self._otherRequestInProgress = false;
self.requestData = function(filenameToFocus, locationToFocus) {
self._filenameToFocus = self._filenameToFocus || filenameToFocus;
self._locationToFocus = self._locationToFocus || locationToFocus;
if (self._otherRequestInProgress !== undefined) {
return self._otherRequestInProgress
}
if (self._otherRequestInProgress) return;
return self._otherRequestInProgress = $.ajax({
self._otherRequestInProgress = true;
$.ajax({
url: API_BASEURL + "files",
method: "GET",
dataType: "json"
}).done(function(response) {
self.fromResponse(response, self._filenameToFocus, self._locationToFocus);
}).always(function() {
self._otherRequestInProgress = undefined;
self._filenameToFocus = undefined;
self._locationToFocus = undefined;
dataType: "json",
success: function(response) {
self.fromResponse(response, filenameToFocus, locationToFocus);
self._otherRequestInProgress = false;
},
error: function() {
self._otherRequestInProgress = false;
}
});
};
@@ -187,19 +179,8 @@ $(function() {
}
var entryElement = self.getEntryElement({name: filenameToFocus, origin: locationToFocus});
if (entryElement) {
// scroll to uploaded element
var entryOffset = entryElement.offsetTop;
$(".gcode_files").slimScroll({
scrollTo: entryOffset + "px"
});
// highlight uploaded element
var element = $(entryElement);
element.on("webkitAnimationEnd oanimationend msAnimationEnd animationend", function(e) {
// remove highlight class again
element.removeClass("highlight");
});
element.addClass("highlight");
$(".gcode_files").slimScroll({ scrollTo: entryOffset + "px" });
}
}
@@ -317,7 +298,7 @@ $(function() {
};
self.enableSlicing = function(data) {
return self.loginState.isUser() && self.slicing.enableSlicingDialog() && self.slicing.enableSlicingDialogForFile(data.name);
return self.loginState.isUser() && self.slicing.enableSlicingDialog();
};
self.enableAdditionalData = function(data) {
@@ -415,7 +396,6 @@ $(function() {
self.localTarget = $("#drop_locally");
} else {
self.localTarget = $("#drop");
self.listHelper.removeFilter('sd');
}
self.sdTarget = $("#drop_sd");
@@ -440,71 +420,15 @@ $(function() {
};
self.onEventUpdatedFiles = function(payload) {
if (self._uploadInProgress) {
return;
if (payload.type == "gcode") {
self.requestData();
}
if (payload.type !== "gcode") {
return;
}
self.requestData();
};
self.onEventSlicingStarted = function(payload) {
self.uploadProgress
.addClass("progress-striped")
.addClass("active");
self.uploadProgressBar.css("width", "100%");
if (payload.progressAvailable) {
self.uploadProgressText(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0}));
} else {
self.uploadProgressText(gettext("Slicing ..."));
}
};
self.onSlicingProgress = function(slicer, modelPath, machinecodePath, progress) {
self.uploadProgressText(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(progress)}));
};
self.onEventSlicingCancelled = function(payload) {
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
self.uploadProgressBar
.css("width", "0%");
self.uploadProgressText("");
};
self.onEventSlicingDone = function(payload) {
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
self.uploadProgressBar
.css("width", "0%");
self.uploadProgressText("");
new PNotify({
title: gettext("Slicing done"),
text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload),
type: "success"
});
self.requestData();
};
self.onEventSlicingFailed = function(payload) {
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
self.uploadProgressBar
.css("width", "0%");
self.uploadProgressText("");
var html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload);
new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false});
};
self.onEventMetadataAnalysisFinished = function(payload) {
self.requestData();
};
@@ -513,33 +437,16 @@ $(function() {
self.requestData();
};
self.onEventTransferStarted = function(payload) {
self.uploadProgress
.addClass("progress-striped")
.addClass("active");
self.uploadProgressBar
.css("width", "100%");
self.uploadProgressText(gettext("Streaming ..."));
};
self.onEventTransferDone = function(payload) {
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
self.uploadProgressBar
.css("width", "0");
self.uploadProgressText("");
new PNotify({
title: gettext("Streaming done"),
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
type: "success"
});
self.requestData(payload.remote, "sdcard");
};
self.onServerConnect = self.onServerReconnect = function(payload) {
self.onServerConnect = function(payload) {
self._enableDragNDrop(true);
self.requestData();
};
self.onServerReconnect = function(payload) {
self._enableDragNDrop(true);
self.requestData();
};
@@ -553,10 +460,8 @@ $(function() {
url: API_BASEURL + "files/local",
dataType: "json",
dropZone: enable ? self.localTarget : null,
submit: self._handleUploadStart,
done: self._handleUploadDone,
fail: self._handleUploadFail,
always: self._handleUploadAlways,
progressall: self._handleUploadProgress
};
self.uploadButton.fileupload(options);
@@ -567,10 +472,8 @@ $(function() {
url: API_BASEURL + "files/sdcard",
dataType: "json",
dropZone: enable ? self.sdTarget : null,
submit: self._handleUploadStart,
done: self._handleUploadDone,
fail: self._handleUploadFail,
always: self._handleUploadAlways,
progressall: self._handleUploadProgress
};
self.sdUploadButton.fileupload(options);
@@ -586,11 +489,6 @@ $(function() {
}
};
self._handleUploadStart = function(e, data) {
self._uploadInProgress = true;
return true;
};
self._handleUploadDone = function(e, data) {
var filename = undefined;
var location = undefined;
@@ -601,32 +499,24 @@ $(function() {
filename = data.result.files.local.name;
location = "local";
}
self.requestData(filename, location)
.done(function() {
if (data.result.done) {
self.uploadProgressBar
.css("width", "0%");
self.uploadProgressText("");
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
}
});
self.requestData(filename, location);
if (_.endsWith(filename.toLowerCase(), ".stl")) {
self.slicing.show(location, filename);
}
if (data.result.done) {
self.uploadProgressBar
.css("width", "0%")
.text("");
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
}
};
self._handleUploadFail = function(e, data) {
var extensions = _.map(SUPPORTED_EXTENSIONS, function(extension) {
return extension.toLowerCase();
}).sort();
extensions = extensions.join(", ");
var error = "<p>"
+ _.sprintf(gettext("Could not upload the file. Make sure that it is a valid file with one of these extensions: %(extensions)s"),
{extensions: extensions})
+ "</p>";
var error = "<p>" + gettext("Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\".") + "</p>";
error += pnotifyAdditionalInfo("<pre>" + data.jqXHR.responseText + "</pre>");
new PNotify({
title: "Upload failed",
@@ -635,29 +525,26 @@ $(function() {
hide: false
});
self.uploadProgressBar
.css("width", "0%");
self.uploadProgressText("");
.css("width", "0%")
.text("");
self.uploadProgress
.removeClass("progress-striped")
.removeClass("active");
};
self._handleUploadAlways = function(e, data) {
self._uploadInProgress = false;
};
self._handleUploadProgress = function(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
self.uploadProgressBar
.css("width", progress + "%");
self.uploadProgressText(gettext("Uploading ..."));
.css("width", progress + "%")
.text(gettext("Uploading ..."));
if (progress >= 100) {
self.uploadProgress
.addClass("progress-striped")
.addClass("active");
self.uploadProgressText(gettext("Saving ..."));
self.uploadProgressBar
.text(gettext("Saving ..."));
}
};
@@ -235,7 +235,7 @@ $(function() {
self._configureLayerCommandSlider(commandSliderElement);
self.settings.requestData(function() {
var initResult = GCODE.ui.init({
GCODE.ui.init({
container: "#gcode_canvas",
onProgress: self._onProgress,
onModelLoaded: self._onModelLoaded,
@@ -244,12 +244,6 @@ $(function() {
toolOffsets: self._retrieveToolOffsets(),
invertAxes: self._retrieveAxesConfiguration()
});
if (!initResult) {
log.info("Could not initialize GCODE viewer component");
return;
}
self.synchronizeOptions();
self.enabled = true;
});
@@ -435,7 +429,7 @@ $(function() {
} else {
var output = [];
output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm &times; " + model.depth.toFixed(2) + "mm &times; " + model.height.toFixed(2) + "mm");
output.push(gettext("Estimated total print time") + ": " + formatFuzzyEstimation(model.printTime));
output.push(gettext("Estimated total print time") + ": " + formatDuration(model.printTime));
output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
@@ -472,7 +466,7 @@ $(function() {
}
}
}
output.push(gettext("Print time for layer") + ": " + formatFuzzyEstimation(layer.printTime));
output.push(gettext("Print time for layer") + ": " + formatDuration(layer.printTime));
self.ui_layerInfo(output.join("<br>"));
@@ -104,11 +104,6 @@ $(function() {
success: function(response) {
new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"});
self.fromResponse(response);
},
error: function(error) {
if (error && error.status === 401) {
self.fromResponse(false);
}
}
})
};
@@ -129,8 +124,11 @@ $(function() {
self.allViewModels = allViewModels;
};
self.onStartupComplete = self.onServerConnect = self.onServerReconnect = function() {
if (self.allViewModels == undefined) return;
self.onDataUpdaterReconnect = function() {
self.requestData();
};
self.onStartupComplete = function() {
self.requestData();
};
}
@@ -30,7 +30,6 @@ $(function() {
self.filepos = ko.observable(undefined);
self.printTime = ko.observable(undefined);
self.printTimeLeft = ko.observable(undefined);
self.printTimeLeftOrigin = ko.observable(undefined);
self.sd = ko.observable(undefined);
self.timelapse = ko.observable(undefined);
@@ -52,9 +51,9 @@ $(function() {
self.estimatedPrintTimeString = ko.pureComputed(function() {
if (self.lastPrintTime())
return formatFuzzyEstimation(self.lastPrintTime());
return formatDuration(self.lastPrintTime());
if (self.estimatedPrintTime())
return formatFuzzyEstimation(self.estimatedPrintTime());
return formatDuration(self.estimatedPrintTime());
return "-";
});
self.byteString = ko.pureComputed(function() {
@@ -84,61 +83,11 @@ $(function() {
return formatFuzzyEstimation(self.printTimeLeft());
}
});
self.printTimeLeftOriginString = ko.pureComputed(function() {
var value = self.printTimeLeftOrigin();
switch (value) {
case "linear": {
return gettext("Based on a linear approximation (accuracy highly dependent on the model)");
}
case "analysis": {
return gettext("Based on the estimate from analysis of file (medium accuracy)");
}
case "mixed-analysis": {
return gettext("Based on a mix of estimate from analysis and calculation (medium accuracy)");
}
case "average": {
return gettext("Based on the average total of past prints of this model with the same printer profile (usually good accuracy)");
}
case "mixed-average": {
return gettext("Based on a mix of average total from past prints and calculation (usually good accuracy)");
}
case "estimate": {
return gettext("Based on the calculated estimate (best accuracy)");
}
default: {
return "";
}
}
});
self.printTimeLeftOriginClass = ko.pureComputed(function() {
var value = self.printTimeLeftOrigin();
switch (value) {
default:
case "linear": {
return "text-error";
}
case "analysis":
case "mixed-analysis": {
return "text-warning";
}
case "average":
case "mixed-average":
case "estimate": {
return "text-success";
}
}
});
self.progressString = ko.pureComputed(function() {
if (!self.progress())
return 0;
return self.progress();
});
self.progressBarString = ko.pureComputed(function() {
if (!self.progress()) {
return "";
}
return _.sprintf("%d%%", self.progress());
});
self.pauseString = ko.pureComputed(function() {
if (self.isPaused())
return gettext("Continue");
@@ -242,7 +191,6 @@ $(function() {
self.filepos(data.filepos);
self.printTime(data.printTime);
self.printTimeLeft(data.printTimeLeft);
self.printTimeLeftOrigin(data.printTimeLeftOrigin);
};
self._processZData = function(data) {
@@ -275,41 +223,21 @@ $(function() {
};
self.onlyPause = function() {
self.pause("pause");
};
self.onlyResume = function() {
self.pause("resume");
};
self.pause = function(action) {
action = action || "toggle";
self._jobCommand("pause", {"action": action});
self.pause = function() {
self._jobCommand("pause");
};
self.cancel = function() {
self._jobCommand("cancel");
};
self._jobCommand = function(command, payload, callback) {
if (arguments.length == 1) {
payload = {};
callback = undefined;
} else if (arguments.length == 2 && typeof payload === "function") {
callback = payload;
payload = {};
}
var data = _.extend(payload, {});
data.command = command;
self._jobCommand = function(command, callback) {
$.ajax({
url: API_BASEURL + "job",
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data),
data: JSON.stringify({command: command}),
success: function(response) {
if (callback != undefined) {
callback();
@@ -5,7 +5,6 @@ $(function() {
self.loginState = parameters[0];
self.users = parameters[1];
self.printerProfiles = parameters[2];
self.about = parameters[3];
self.receiving = ko.observable(false);
self.sending = ko.observable(false);
@@ -116,7 +115,6 @@ $(function() {
self.feature_waitForStart = ko.observable(undefined);
self.feature_alwaysSendChecksum = ko.observable(undefined);
self.feature_sdSupport = ko.observable(undefined);
self.feature_sdRelativePath = ko.observable(undefined);
self.feature_sdAlwaysAvailable = ko.observable(undefined);
self.feature_swallowOkAfterResend = ko.observable(undefined);
self.feature_repetierTargetTemp = ko.observable(undefined);
@@ -143,10 +141,6 @@ $(function() {
self.serial_ignoreErrorsFromFirmware = ko.observable(undefined);
self.serial_disconnectOnErrors = ko.observable(undefined);
self.serial_triggerOkForM29 = ko.observable(undefined);
self.serial_supportResendsWithoutOk = ko.observable(undefined);
self.serial_maxTimeoutsIdle = ko.observable(undefined);
self.serial_maxTimeoutsPrinting = ko.observable(undefined);
self.serial_maxTimeoutsLong = ko.observable(undefined);
self.folder_uploads = ko.observable(undefined);
self.folder_timelapse = ko.observable(undefined);
@@ -466,10 +460,6 @@ $(function() {
self.serial_ignoreErrorsFromFirmware(response.serial.ignoreErrorsFromFirmware);
self.serial_disconnectOnErrors(response.serial.disconnectOnErrors);
self.serial_triggerOkForM29(response.serial.triggerOkForM29);
self.serial_supportResendsWithoutOk(response.serial.supportResendsWithoutOk);
self.serial_maxTimeoutsIdle(response.serial.maxTimeoutsIdle);
self.serial_maxTimeoutsPrinting(response.serial.maxTimeoutsPrinting);
self.serial_maxTimeoutsLong(response.serial.maxTimeoutsLong);
self.folder_uploads(response.folder.uploads);
self.folder_timelapse(response.folder.timelapse);
@@ -561,11 +551,7 @@ $(function() {
"helloCommand": self.serial_helloCommand(),
"ignoreErrorsFromFirmware": self.serial_ignoreErrorsFromFirmware(),
"disconnectOnErrors": self.serial_disconnectOnErrors(),
"triggerOkForM29": self.serial_triggerOkForM29(),
"supportResendsWithoutOk": self.serial_supportResendsWithoutOk(),
"maxTimeoutsIdle": self.serial_maxTimeoutsIdle(),
"maxTimeoutsPrinting": self.serial_maxTimeoutsPrinting(),
"maxTimeoutsLong": self.serial_maxTimeoutsLong()
"triggerOkForM29": self.serial_triggerOkForM29()
},
"folder": {
"uploads": self.folder_uploads(),
@@ -646,7 +632,7 @@ $(function() {
OCTOPRINT_VIEWMODELS.push([
SettingsViewModel,
["loginStateViewModel", "usersViewModel", "printerProfilesViewModel", "aboutViewModel"],
["loginStateViewModel", "usersViewModel", "printerProfilesViewModel"],
["#settings_dialog", "#navbar_settings"]
]);
});
+94 -166
View File
@@ -5,15 +5,14 @@ $(function() {
self.loginState = parameters[0];
self.printerProfiles = parameters[1];
self.file = ko.observable(undefined);
self.target = undefined;
self.file = undefined;
self.data = undefined;
self.defaultSlicer = undefined;
self.defaultProfile = undefined;
self.destinationFilename = ko.observable();
self.gcodeFilename = self.destinationFilename; // TODO: for backwards compatiblity, mark deprecated ASAP
self.gcodeFilename = ko.observable();
self.title = ko.observable();
self.slicer = ko.observable();
@@ -22,16 +21,90 @@ $(function() {
self.profiles = ko.observableArray();
self.printerProfile = ko.observable();
self.slicersForFile = function(file) {
if (file === undefined) {
return [];
self.configured_slicers = ko.pureComputed(function() {
return _.filter(self.slicers(), function(slicer) {
return slicer.configured;
});
});
self.afterSlicingOptions = [
{"value": "none", "text": gettext("Do nothing")},
{"value": "select", "text": gettext("Select for printing")},
{"value": "print", "text": gettext("Start printing")}
];
self.afterSlicing = ko.observable("none");
self.show = function(target, file, force) {
if (!self.enableSlicingDialog() && !force) {
return;
}
return _.filter(self.configuredSlicers(), function(slicer) {
return _.any(slicer.sourceExtensions, function(extension) {
return _.endsWith(file.toLowerCase(), "." + extension.toLowerCase());
self.requestData();
self.target = target;
self.file = file;
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file}));
self.gcodeFilename(self.file.substr(0, self.file.lastIndexOf(".")));
self.printerProfile(self.printerProfiles.currentProfile());
self.afterSlicing("none");
$("#slicing_configuration_dialog").modal("show");
};
self.slicer.subscribe(function(newValue) {
self.profilesForSlicer(newValue);
});
self.enableSlicingDialog = ko.pureComputed(function() {
return self.configured_slicers().length > 0;
});
self.enableSliceButton = ko.pureComputed(function() {
return self.gcodeFilename() != undefined
&& self.gcodeFilename().trim() != ""
&& self.slicer() != undefined
&& self.profile() != undefined;
});
self.requestData = function(callback) {
$.ajax({
url: API_BASEURL + "slicing",
type: "GET",
dataType: "json",
success: function(data) {
self.fromResponse(data);
if (callback !== undefined) {
callback();
}
}
});
};
self.fromResponse = function(data) {
self.data = data;
var selectedSlicer = undefined;
self.slicers.removeAll();
_.each(_.values(data), function(slicer) {
var name = slicer.displayName;
if (name == undefined) {
name = slicer.key;
}
if (slicer.default && slicer.configured) {
selectedSlicer = slicer.key;
}
self.slicers.push({
key: slicer.key,
name: name,
configured: slicer.configured
});
});
if (selectedSlicer != undefined) {
self.slicer(selectedSlicer);
}
self.defaultSlicer = selectedSlicer;
};
self.profilesForSlicer = function(key) {
@@ -61,164 +134,19 @@ $(function() {
})
});
self.profile(selectedProfile);
if (selectedProfile != undefined) {
self.profile(selectedProfile);
}
self.defaultProfile = selectedProfile;
};
self.resetProfiles = function() {
self.profiles.removeAll();
self.profile(undefined);
};
self.configuredSlicers = ko.pureComputed(function() {
return _.filter(self.slicers(), function(slicer) {
return slicer.configured;
});
});
self.matchingSlicers = ko.computed(function() {
var slicers = self.slicersForFile(self.file());
var containsSlicer = function(key) {
return _.any(slicers, function(slicer) {
return slicer.key == key;
});
};
var current = self.slicer();
if (!containsSlicer(current)) {
if (self.defaultSlicer !== undefined && containsSlicer(self.defaultSlicer)) {
self.slicer(self.defaultSlicer);
} else {
self.slicer(undefined);
self.resetProfiles();
}
} else {
self.profilesForSlicer(self.slicer());
}
return slicers;
});
self.afterSlicingOptions = [
{"value": "none", "text": gettext("Do nothing")},
{"value": "select", "text": gettext("Select for printing")},
{"value": "print", "text": gettext("Start printing")}
];
self.afterSlicing = ko.observable("none");
self.show = function(target, file, force) {
if (!self.enableSlicingDialog() && !force) {
return;
}
self.requestData();
self.target = target;
self.file(file);
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file()}));
self.destinationFilename(self.file().substr(0, self.file().lastIndexOf(".")));
self.printerProfile(self.printerProfiles.currentProfile());
self.afterSlicing("none");
$("#slicing_configuration_dialog").modal("show");
};
self.slicer.subscribe(function(newValue) {
if (newValue === undefined) {
self.resetProfiles();
} else {
self.profilesForSlicer(newValue);
}
});
self.enableSlicingDialog = ko.pureComputed(function() {
return self.configuredSlicers().length > 0;
});
self.enableSlicingDialogForFile = function(file) {
return self.slicersForFile(file).length > 0;
};
self.enableSliceButton = ko.pureComputed(function() {
return self.destinationFilename() != undefined
&& self.destinationFilename().trim() != ""
&& self.slicer() != undefined
&& self.profile() != undefined;
});
self.requestData = function(callback) {
$.ajax({
url: API_BASEURL + "slicing",
type: "GET",
dataType: "json",
success: function(data) {
self.fromResponse(data);
if (callback !== undefined) {
callback();
}
}
});
};
self.destinationExtension = ko.pureComputed(function() {
var fallback = "???";
if (self.slicer() === undefined) {
return fallback;
}
var slicer = self.data[self.slicer()];
if (slicer === undefined) {
return fallback;
}
var extensions = slicer.extensions;
if (extensions === undefined) {
return fallback;
}
var destinationExtensions = extensions.destination;
if (destinationExtensions === undefined || !destinationExtensions.length) {
return fallback;
}
return destinationExtensions[0] || fallback;
});
self.fromResponse = function(data) {
self.data = data;
var selectedSlicer = undefined;
self.slicers.removeAll();
_.each(_.values(data), function(slicer) {
var name = slicer.displayName;
if (name == undefined) {
name = slicer.key;
}
if (slicer.default && slicer.configured) {
selectedSlicer = slicer.key;
}
var props = {
key: slicer.key,
name: name,
configured: slicer.configured,
sourceExtensions: slicer.extensions.source,
destinationExtensions: slicer.extensions.destination
};
self.slicers.push(props);
});
self.defaultSlicer = selectedSlicer;
};
self.slice = function() {
var destinationFilename = self._sanitize(self.destinationFilename());
var destinationExtensions = self.data[self.slicer()] && self.data[self.slicer()].extensions && self.data[self.slicer()].extensions.destination
? self.data[self.slicer()].extensions.destination
: ["???"];
if (!_.any(destinationExtensions, function(extension) {
return _.endsWith(destinationFilename.toLowerCase(), "." + extension.toLowerCase());
})) {
destinationFilename = destinationFilename + "." + destinationExtensions[0];
var gcodeFilename = self._sanitize(self.gcodeFilename());
if (!_.endsWith(gcodeFilename.toLowerCase(), ".gco")
&& !_.endsWith(gcodeFilename.toLowerCase(), ".gcode")
&& !_.endsWith(gcodeFilename.toLowerCase(), ".g")) {
gcodeFilename = gcodeFilename + ".gco";
}
var data = {
@@ -226,7 +154,7 @@ $(function() {
slicer: self.slicer(),
profile: self.profile(),
printerProfile: self.printerProfile(),
destination: destinationFilename
gcode: gcodeFilename
};
if (self.afterSlicing() == "print") {
@@ -236,7 +164,7 @@ $(function() {
}
$.ajax({
url: API_BASEURL + "files/" + self.target + "/" + self.file(),
url: API_BASEURL + "files/" + self.target + "/" + self.file,
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
@@ -245,7 +173,7 @@ $(function() {
$("#slicing_configuration_dialog").modal("hide");
self.destinationFilename(undefined);
self.gcodeFilename(undefined);
self.slicer(self.defaultSlicer);
self.profile(self.defaultProfile);
};
@@ -40,15 +40,13 @@ $(function() {
var graphColors = ["red", "orange", "green", "brown", "purple"];
var heaterOptions = {};
var tools = self.tools();
var color;
// tools
var currentProfileData = self.settingsViewModel.printerProfiles.currentProfileData();
var numExtruders = (currentProfileData ? currentProfileData.extruder.count() : 0);
var numExtruders = self.settingsViewModel.printerProfiles.currentProfileData().extruder.count();
if (numExtruders && numExtruders > 1) {
// multiple extruders
for (var extruder = 0; extruder < numExtruders; extruder++) {
color = graphColors.shift();
var color = graphColors.shift();
if (!color) color = "black";
heaterOptions["tool" + extruder] = {name: "T" + extruder, color: color};
@@ -58,9 +56,9 @@ $(function() {
tools[extruder]["name"](gettext("Tool") + " " + extruder);
tools[extruder]["key"]("tool" + extruder);
}
} else if (numExtruders == 1) {
} else {
// only one extruder, no need to add numbers
color = graphColors[0];
var color = graphColors[0];
heaterOptions["tool0"] = {name: "T", color: color};
if (tools.length < 1 || !tools[0]) {
@@ -71,7 +69,7 @@ $(function() {
}
// print bed
if (currentProfileData && currentProfileData.heatedBed()) {
if (self.settingsViewModel.printerProfiles.currentProfileData().heatedBed()) {
self.hasBed(true);
heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"};
} else {
@@ -81,12 +79,11 @@ $(function() {
// write back
self.heaterOptions(heaterOptions);
self.tools(tools);
self.updatePlot();
};
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
self._printerProfileUpdated();
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated);
self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated());
});
self.temperatures = [];
@@ -370,11 +367,7 @@ $(function() {
return;
}
self.updatePlot();
};
self.onStartupComplete = function() {
self._printerProfileUpdated();
};
}
}
@@ -4,8 +4,6 @@ $(function() {
self.loginState = parameters[0];
self.timelapsePopup = undefined;
self.defaultFps = 25;
self.defaultPostRoll = 0;
self.defaultInterval = 10;
@@ -229,88 +227,11 @@ $(function() {
});
};
self.displayTimelapsePopup = function(options) {
if (self.timelapsePopup !== undefined) {
self.timelapsePopup.remove();
}
_.extend(options, {
callbacks: {
before_close: function(notice) {
if (self.timelapsePopup == notice) {
self.timelapsePopup = undefined;
}
}
}
});
self.timelapsePopup = new PNotify(options);
};
self.onDataUpdaterReconnect = function() {
self.requestData();
};
self.onEventPostRollStart = function(payload) {
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 {
var format = {
time: moment().add(payload.postroll_duration, "s").format("LT")
};
if (payload.postroll_duration > 60) {
format.duration = _.sprintf(gettext("%(minutes)d min"), {minutes: payload.postroll_duration / 60});
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s (so until %(time)s)..."), format);
} 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);
}
}
self.displayTimelapsePopup({
title: title,
text: text,
hide: false
});
};
self.onEventMovieRendering = function(payload) {
self.displayTimelapsePopup({
title: gettext("Rendering timelapse"),
text: _.sprintf(gettext("Now rendering timelapse %(movie_prefix)s. Due to performance reasons it is not recommended to start a print job while a movie is still rendering."), payload),
hide: false
});
};
self.onEventMovieFailed = function(payload) {
var html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_prefix)s failed with return code %(returncode)s"), payload) + "</p>";
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
self.displayTimelapsePopup({
title: gettext("Rendering failed"),
text: html,
type: "error",
hide: false
});
};
self.onEventMovieDone = function(payload) {
self.displayTimelapsePopup({
title: gettext("Timelapse ready"),
text: _.sprintf(gettext("New timelapse %(movie_prefix)s is done rendering."), payload),
type: "success",
callbacks: {
before_close: function(notice) {
if (self.timelapsePopup == notice) {
self.timelapsePopup = undefined;
}
}
}
});
self.requestData();
};
-78
View File
@@ -513,14 +513,6 @@ ul.dropdown-menu li a {
}
}
/** State sidebar panel */
#state_wrapper {
hr {
margin: 5px 0;
}
}
/** GCODE file manager */
#files {
@@ -560,20 +552,6 @@ ul.dropdown-menu li a {
.additionalInfo {
padding-bottom: @line-height + 2px;
}
@highlight-color: yellow;
@keyframes highlightframes {
0% {
background: @highlight-color;
}
100% {
background: transparent;
}
}
&.highlight {
animation: highlightframes 2s;
}
}
}
@@ -733,10 +711,6 @@ ul.dropdown-menu li a {
margin-left: 0;
}
}
.aboutlink {
float: left;
}
}
@@ -1062,55 +1036,3 @@ _::-webkit-full-page-media, _:future, :root .full-sized-box {
input[type=number] {
text-align: right;
}
// Progress bars with text
//
// .progress-text-front will also need to have the full width of the enclosing
// progress wrapper applied (e.g. via copyWidth knockout binding)
.progress-text,
.progress-text-centered {
position: relative;
.progress-text-front,
.progress-text-back {
white-space: nowrap;
}
.progress-text-front {
box-sizing: border-box;
padding: 0 10px;
width: 100%;
display: block;
}
.progress-text-back {
position: absolute;
font-size: 12px;
line-height: 20px;
display: block;
box-sizing: border-box;
text-align: center;
padding: 0 10px;
}
.bar {
position: absolute;
overflow: hidden;
}
}
.progress-text-centered {
.progress-text-front {
position: absolute;
font-size: 12px;
line-height: 20px;
display: block;
text-align: center;
color: #fff;
}
.progress-text-back {
width: 100%;
}
}
-677
View File
@@ -1,677 +0,0 @@
<h3 style="text-align: center;">GNU AFFERO GENERAL PUBLIC LICENSE</h3>
<p style="text-align: center;">Version 3, 19 November 2007</p>
<p>Copyright &copy; 2007 Free Software Foundation,
Inc. &lt;<a href="http://fsf.org/">http://fsf.org/</a>&gt;
<br />
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.</p>
<h3><a name="preamble"></a>Preamble</h3>
<p>The GNU Affero General Public License is a free, copyleft license
for software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.</p>
<p>The licenses for most software and other practical works are
designed to take away your freedom to share and change the works. By
contrast, our General Public Licenses are intended to guarantee your
freedom to share and change all versions of a program--to make sure it
remains free software for all its users.</p>
<p>When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.</p>
<p>Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.</p>
<p>A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.</p>
<p>The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.</p>
<p>An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.</p>
<p>The precise terms and conditions for copying, distribution and
modification follow.</p>
<h3><a name="terms"></a>TERMS AND CONDITIONS</h3>
<h4><a name="section0"></a>0. Definitions.</h4>
<p>&quot;This License&quot; refers to version 3 of the GNU Affero General Public
License.</p>
<p>&quot;Copyright&quot; also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.</p>
<p>&quot;The Program&quot; refers to any copyrightable work licensed under this
License. Each licensee is addressed as &quot;you&quot;. &quot;Licensees&quot; and
&quot;recipients&quot; may be individuals or organizations.</p>
<p>To &quot;modify&quot; a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a &quot;modified version&quot; of the
earlier work or a work &quot;based on&quot; the earlier work.</p>
<p>A &quot;covered work&quot; means either the unmodified Program or a work based
on the Program.</p>
<p>To &quot;propagate&quot; a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.</p>
<p>To &quot;convey&quot; a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.</p>
<p>An interactive user interface displays &quot;Appropriate Legal Notices&quot;
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.</p>
<h4><a name="section1"></a>1. Source Code.</h4>
<p>The &quot;source code&quot; for a work means the preferred form of the work
for making modifications to it. &quot;Object code&quot; means any non-source
form of a work.</p>
<p>A &quot;Standard Interface&quot; means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.</p>
<p>The &quot;System Libraries&quot; of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
&quot;Major Component&quot;, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.</p>
<p>The &quot;Corresponding Source&quot; for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.</p>
<p>The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.</p>
<p>The Corresponding Source for a work in source code form is that
same work.</p>
<h4><a name="section2"></a>2. Basic Permissions.</h4>
<p>All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.</p>
<p>You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.</p>
<p>Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.</p>
<h4><a name="section3"></a>3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4>
<p>No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.</p>
<p>When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.</p>
<h4><a name="section4"></a>4. Conveying Verbatim Copies.</h4>
<p>You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.</p>
<p>You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.</p>
<h4><a name="section5"></a>5. Conveying Modified Source Versions.</h4>
<p>You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:</p>
<ul>
<li>a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.</li>
<li>b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
&quot;keep intact all notices&quot;.</li>
<li>c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.</li>
<li>d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.</li>
</ul>
<p>A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
&quot;aggregate&quot; if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.</p>
<h4><a name="section6"></a>6. Conveying Non-Source Forms.</h4>
<p>You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:</p>
<ul>
<li>a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.</li>
<li>b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.</li>
<li>c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.</li>
<li>d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.</li>
<li>e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.</li>
</ul>
<p>A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.</p>
<p>A &quot;User Product&quot; is either (1) a &quot;consumer product&quot;, which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, &quot;normally used&quot; refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.</p>
<p>&quot;Installation Information&quot; for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.</p>
<p>If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).</p>
<p>The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.</p>
<p>Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.</p>
<h4><a name="section7"></a>7. Additional Terms.</h4>
<p>&quot;Additional permissions&quot; are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.</p>
<p>When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.</p>
<p>Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:</p>
<ul>
<li>a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or</li>
<li>b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or</li>
<li>c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or</li>
<li>d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or</li>
<li>e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or</li>
<li>f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.</li>
</ul>
<p>All other non-permissive additional terms are considered &quot;further
restrictions&quot; within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further restriction,
you may remove that term. If a license document contains a further
restriction but permits relicensing or conveying under this License, you
may add to a covered work material governed by the terms of that license
document, provided that the further restriction does not survive such
relicensing or conveying.</p>
<p>If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.</p>
<p>Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.</p>
<h4><a name="section8"></a>8. Termination.</h4>
<p>You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).</p>
<p>However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.</p>
<p>Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.</p>
<p>Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.</p>
<h4><a name="section9"></a>9. Acceptance Not Required for Having Copies.</h4>
<p>You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.</p>
<h4><a name="section10"></a>10. Automatic Licensing of Downstream Recipients.</h4>
<p>Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.</p>
<p>An &quot;entity transaction&quot; is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.</p>
<p>You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.</p>
<h4><a name="section11"></a>11. Patents.</h4>
<p>A &quot;contributor&quot; is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's &quot;contributor version&quot;.</p>
<p>A contributor's &quot;essential patent claims&quot; are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, &quot;control&quot; includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.</p>
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.</p>
<p>In the following three paragraphs, a &quot;patent license&quot; is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To &quot;grant&quot; such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.</p>
<p>If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. &quot;Knowingly relying&quot; means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.</p>
<p>If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.</p>
<p>A patent license is &quot;discriminatory&quot; if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.</p>
<p>Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.</p>
<h4><a name="section12"></a>12. No Surrender of Others' Freedom.</h4>
<p>If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.</p>
<h4><a name="section13"></a>13. Remote Network Interaction; Use with the GNU General Public License.</h4>
<p>Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.</p>
<p>Notwithstanding any other provision of this License, you have permission
to link or combine any covered work with a work licensed under version 3
of the GNU General Public License into a single combined work, and to
convey the resulting work. The terms of this License will continue to
apply to the part which is the covered work, but the work with which it is
combined will remain governed by version 3 of the GNU General Public
License.</p>
<h4><a name="section14"></a>14. Revised Versions of this License.</h4>
<p>The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may differ
in detail to address new problems or concerns.</p>
<p>Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero
General Public License &quot;or any later version&quot; applies to it, you have
the option of following the terms and conditions either of that
numbered version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number
of the GNU Affero General Public License, you may choose any version
ever published by the Free Software Foundation.</p>
<p>If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that
proxy's public statement of acceptance of a version permanently
authorizes you to choose that version for the Program.</p>
<p>Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.</p>
<h4><a name="section15"></a>15. Disclaimer of Warranty.</h4>
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM &quot;AS IS&quot; WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p>
<h4><a name="section16"></a>16. Limitation of Liability.</h4>
<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.</p>
<h4><a name="section17"></a>17. Interpretation of Sections 15 and 16.</h4>
<p>If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.</p>
<p>END OF TERMS AND CONDITIONS</p>
<h3><a name="howto"></a>How to Apply These Terms to Your New Programs</h3>
<p>If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.</p>
<p>To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the &quot;copyright&quot; line and a pointer to where the full notice is found.</p>
<pre> &lt;one line to give the program's name and a brief idea of what it does.&gt;
Copyright (C) &lt;year&gt; &lt;name of author&gt;
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see &lt;http://www.gnu.org/licenses/&gt;.
</pre>
<p>Also add information on how to contact you by electronic and paper mail.</p>
<p>If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a &quot;Source&quot; link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.</p>
<p>You should also get your employer (if you work as a programmer) or school,
if any, to sign a &quot;copyright disclaimer&quot; for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
&lt;<a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>&gt;.</p>
@@ -1,53 +0,0 @@
<div id="about_dialog" class="modal hide fade large" tabindex="-1" role="dialog" aria-labelledby="about_dialog_label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h3 id="about_dialog_label">{{ _('About OctoPrint') }}</h3>
</div>
<div class="modal-body">
<div class="full-sized-box">
<div class="tabbable row-fluid">
<div class="span3 scrollable" id="about_dialog_menu">
<ul class="nav nav-list" id="about_dialog_tabs">
{% set mark_active = True %}
{% for key in templates.about.order %}
{% set entry, data = templates.about.entries[key] %}
{% if data is none %}
<li class="nav-header">{{ entry }}</li>
{% else %}
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
<li id="{{ data._div }}_link"
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% 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 %}
>
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
</li>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endif %}
{% endfor %}
</ul>
</div>
<div class="tab-content span9 scrollable" id="about_dialog_content">
{% set mark_active = True %}
{% for key in templates.about.order %}
{% set entry, data = templates.about.entries[key] %}
{% if data is not none %}
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
<div id="{{ data._div }}"
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
class="tab-pane {% if mark_active %}active{% set mark_active = False %}{% endif %} {% if classes_content in data %}{{ data.classes_content|join(' ') }}{% elif classes in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif styles in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
</div>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endif %}
{% endfor %}
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-block" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
@@ -1,49 +0,0 @@
<h3>{{ _('OctoPrint') }}</h3>
<h4>{{ _('The snappy web interface for your 3D printer') }}</h4>
<p>Version <span class="version">{{ display_version }}</span></p>
<ul>
<li>Website: <a href="http://octoprint.org" target="_blank" rel="noreferrer noopener">octoprint.org</a></li>
<li>Source Code: <a href="https://github.com/foosel/OctoPrint" target="_blank" rel="noreferrer noopener">github.com/foosel/OctoPrint</a></li>
<li>Documentation: <a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener">docs.octoprint.org</a></li>
</ul>
<p>
<strong>Development of OctoPrint wouldn't be possible without <a href="javascript:void(0)" data-bind="click: function() { showTab('{{ templates.about.entries.supporters[1]._div }}'); }">its supporters</a>.</strong><br>
If you enjoy OctoPrint, please consider <a href="http://octoprint.org/support-octoprint/" target="_blank" rel="noreferrer noopener">supporting its ongoing development</a>.
</p>
<p>
&copy; 2012-{{ now.strftime("%Y") }} <a href="javascript:void(0)" data-bind="click: function() { showTab('{{ templates.about.entries.authors[1]._div }}'); }">The OctoPrint Authors</a>
</p>
<p>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
</p>
<p>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
</p>
<p>
For a copy of the GNU Affero General Public License, see <a href="javascript:void(0)" data-bind="click: function() { showTab('{{ templates.about.entries.license[1]._div }}'); }">{{ templates.about.entries.license[0] }}</a>
to the left.
</p>
<p>
OctoPrint also utilizes various dependencies under terms of their
respective licenses, which can be found under <a href="javascript:void(0)" data-bind="click: function() { showTab('{{ templates.about.entries.thirdparty[1]._div }}'); }">{{ templates.about.entries.thirdparty[0] }}</a> to
the left. Copyright of those dependencies lies with their respective authors
</p>
<p><small>
"OctoPrint" is a registered trademark.
</small></p>
@@ -1 +0,0 @@
{% filter externalize_links %}{% filter markdown %}{% filter offset_markdown_headers(2) %}{% include "_data/AUTHORS.md" ignore missing %}{% endfilter %}{% endfilter %}{% endfilter %}
@@ -1 +0,0 @@
{% filter externalize_links %}{% filter markdown %}{% filter offset_markdown_headers(2) %}{% include "_data/CHANGELOG.md" ignore missing %}{% endfilter %}{% endfilter %}{% endfilter %}
@@ -1 +0,0 @@
{% filter externalize_links %}{% include "_data/agpl.html" %}{% endfilter %}
@@ -1 +0,0 @@
{% filter externalize_links %}{% filter markdown %}{% filter offset_markdown_headers(2) %}{% include "_data/SUPPORTERS.md" ignore missing %}{% endfilter %}{% endfilter %}{% endfilter %}
@@ -1 +0,0 @@
{% filter externalize_links %}{% filter markdown %}{% filter offset_markdown_headers(2) %}{% include "_data/THIRDPARTYLICENSES.md" ignore missing %}{% endfilter %}{% endfilter %}{% endfilter %}
@@ -38,7 +38,7 @@
class="tab-pane {% if mark_active %}active{% set mark_active = False %}{% endif %} {% if classes_content in data %}{{ data.classes_content|join(' ') }}{% elif classes in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif styles in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
{% include data.template ignore missing %}
</div>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endif %}
@@ -48,7 +48,6 @@
</div>
</div>
<div class="modal-footer">
<button class="btn aboutlink" data-bind="click: about.show"><i class="icon-info-sign"></i> {{ _('About OctoPrint') }}</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) }, enable: !exchanging(), css: {disabled: exchanging()}"><i class="icon-spinner icon-spin" data-bind="visible: sending"></i> {{ _('Save') }}</button>
</div>
@@ -107,7 +107,7 @@
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmEditUser(); }">{{ _('Confirm') }}</button>
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmUserSettingsDialog(); }">{{ _('Confirm') }}</button>
</div>
</div>
@@ -34,13 +34,6 @@
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdRelativePath" id="settings-sdRelativePath"> {{ _('Select SD files by relative path') }} <span class="label">{{ _('RepRap Firmware') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
@@ -55,6 +55,4 @@
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_critical_str">
</div>
</div>
<p>{% trans %}Provide values including size unit. Allowed units are: b, byte, bytes, kb, mb, gb, tb (case insensitive). Example: <code>5MB</code>, <code>500KB</code>{% endtrans %}</p>
</form>
@@ -121,29 +121,6 @@
<input type="checkbox" data-bind="checked: serial_triggerOkForM29" id="settings-triggerOkForM29"> {{ _('Generate additional <code>ok</code> for <code>M29</code>') }} <span class="label">{{ _('Most Marlin < v1.1.0') }}</span>
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_supportResendsWithoutOk" id="settings-supportResendsWithoutOk"> {{ _('Simulate an additional `ok` for resend requests') }}
</label>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while idle. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsIdle">{{ _('Max. consecutive timeouts while idle') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsIdle" data-bind="value: serial_maxTimeoutsIdle">
</div>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while printing. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsPrinting">{{ _('Max. consecutive timeouts while printing') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsPrinting" data-bind="value: serial_maxTimeoutsPrinting">
</div>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while a long running command is active. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsLong">{{ _('Max. consecutive timeouts during long running commands') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsLong" data-bind="value: serial_maxTimeoutsLong">
</div>
</div>
</div>
</div>
@@ -13,7 +13,7 @@
<div class="control-group">
<label class="control-label">{{ _('Slicer') }}</label>
<div class="controls">
<select data-bind="options: matchingSlicers, optionsText: 'name', optionsValue: 'key', optionsCaption: '{{ _('Select a slicer...') }}', value: slicer, valueAllowUnset: true"></select>
<select data-bind="options: configured_slicers, optionsText: 'name', optionsValue: 'key', optionsCaption: '{{ _('Select a slicer...') }}', value: slicer, valueAllowUnset: true"></select>
</div>
</div>
<div class="control-group">
@@ -29,11 +29,11 @@
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Output Filename') }}</label>
<label class="control-label">{{ _('GCode Filename') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" data-bind="value: destinationFilename">
<span class="add-on" data-bind="text: '.' + destinationExtension()"></span>
<input type="text" data-bind="value: gcodeFilename">
<span class="add-on">.gco</span>
</div>
</div>
</div>
@@ -35,7 +35,7 @@
class="tab-pane {% if mark_active %}active{% set mark_active = False %}{% endif %} {% if classes_content in data %}{{ data.classes_content|join(' ') }}{% elif classes in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif styles in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
{% include data.template ignore missing %}
</div>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endif %}
+9 -11
View File
@@ -31,7 +31,7 @@
{% if "classes" in data %}class="{{ data.classes|join(' ') }}"{% endif %}
{% if "styles" in data %}style="{{ data.styles|join(', ') }}"{% endif %}
>
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
{% include data.template ignore missing %}
</li>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endfor %}
@@ -58,7 +58,7 @@
{% if "icon" in data %}<i class="icon-{{ data.icon }}"></i> {% endif %}{{ entry|e }}
</a>
{% if "template_header" in data %}
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template_header ignore missing %}{% endtry %}
{% include data.template_header ignore missing %}
{% endif %}
</div>
<div id="{{ data._div }}"
@@ -66,7 +66,7 @@
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}"{% endif %}
>
<div class="accordion-inner">
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
{% include data.template ignore missing %}
</div>
</div>
</div>
@@ -102,7 +102,7 @@
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
{% include data.template ignore missing %}
</div>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endfor %}
@@ -115,11 +115,10 @@
<li><small>{{ _('Version') }}: <span class="version">{{ display_version|e }}</span></small></li>
</ul>
<ul class="pull-right">
<li><a href="http://octoprint.org" target="_blank" rel="noreferrer noopener"><i class="icon-home"></i> {{ _('Homepage') }}</a></li>
<li><a href="https://github.com/foosel/OctoPrint/" target="_blank" rel="noreferrer noopener"><i class="icon-github"></i> {{ _('Sourcecode') }}</a></li>
<li><a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener"><i class="icon-book"></i> {{ _('Documentation') }}</a></li>
<li><a href="https://github.com/foosel/OctoPrint/issues" target="_blank" rel="noreferrer noopener"><i class="icon-flag"></i> {{ _('Bugs and Requests') }}</a></li>
<li id="footer_about"><a href="javascript:void(0)" data-bind="click: show"><i class="icon-info-sign"></i> {{ _('About') }}</a></li>
<li><a href="http://octoprint.org"><i class="icon-home"></i> {{ _('Homepage') }}</a></li>
<li><a href="https://github.com/foosel/OctoPrint/"><i class="icon-github"></i> {{ _('Sourcecode') }}</a></li>
<li><a href="http://docs.octoprint.org"><i class="icon-book"></i> {{ _('Documentation') }}</a></li>
<li><a href="https://github.com/foosel/OctoPrint/issues"><i class="icon-flag"></i> {{ _('Bugs and Requests') }}</a></li>
</ul>
</div>
</div>
@@ -130,7 +129,6 @@
{% include 'dialogs/settings.jinja2' %}
{% include 'dialogs/slicing.jinja2' %}
{% include 'dialogs/usersettings.jinja2' %}
{% include 'dialogs/about.jinja2' %}
<!-- End of dialogs -->
<!-- Overlays -->
@@ -142,7 +140,7 @@
<!-- Generic plugin template files -->
{% for key in templates.generic.order %}
{% set data = templates.generic.entries[key] %}
{% try "<!-- There was an error with the template {filename} at line number {lineno}: {exception} -->" %}{% include data.template ignore missing %}{% endtry %}
{% include data.template ignore missing %}
{% endfor %}
<!-- End of generic plugin template files -->
@@ -29,7 +29,6 @@
var BRANCH = "{{ branch|e }}";
var LOCALE = "{{ g.locale|e }}";
var AVAILABLE_LOCALES = {{ locales|tojson }};
var SUPPORTED_EXTENSIONS = {{ supportedExtensions|tojson }};
var OCTOPRINT_VIEWMODELS = [];
var ADDITIONAL_VIEWMODELS = [];
+4 -7
View File
@@ -11,10 +11,10 @@
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
<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) }" 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)}" title="{{ _('Download') }}"><i class="icon-download-alt"></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)}" 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)}" 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)}" title="{{ _('Load and Print') }}"><i class="icon-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>
</script>
@@ -57,11 +57,8 @@
</span>
{% endif %}
</div>
<div id="gcode_upload_progress" class="progress progress-text-centered">
<span class="progress-text-back" data-bind="text: uploadProgressText"></span>
<div class="bar">
<span class="progress-text-front" data-bind="copyWidth: ':parent :parent :parent :parent form', text: uploadProgressText"></span>
</div>
<div id="gcode_upload_progress" class="progress" style="width: 100%;">
<div class="bar" style="width: 0%"></div>
</div>
<div>
<small class="muted">{{ _('Hint: You can also drag and drop files on this page to upload them.') }}</small>
+4 -9
View File
@@ -1,25 +1,20 @@
{{ _('Machine State') }}: <strong data-bind="text: stateString"></strong><br>
<hr>
{{ _('File') }}: <strong data-bind="text: filename"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
{{ _('Timelapse') }}: <strong data-bind="text: timelapseString"></strong><br>
<!-- ko foreach: filament -->
<span data-bind="text: 'Filament (' + name() + '): '"></span><strong data-bind="text: formatFilament(data())"></strong><br>
<!-- /ko -->
{{ _('Approx. Total Print Time') }}: <strong data-bind="text: estimatedPrintTimeString"></strong><br>
<hr>
{{ _('Print Time') }}: <strong data-bind="text: printTimeString"></strong><br>
{{ _('Print Time Left') }}: <strong data-bind="text: printTimeLeftString"></strong> <span id="state_printtimeleft_popover" style="display: none" data-bind="visible: printTimeLeftOrigin, attr: {title: printTimeLeftOriginString}, css: printTimeLeftOriginClass">&#9679;</span><br>
{{ _('Print Time Left') }}: <strong data-bind="text: printTimeLeftString"></strong><br>
{{ _('Printed') }}: <strong data-bind="text: byteString"></strong><br>
<div class="progress progress-text-centered">
<span class="progress-text-back" data-bind="text: progressBarString()"></span>
<div class="bar" id="job_progressBar" data-bind="style: {width: progressString() + '%'}">
<span class="progress-text-front" data-bind="copyWidth: ':parent :parent', text: progressBarString()"></span>
</div>
<div class="progress">
<div class="bar" id="job_progressBar" data-bind="style: { width: progressString() + '%' }"></div>
</div>
<div class="row-fluid print-control" style="display: none;" data-bind="visible: loginState.isUser">
<button class="btn btn-primary span4" data-bind="click: print, enable: enablePrint, css: {'btn-danger': isPaused()}, attr: {title: titlePrintButton}" id="job_print"><i class="icon-white" data-bind="css: {'icon-print': !isPaused(), 'icon-undo': isPaused()}"></i> <span data-bind="text: (isPaused() ? '{{ _('Restart') }}' : '{{ _('Print') }}')">{{ _('Print') }}</span></button>
<button class="btn span4" id="job_pause" data-bind="click: function() { isPaused() ? onlyResume() : onlyPause(); }, enable: enablePause, css: {active: isPaused()}, attr: {title: titlePauseButton}"><i data-bind="css: {'icon-pause': !isPaused(), 'icon-play': isPaused()}"></i> <span data-bind="visible: !isPaused()">{{ _('Pause') }}</span><span data-bind="visible: isPaused()">{{ _('Resume') }}</span></button>
<button class="btn span4" id="job_pause" data-bind="click: pause, enable: enablePause, css: {active: isPaused()}, attr: {title: titlePauseButton}"><i data-bind="css: {'icon-pause': !isPaused(), 'icon-play': isPaused()}"></i> <span data-bind="visible: !isPaused()">{{ _('Pause') }}</span><span data-bind="visible: isPaused()">{{ _('Resume') }}</span></button>
<button class="btn span4" id="job_cancel" data-bind="click: cancel, enable: enableCancel" title="{{ _('Cancels the print job') }}"><i class="icon-stop"></i> {{ _('Cancel') }}</button>
</div>
+4 -3
View File
@@ -57,9 +57,10 @@
<!-- Jog distance -->
<div class="distance">
<div class="btn-group" data-toggle="buttons-radio" id="jog_distance">
<!-- ko foreach: distances -->
<button type="button" class="btn distance" data-bind="enable: $root.loginState.isUser(), text: $data, click: function() { $root.distance($data) }, css: { active: $root.distance() === $data }, attr: { id: 'control-distance' + $root.stripDistanceDecimal($data) }"></button>
<!-- /ko -->
<button type="button" id="control-distance01" class="btn distance" data-distance="0.1" data-bind="enable: loginState.isUser()">0.1</button>
<button type="button" id="control-distance1" class="btn distance" data-distance="1" data-bind="enable: loginState.isUser()">1</button>
<button type="button" id="control-distance10" class="btn distance active" data-distance="10" data-bind="enable: loginState.isUser()">10</button>
<button type="button" id="control-distance100" class="btn distance" data-distance="100" data-bind="enable: loginState.isUser()">100</button>
</div>
</div>
@@ -5,11 +5,8 @@
<input id="gcode_slider_commands" type="text" style="width: 554px">
</div>
<div class="progress progress-text-centered">
<span class="progress-text-back" data-bind="text: ui_progress_text"></span>
<div class="bar" style="width: 0;" data-bind="style: { width: ui_progress_percentage() + '%' }">
<span class="progress-text-front" data-bind="copyWidth: ':parent :parent', text: ui_progress_text"></span>
</div>
<div class="progress" >
<div class="bar" style="width: 0%;" data-bind="text: ui_progress_text, style: { width: ui_progress_percentage() + '%' }"></div>
</div>
<div class="row-fluid">
@@ -94,10 +94,7 @@
<td class="timelapse_unrendered_name" data-bind="text: name"></td>
<td class="timelapse_unrendered_count" data-bind="text: count"></td>
<td class="timelapse_unrendered_size" data-bind="text: size"></td>
<td class="timelapse_unrendered_action">
<span data-bind="visible: processing"><i class="icon-refresh icon-spin"></i></span>
<span data-bind="visible: !processing"><a href="javascript:void(0)" title="{{ _('Delete unrendered timelapse') }}" class="icon-trash" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeUnrendered($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a>&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Render timelapse') }}" class="icon-facetime-video" data-bind="click: function() { if ($root.loginState.isUser() && !$root.isBusy()) { $parent.renderUnrendered($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser() || $root.isBusy()}"></a></span>
</td>
<td class="timelapse_unrendered_action"><a href="javascript:void(0)" title="{{ _('Delete unrendered timelapse') }}" class="icon-trash" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeUnrendered($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a>&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Render timelapse') }}" class="icon-facetime-video" data-bind="click: function() { if ($root.loginState.isUser() && !$root.isBusy()) { $parent.renderUnrendered($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser() || $root.isBusy()}"></a></td>
</tr>
</tbody>
</table>
+43 -87
View File
@@ -44,12 +44,6 @@ _valid_timelapse_types = ["off", "timed", "zchange"]
# callbacks for timelapse config updates
_update_callbacks = []
# lock for timelapse cleanup, must be re-entrant
_cleanup_lock = threading.RLock()
# lock for timelapse job
_job_lock = threading.RLock()
def _extract_prefix(filename):
"""
@@ -81,14 +75,10 @@ def get_finished_timelapses():
def get_unrendered_timelapses():
global _job_lock
global current
delete_old_unrendered_timelapses()
basedir = settings().getBaseFolder("timelapse_tmp")
jobs = collections.defaultdict(lambda: dict(count=0, size=None, bytes=0, date=None, timestamp=None))
for osFile in os.listdir(basedir):
if not fnmatch.fnmatch(osFile, "*.jpg"):
continue
@@ -103,37 +93,23 @@ def get_unrendered_timelapses():
if jobs[prefix]["timestamp"] is None or statResult.st_ctime < jobs[prefix]["timestamp"]:
jobs[prefix]["timestamp"] = statResult.st_ctime
with _job_lock:
global current_render_job
def finalize_fields(job):
job["size"] = util.get_formatted_size(job["bytes"])
job["date"] = util.get_formatted_datetime(datetime.datetime.fromtimestamp(job["timestamp"]))
del job["timestamp"]
return job
def finalize_fields(prefix, job):
currently_recording = current is not None and current.prefix == prefix
currently_rendering = current_render_job is not None and current_render_job["prefix"] == prefix
job["size"] = util.get_formatted_size(job["bytes"])
job["date"] = util.get_formatted_datetime(datetime.datetime.fromtimestamp(job["timestamp"]))
job["recording"] = currently_recording
job["rendering"] = currently_rendering
job["processing"] = currently_recording or currently_rendering
del job["timestamp"]
return job
return sorted([util.dict_merge(dict(name=key), finalize_fields(key, value)) for key, value in jobs.items()], key=lambda x: x["name"])
return sorted([util.dict_merge(dict(name=key), finalize_fields(value)) for key, value in jobs.items()], key=lambda x: x["name"])
def delete_unrendered_timelapse(name):
global _cleanup_lock
basedir = settings().getBaseFolder("timelapse_tmp")
with _cleanup_lock:
for filename in os.listdir(basedir):
try:
if fnmatch.fnmatch(filename, "{}*.jpg".format(name)):
os.remove(os.path.join(basedir, filename))
except:
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
logging.getLogger(__name__).exception("Error while processing file {} during cleanup".format(filename))
for filename in os.listdir(basedir):
try:
if fnmatch.fnmatch(filename, "{}*.jpg".format(name)):
os.remove(os.path.join(basedir, filename))
except:
logging.getLogger(__name__).exception("Error while processing file {} during cleanup".format(filename))
def render_unrendered_timelapse(name, gcode=None, postfix=None, fps=25):
@@ -155,65 +131,53 @@ def render_unrendered_timelapse(name, gcode=None, postfix=None, fps=25):
def delete_old_unrendered_timelapses():
global _cleanup_lock
basedir = settings().getBaseFolder("timelapse_tmp")
clean_after_days = settings().getInt(["webcam", "cleanTmpAfterDays"])
cutoff = time.time() - clean_after_days * 24 * 60 * 60
prefixes_to_clean = []
for filename in os.listdir(basedir):
try:
path = os.path.join(basedir, filename)
with _cleanup_lock:
for filename in os.listdir(basedir):
try:
path = os.path.join(basedir, filename)
prefix = _extract_prefix(filename)
if prefix is None:
# might be an old tmp_00000.jpg kinda frame. we can't
# render those easily anymore, so delete that stuff
if _old_capture_format_re.match(filename):
os.remove(path)
continue
prefix = _extract_prefix(filename)
if prefix is None:
# might be an old tmp_00000.jpg kinda frame. we can't
# render those easily anymore, so delete that stuff
if _old_capture_format_re.match(filename):
os.remove(path)
continue
if prefix in prefixes_to_clean:
continue
if prefix in prefixes_to_clean:
continue
if os.path.getmtime(path) < cutoff:
prefixes_to_clean.append(prefix)
except:
logging.getLogger(__name__).exception("Error while processing file {} during cleanup".format(filename))
if os.path.getmtime(path) < cutoff:
prefixes_to_clean.append(prefix)
except:
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
logging.getLogger(__name__).exception("Error while processing file {} during cleanup".format(filename))
for prefix in prefixes_to_clean:
delete_unrendered_timelapse(prefix)
logging.getLogger(__name__).info("Deleted old unrendered timelapse {}".format(prefix))
for prefix in prefixes_to_clean:
delete_unrendered_timelapse(prefix)
def _create_render_start_handler(name, gcode=None):
def f(movie):
global _job_lock
with _job_lock:
global current_render_job
event_payload = {"gcode": gcode if gcode is not None else "unknown",
"movie": movie,
"movie_basename": os.path.basename(movie),
"movie_prefix": name}
current_render_job = dict(prefix=name)
current_render_job.update(event_payload)
global current_render_job
event_payload = {"gcode": gcode if gcode is not None else "unknown",
"movie": movie,
"movie_basename": os.path.basename(movie)}
current_render_job = event_payload
eventManager().fire(Events.MOVIE_RENDERING, event_payload)
return f
def _create_render_success_handler(name, gcode=None):
def f(movie):
delete_unrendered_timelapse(name)
event_payload = {"gcode": gcode if gcode is not None else "unknown",
"movie": movie,
"movie_basename": os.path.basename(movie),
"movie_prefix": name}
"movie_basename": os.path.basename(movie)}
eventManager().fire(Events.MOVIE_DONE, event_payload)
delete_unrendered_timelapse(name)
return f
@@ -221,8 +185,7 @@ def _create_render_fail_handler(name, gcode=None):
def f(movie, returncode=255, stdout="Unknown error", stderr="Unknown error"):
event_payload = {"gcode": gcode if gcode is not None else "unknown",
"movie": movie,
"movie_basename": os.path.basename(movie),
"movie_prefix": name}
"movie_basename": os.path.basename(movie)}
payload = dict(event_payload)
payload.update(dict(returncode=returncode, error=stderr))
eventManager().fire(Events.MOVIE_FAILED, payload)
@@ -232,9 +195,7 @@ def _create_render_fail_handler(name, gcode=None):
def _create_render_always_handler(name, gcode=None):
def f(movie):
global current_render_job
global _job_lock
with _job_lock:
current_render_job = None
current_render_job = None
return f
@@ -303,7 +264,6 @@ class Timelapse(object):
self._image_number = None
self._in_timelapse = False
self._gcode_file = None
self._file_prefix = None
self._post_roll = post_roll
self._on_post_roll_done = None
@@ -330,10 +290,6 @@ class Timelapse(object):
for (event, callback) in self.event_subscriptions():
eventManager().subscribe(event, callback)
@property
def prefix(self):
return self._file_prefix
@property
def post_roll(self):
return self._post_roll
@@ -544,12 +500,12 @@ class ZTimelapse(Timelapse):
def process_post_roll(self):
with self._capture_mutex:
filename = os.path.join(self._capture_dir, _capture_format.format(prefix=self._file_prefix) % self._image_number)
filename = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
self._image_number += 1
if self._perform_capture(filename):
for _ in range(self._post_roll * self._fps):
newFile = os.path.join(self._capture_dir, _capture_format.format(prefix=self._file_prefix) % self._image_number)
newFile = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
self._image_number += 1
shutil.copyfile(filename, newFile)
@@ -594,11 +550,11 @@ class TimedTimelapse(Timelapse):
self._timer.start()
def on_print_done(self, event, payload):
self._postroll_captures = self._post_roll * self._fps
self._postroll_captures = self.post_roll * self.fps
Timelapse.on_print_done(self, event, payload)
def calculate_post_roll(self):
return self._post_roll * self._fps * self._interval
return self.post_roll * self.fps * self.interval
def process_post_roll(self):
pass
File diff suppressed because it is too large. Load diff
+9 -77
View File
@@ -206,7 +206,7 @@ def get_free_bytes(path):
return psutil.disk_usage(path).free
def get_dos_filename(input, existing_filenames=None, extension=None, whitelisted_extensions=None, **kwargs):
def get_dos_filename(origin, existing_filenames=None, extension=None, **kwargs):
"""
Converts the provided input filename to a 8.3 DOS compatible filename. If ``existing_filenames`` is provided, the
conversion result will be guaranteed not to collide with any of the filenames provided thus.
@@ -219,8 +219,6 @@ def get_dos_filename(input, existing_filenames=None, extension=None, whitelisted
Optional.
extension (string): The .3 file extension to use for the generated filename. If not provided, the extension of
the provided ``filename`` will simply be truncated to 3 characters.
whitelisted_extensions (list): A list of extensions on ``input`` that will be left as-is instead of
exchanging for ``extension``.
kwargs (dict): Additional keyword arguments to provide to :func:`find_collision_free_name`.
Returns:
@@ -230,43 +228,16 @@ def get_dos_filename(input, existing_filenames=None, extension=None, whitelisted
Raises:
ValueError: No 8.3 compatible name could be found that doesn't collide with the provided ``existing_filenames``.
Examples:
>>> get_dos_filename("test1234.gco")
u'test1234.gco'
>>> get_dos_filename("test1234.gcode")
u'test1234.gco'
>>> get_dos_filename("test12345.gco")
u'test12~1.gco'
>>> get_dos_filename("test1234.fnord", extension="gco")
u'test1234.gco'
>>> get_dos_filename("auto0.g", extension="gco")
u'auto0.gco'
>>> get_dos_filename("auto0.g", extension="gco", whitelisted_extensions=["g"])
u'auto0.g'
>>> get_dos_filename(None)
>>> get_dos_filename("foo")
u'foo'
"""
if input is None:
if origin is None:
return None
if existing_filenames is None:
existing_filenames = []
if extension is not None:
extension = extension.lower()
if whitelisted_extensions is None:
whitelisted_extensions = []
filename, ext = os.path.splitext(input)
ext = ext.lower()
ext = ext[1:] if ext.startswith(".") else ext
if ext in whitelisted_extensions or extension is None:
filename, ext = os.path.splitext(origin)
if extension is None:
extension = ext
return find_collision_free_name(filename, extension, existing_filenames, **kwargs)
@@ -315,37 +286,10 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power=
Raises:
ValueError: No collision free name could be found.
Examples:
>>> find_collision_free_name("test1234", "gco", [])
u'test1234.gco'
>>> find_collision_free_name("test1234", "gcode", [])
u'test1234.gco'
>>> find_collision_free_name("test12345", "gco", [])
u'test12~1.gco'
>>> find_collision_free_name("test 123", "gco", [])
u'test_123.gco'
>>> find_collision_free_name("test1234", "g o", [])
u'test1234.g_o'
>>> find_collision_free_name("test12345", "gco", ["test12~1.gco"])
u'test12~2.gco'
>>> many_files = ["test12~{}.gco".format(x) for x in range(10)[1:]]
>>> find_collision_free_name("test12345", "gco", many_files)
u'test1~10.gco'
>>> many_more_files = many_files + ["test1~{}.gco".format(x) for x in range(10, 99)]
>>> find_collision_free_name("test12345", "gco", many_more_files)
u'test1~99.gco'
>>> many_more_files_plus_one = many_more_files + ["test1~99.gco"]
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one)
Traceback (most recent call last):
...
ValueError: Can't create a collision free filename
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one, max_power=3)
u'test~100.gco'
"""
# TODO unit test!
if not isinstance(filename, unicode):
filename = unicode(filename)
if not isinstance(extension, unicode):
@@ -358,21 +302,14 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power=
extension = make_valid(extension)
extension = extension[:3] if len(extension) > 3 else extension
full_name_format = u"{filename}.{extension}" if extension else u"{filename}"
result = full_name_format.format(filename=filename,
extension=extension)
if len(filename) <= 8 and not result in existing_filenames:
if len(filename) <= 8 and not filename + "." + extension in existing_filenames:
# early exit
return result
return filename + "." + extension
counter = 1
power = 1
prefix_format = u"{segment}~{counter}"
while counter < (10 ** max_power):
prefix = prefix_format.format(segment=filename[:(6 - power + 1)], counter=str(counter))
result = full_name_format.format(filename=prefix,
extension=extension)
result = filename[:(6 - power + 1)] + "~" + str(counter) + "." + extension
if result not in existing_filenames:
return result
counter += 1
@@ -436,11 +373,6 @@ def to_unicode(s_or_u, encoding="utf-8", errors="strict"):
return s_or_u
def is_running_from_source():
root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
return os.path.isdir(os.path.join(root, "src")) and os.path.isfile(os.path.join(root, "setup.py"))
def dict_merge(a, b):
"""
Recursively deep-merges two dictionaries.
+140 -273
View File
@@ -236,16 +236,6 @@ class MachineCom(object):
except:
pass
self._consecutive_timeouts = 0
self._consecutive_timeout_maximums = dict()
for key, value in settings().get(["serial", "maxCommunicationTimeouts"], merged=True, asdict=True).items():
try:
self._consecutive_timeout_maximums[key] = int(value)
except:
pass
self._max_write_passes = settings().getInt(["serial", "maxWritePasses"])
self._hello_command = settings().get(["serial", "helloCommand"])
self._trigger_ok_for_m29 = settings().getBoolean(["serial", "triggerOkForM29"])
@@ -259,11 +249,10 @@ class MachineCom(object):
self._lastCommError = None
self._lastResendNumber = None
self._currentResendCount = 0
self._resendSwallowNextOk = False
self._resendSwallowRepetitions = settings().getBoolean(["feature", "ignoreIdenticalResends"])
self._resendSwallowRepetitionsCounter = 0
self._supportResendsWithoutOk = settings().getBoolean(["serial", "supportResendsWithoutOk"])
self._resendActive = False
self._terminal_log = deque([], 20)
@@ -273,11 +262,11 @@ class MachineCom(object):
self._log_resends = settings().getBoolean(["serial", "logResends"])
# don't log more resends than 5 / 60s
# don't log more resends than 5 / 10s
self._log_resends_rate_start = None
self._log_resends_rate_count = 0
self._log_resends_max = 5
self._log_resends_rate_frame = 60
self._log_resends_rate_frame = 10
self._long_running_commands = settings().get(["serial", "longRunningCommands"])
self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"])
@@ -332,10 +321,6 @@ class MachineCom(object):
def __del__(self):
self.close()
@property
def _active(self):
return self._monitoring_active and self._send_queue_active
##~~ internal state management
def _changeState(self, newState):
@@ -400,11 +385,11 @@ class MachineCom(object):
if self._state == self.STATE_PAUSED:
return "Paused"
if self._state == self.STATE_CLOSED:
return "Offline"
return "Closed"
if self._state == self.STATE_ERROR:
return "Error: %s" % (self.getErrorString())
if self._state == self.STATE_CLOSED_WITH_ERROR:
return "Offline: %s" % (self.getErrorString())
return "Error: %s" % (self.getErrorString())
if self._state == self.STATE_TRANSFERING_FILE:
return "Transfering file to SD"
return "?%d?" % (self._state)
@@ -580,17 +565,15 @@ class MachineCom(object):
if not processed:
cmd = process_gcode_line(cmd)
if not cmd:
return False
return
if self.isPrinting() and not self.isSdFileSelected():
try:
self._command_queue.put((cmd, cmd_type), item_type=cmd_type)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in command queue: " + e.type)
return False
elif self.isOperational() or force:
return self._sendCommand(cmd, cmd_type=cmd_type)
self._sendCommand(cmd, cmd_type=cmd_type)
def sendGcodeScript(self, scriptName, replacements=None):
context = dict()
@@ -937,8 +920,6 @@ class MachineCom(object):
disable_external_heatup_detection = not settings().getBoolean(["feature", "externalHeatupDetection"])
self._consecutive_timeouts = 0
#Open the serial port.
if not self._openSerial():
return
@@ -974,11 +955,7 @@ class MachineCom(object):
if line is None:
break
if line.strip() is not "":
self._consecutive_timeouts = 0
if self._heating:
self._timeout = get_new_timeout("heatup", self._timeout_intervals)
else:
self._timeout = get_new_timeout("communication", self._timeout_intervals)
self._timeout = get_new_timeout("communication", self._timeout_intervals)
##~~ debugging output handling
if line.startswith("//"):
@@ -1068,20 +1045,12 @@ class MachineCom(object):
if handled and self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_BAUDRATE):
continue
# position report processing
if 'X:' in line and 'Y:' in line and 'Z:' in line:
# currently only here to prevent any "B:"s in a position report from
# triggering temperature processing and being interpreted as a bed
# temperature - can happen with COREXY in current Marlin
#
# see also issue #1373
pass
# temperature processing
elif ' T:' in line or line.startswith('T:') or ' T0:' in line or line.startswith('T0:') or ((' B:' in line or line.startswith('B:')) and not 'A:' in line):
##~~ Temperature processing
if ' T:' in line or line.startswith('T:') or ' T0:' in line or line.startswith('T0:') or ' B:' in line or line.startswith('B:'):
if not disable_external_heatup_detection and not line.strip().startswith("ok") and not self._heating:
self._logger.debug("Externally triggered heatup detected")
self._track_heatup()
self._heating = True
self._heatupWaitStartTime = time.time()
self._processTemperatures(line)
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
@@ -1141,16 +1110,12 @@ class MachineCom(object):
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"
match = regex_sdFileOpened.search(line)
if match:
name = match.group("name")
size = int(match.group("size"))
else:
name = "Unknown"
size = 0
if self._sdFileToSelect:
name = self._sdFileToSelect
self._sdFileToSelect = None
self._currentFile = PrintingSdFileInformation(name, size)
else:
name = match.group("name")
self._currentFile = PrintingSdFileInformation(name, int(match.group("size")))
elif 'File selected' in line:
if self._ignore_select:
self._ignore_select = False
@@ -1190,7 +1155,13 @@ class MachineCom(object):
self._handle_ok()
##~~ Message handling
self._callback.on_comm_message(line)
elif line != '' \
and not line.startswith("ok") \
and not line.startswith("wait") \
and not line.startswith('Resend:') \
and line != 'echo:Unknown command:""\n' \
and self.isOperational():
self._callback.on_comm_message(line)
##~~ Parsing for feedback commands
if feedback_controls and feedback_matcher and not "_all" in feedback_errors:
@@ -1251,7 +1222,6 @@ class MachineCom(object):
elif line.startswith("ok"):
self._onConnected()
elif time.time() > self._timeout:
self._log("There was a timeout while trying to connect to the printer")
self.close()
except:
@@ -1260,8 +1230,8 @@ class MachineCom(object):
errorMsg = "See octoprint.log for details"
self._log(errorMsg)
self._errorValue = errorMsg
self._changeState(self.STATE_ERROR)
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
self.close(is_error=True)
self._log("Connection closed, closing down monitor")
def _handle_ok(self):
@@ -1275,7 +1245,10 @@ class MachineCom(object):
self._currentTool = self._formerTool
self._formerTool = None
self._finish_heatup()
if self._heatupWaitStartTime:
self._heatupWaitTimeLost = self._heatupWaitTimeLost + (time.time() - self._heatupWaitStartTime)
self._heatupWaitStartTime = None
self._heating = False
if not self._state in (self.STATE_PRINTING, self.STATE_OPERATIONAL, self.STATE_PAUSED):
return
@@ -1291,99 +1264,32 @@ class MachineCom(object):
return
def _handle_timeout(self):
if self._state not in (self.STATE_PRINTING,
self.STATE_PAUSED,
self.STATE_OPERATIONAL):
if self._state not in (self.STATE_PRINTING,):
return
if self._long_running_command:
self._logger.debug("Ran into a communication timeout, but a command known to be a long runner is currently active")
return
general_message = "Configure long running commands or increase communication timeout if that happens regularly on specific commands or long moves."
# figure out which consecutive timeout maximum we have to use
if self._long_running_command:
consecutive_max = self._consecutive_timeout_maximums.get("long", 0)
elif self._state in (self.STATE_PRINTING,):
consecutive_max = self._consecutive_timeout_maximums.get("printing", 0)
else:
consecutive_max = self._consecutive_timeout_maximums.get("idle", 0)
# now increment the timeout counter
self._consecutive_timeouts += 1
self._logger.debug("Now at {} consecutive timeouts".format(self._consecutive_timeouts))
if 0 < consecutive_max < self._consecutive_timeouts:
# too many consecutive timeouts, we give up
message = "No response from printer after {} consecutive communication timeouts, considering it dead.".format(consecutive_max + 1)
self._logger.info(message)
self._log(message + " " + general_message)
self._errorValue = "Too many consecutive timeouts, printer still connected and alive?"
eventManager().fire(Events.ERROR, {"error": self._errorValue})
self.close(is_error=True)
elif self._resendActive:
# resend active, resend same command instead of triggering a new one
message = "Communication timeout during an active resend, resending same line again to trigger response from printer."
self._logger.info(message)
self._log(message + " " + general_message)
if self._resendSameCommand():
self._clear_to_send.set()
elif self._heating:
# blocking heatup active, consider that finished
message = "Timeout while in an active heatup, considering heatup to be over."
self._logger.info(message)
self._finish_heatup()
elif self._long_running_command:
# long running command active, ignore timeout
self._logger.debug("Ran into a communication timeout, but a command known to be a long runner is currently active")
elif self._state in (self.STATE_PRINTING, self.STATE_PAUSED):
# printing, try to tickle the printer
message = "Communication timeout while printing, trying to trigger response from printer."
self._logger.info(message)
self._log(message + " " + general_message)
if self._sendCommand("M105", cmd_type="temperature"):
self._clear_to_send.set()
elif self._clear_to_send.blocked():
# timeout while idle and no oks left, let's try to tickle the printer
message = "Communication timeout while idle, trying to trigger response from printer."
self._logger.info(message)
self._log(message + " " + general_message)
if self._resendActive:
self._log("Communication timeout while printing and during an active resend, resending same line again to trigger response from printer. " + general_message)
self._resendSameCommand()
self._clear_to_send.set()
def _track_heatup(self):
self._heating = True
self._heatupWaitStartTime = time.time()
self._serial.timeout = settings().getFloat(["serial", "timeout", "heatup"])
else:
self._log("Communication timeout while printing, trying to trigger response from printer. " + general_message)
self._sendCommand("M105", cmd_type="temperature")
self._clear_to_send.set()
def _finish_heatup(self):
if self._heatupWaitStartTime:
self._heatupWaitTimeLost = self._heatupWaitTimeLost + (time.time() - self._heatupWaitStartTime)
self._heatupWaitStartTime = None
self._heating = False
self._serial.timeout = settings().getFloat(["serial", "timeout", "communication"])
return
def _continue_sending(self):
while self._active:
if self._state == self.STATE_OPERATIONAL or self._state == self.STATE_PAUSED or self.isSdPrinting():
# just send stuff from the command queue and be done with it
return self._sendFromQueue()
elif self._state == self.STATE_PRINTING:
# we are printing, we really want to send either something from the command
# queue or the next line from our file, so we only return here if we actually DO
# send something
if self._sendFromQueue():
# we found something in the queue to send
return True
elif self._sendNext():
# we sent the next line from the file
return True
self._logger.debug("No command sent on ok while printing, doing another iteration")
if self._state == self.STATE_PRINTING:
if not self._sendFromQueue() and not self.isSdPrinting():
self._sendNext()
elif self._state == self.STATE_OPERATIONAL or self._state == self.STATE_PAUSED:
self._sendFromQueue()
def _process_registered_message(self, line, feedback_matcher, feedback_controls, feedback_errors):
feedback_match = feedback_matcher.search(line)
@@ -1678,108 +1584,93 @@ class MachineCom(object):
def _sendNext(self):
with self._sendNextLock:
while self._active:
# we loop until we've actually enqueued a line for sending
line = self._getNext()
if line is None:
# end of file, return false
return False
result = self._sendCommand(line)
line = self._getNext()
if line is not None:
self._sendCommand(line)
self._callback.on_comm_progress()
if result:
# line sent, return true
return True
self._logger.debug("Command \"{}\" from file not enqueued, doing another iteration".format(line))
def _handleResendRequest(self, line):
lineToResend = None
try:
lineToResend = None
try:
lineToResend = int(line.replace("N:", " ").replace("N", " ").replace(":", " ").split()[-1])
except:
if "rs" in line:
lineToResend = int(line.split()[1])
lineToResend = int(line.replace("N:", " ").replace("N", " ").replace(":", " ").split()[-1])
except:
if "rs" in line:
lineToResend = int(line.split()[1])
if lineToResend is None:
return False
if lineToResend is None:
return False
if self._resendDelta is None and lineToResend == self._currentLine:
# We don't expect to have an active resend request and the printer is requesting a resend of
# a line we haven't yet sent.
#
# This means the printer got a line from us with N = self._currentLine - 1 but had already
# acknowledged that. This can happen if the last line was resent due to a timeout during
# an active (prior) resend request.
#
# We will ignore this resend request and just continue normally.
self._logger.debug("Ignoring resend request for line %d == current line, we haven't sent that yet so the printer got N-1 twice from us, probably due to a timeout" % lineToResend)
return False
lastCommError = self._lastCommError
self._lastCommError = None
resendDelta = self._currentLine - lineToResend
if lastCommError is not None \
and ("line number" in lastCommError.lower() or "expected line" in lastCommError.lower()) \
and lineToResend == self._lastResendNumber \
and self._resendDelta is not None and self._currentResendCount < self._resendDelta:
self._logger.debug("Ignoring resend request for line %d, that still originates from lines we sent before we got the first resend request" % lineToResend)
self._currentResendCount += 1
return True
# 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 True
self._resendActive = True
self._resendDelta = resendDelta
self._lastResendNumber = lineToResend
self._currentResendCount = 0
self._resendSwallowRepetitionsCounter = settings().getInt(["feature", "identicalResendsCountdown"])
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._log(self._errorValue)
self._logger.warn(self._errorValue + ". Printer requested line {}, current line is {}, line history has {} entries.".format(lineToResend, self._currentLine, len(self._lastLines)))
if self.isPrinting():
# abort the print, there's nothing we can do to rescue it now
self._changeState(self.STATE_ERROR)
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
else:
# reset resend delta, we can't do anything about it
self._resendDelta = None
# if we log resends, make sure we don't log more resends than the set rate within a window
if self._resendDelta is None and lineToResend == self._currentLine:
# We don't expect to have an active resend request and the printer is requesting a resend of
# a line we haven't yet sent.
#
# this it to prevent the log from getting flooded for extremely bad communication issues
if self._log_resends:
now = time.time()
new_rate_window = self._log_resends_rate_start is None or self._log_resends_rate_start + self._log_resends_rate_frame < now
in_rate = self._log_resends_rate_count < self._log_resends_max
# This means the printer got a line from us with N = self._currentLine - 1 but had already
# acknowledged that. This can happen if the last line was resent due to a timeout during
# an active (prior) resend request.
#
# We will ignore this resend request and just continue normally.
self._logger.debug("Ignoring resend request for line %d == current line, we haven't sent that yet so the printer got N-1 twice from us, probably due to a timeout" % lineToResend)
return False
if new_rate_window or in_rate:
if new_rate_window:
self._log_resends_rate_start = now
self._log_resends_rate_count = 0
lastCommError = self._lastCommError
self._lastCommError = None
self._to_logfile_with_terminal("Got a resend request from the printer: requested line = {}, current line = {}".format(lineToResend, self._currentLine))
self._log_resends_rate_count += 1
resendDelta = self._currentLine - lineToResend
if lastCommError is not None \
and ("line number" in lastCommError.lower() or "expected line" in lastCommError.lower()) \
and lineToResend == self._lastResendNumber \
and self._resendDelta is not None and self._currentResendCount < self._resendDelta:
self._logger.debug("Ignoring resend request for line %d, that still originates from lines we sent before we got the first resend request" % lineToResend)
self._currentResendCount += 1
return True
finally:
if self._supportResendsWithoutOk:
# simulate an ok if our flags indicate that the printer needs that for resend requests to work
self._handle_ok()
# 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 True
self._resendActive = True
self._resendDelta = resendDelta
self._lastResendNumber = lineToResend
self._currentResendCount = 0
self._resendSwallowRepetitionsCounter = settings().getInt(["feature", "identicalResendsCountdown"])
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._log(self._errorValue)
self._logger.warn(self._errorValue + ". Printer requested line {}, current line is {}, line history has {} entries.".format(lineToResend, self._currentLine, len(self._lastLines)))
if self.isPrinting():
# abort the print, there's nothing we can do to rescue it now
self._changeState(self.STATE_ERROR)
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
else:
# reset resend delta, we can't do anything about it
self._resendDelta = None
# if we log resends, make sure we don't log more resends than the set rate within a window
#
# this it to prevent the log from getting flooded for extremely bad communication issues
if self._log_resends:
now = time.time()
new_rate_window = self._log_resends_rate_start is None or self._log_resends_rate_start + self._log_resends_rate_frame < now
in_rate = self._log_resends_rate_count < self._log_resends_max
if new_rate_window or in_rate:
if new_rate_window:
self._log_resends_rate_start = now
self._log_resends_rate_count = 0
self._to_logfile_with_terminal("Got a resend request from the printer: requested line = {}, current line = {}".format(lineToResend, self._currentLine))
self._log_resends_rate_count += 1
return True
def _resendSameCommand(self):
return self._resendNextCommand(again=True)
self._resendNextCommand(again=True)
def _resendNextCommand(self, again=False):
self._lastCommError = None
@@ -1800,7 +1691,7 @@ class MachineCom(object):
cmd = self._lastLines[-self._resendDelta]
lineNumber = self._currentLine - self._resendDelta
result = self._enqueue_for_sending(cmd, linenumber=lineNumber)
self._enqueue_for_sending(cmd, linenumber=lineNumber)
self._resendDelta -= 1
if self._resendDelta <= 0:
@@ -1808,8 +1699,6 @@ class MachineCom(object):
self._lastResendNumber = None
self._currentResendCount = 0
return result
def _sendCommand(self, cmd, cmd_type=None):
# Make sure we are only handling one sending job at a time
with self._sendingLock:
@@ -1830,11 +1719,11 @@ class MachineCom(object):
eventManager().fire(gcodeToEvent[gcode])
# actually enqueue the command for sending
if self._enqueue_for_sending(cmd, command_type=cmd_type):
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
return True
else:
return False
self._enqueue_for_sending(cmd, command_type=cmd_type)
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
return True
##~~ send loop handling
@@ -1850,10 +1739,8 @@ class MachineCom(object):
try:
self._send_queue.put((command, linenumber, command_type), item_type=command_type)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in send queue: " + e.type)
return False
def _send_loop(self):
"""
@@ -2027,46 +1914,24 @@ class MachineCom(object):
return
self._log("Send: " + str(cmd))
cmd += "\n"
written = 0
passes = 0
while written < len(cmd):
to_send = cmd[written:]
old_written = written
try:
self._serial.write(cmd + '\n')
except serial.SerialTimeoutException:
self._log("Serial timeout while writing to serial port, trying again.")
try:
written += self._serial.write(to_send)
except serial.SerialTimeoutException:
self._log("Serial timeout while writing to serial port, trying again.")
try:
written += self._serial.write(to_send)
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(is_error=True)
break
self._serial.write(cmd + '\n')
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(is_error=True)
break
if old_written == written:
# nothing written this pass
passes += 1
if passes > self._max_write_passes:
# nothing written in max consecutive passes, we give up
message = "Could not write anything to the serial port in {} tries, something appears to be wrong with the printer communication".format(self._max_write_passes)
self._logger.error(message)
self._log(message)
self._errorValue = "Could not write to serial port"
self.close(is_error=True)
break
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(is_error=True)
##~~ command handlers
@@ -2152,13 +2017,15 @@ class MachineCom(object):
pass
def _gcode_M109_sent(self, cmd, cmd_type=None):
self._heatupWaitStartTime = time.time()
self._long_running_command = True
self._track_heatup()
self._heating = True
self._gcode_M104_sent(cmd, cmd_type, wait=True)
def _gcode_M190_sent(self, cmd, cmd_type=None):
self._heatupWaitStartTime = time.time()
self._long_running_command = True
self._track_heatup()
self._heating = True
self._gcode_M140_sent(cmd, cmd_type, wait=True)
def _gcode_M110_sending(self, cmd, cmd_type=None):
+53 -137
View File
@@ -14,107 +14,6 @@ import logging
from octoprint.settings import settings
class Vector3D(object):
"""
3D vector value
Supports addition, subtraction and multiplication with a scalar value (float, int) as well as calculating the
length of the vector.
Examples:
>>> a = Vector3D(1.0, 1.0, 1.0)
>>> b = Vector3D(4.0, 4.0, 4.0)
>>> a + b == Vector3D(5.0, 5.0, 5.0)
True
>>> b - a == Vector3D(3.0, 3.0, 3.0)
True
>>> abs(a - b) == Vector3D(3.0, 3.0, 3.0)
True
>>> a * 2 == Vector3D(2.0, 2.0, 2.0)
True
>>> a * 2 == 2 * a
True
>>> a.length == math.sqrt(a.x ** 2 + a.y ** 2 + a.z ** 2)
True
>>> copied_a = Vector3D(a)
>>> a == copied_a
True
>>> copied_a.x == a.x and copied_a.y == a.y and copied_a.z == a.z
True
"""
def __init__(self, *args, **kwargs):
self.x = kwargs.get("x", 0.0)
self.y = kwargs.get("y", 0.0)
self.z = kwargs.get("z", 0.0)
if len(args) == 3:
self.x = args[0]
self.y = args[1]
self.z = args[2]
elif len(args) == 1:
# copy constructor
other = args[0]
if not isinstance(other, Vector3D):
raise ValueError("Object to copy must be a Vector3D instance")
self.x = other.x
self.y = other.y
self.z = other.z
@property
def length(self):
return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
def __add__(self, other):
if isinstance(other, Vector3D):
return Vector3D(self.x + other.x,
self.y + other.y,
self.z + other.z)
elif isinstance(other, (tuple, list)) and len(other) == 3:
return Vector3D(self.x + other[0],
self.y + other[1],
self.z + other[2])
else:
raise ValueError("other must be a Vector3D instance or a list or tuple of length 3")
def __sub__(self, other):
if isinstance(other, Vector3D):
return Vector3D(self.x - other.x,
self.y - other.y,
self.z - other.z)
elif isinstance(other, (tuple, list)) and len(other) == 3:
return Vector3D(self.x - other[0],
self.y - other[1],
self.z - other[2])
else:
raise ValueError("other must be a Vector3D instance or a list or tuple")
def __mul__(self, other):
if isinstance(other, (int, float)):
return Vector3D(self.x * other,
self.y * other,
self.z * other)
else:
raise ValueError("other must be a float or int value")
def __rmul__(self, other):
return self.__mul__(other)
def __abs__(self):
return Vector3D(abs(self.x), abs(self.y), abs(self.z))
def __eq__(self, other):
if not isinstance(other, Vector3D):
return False
return self.x == other.x and self.y == other.y and self.z == other.z
def __str__(self):
return "Vector3D(x={}, y={}, z={}, length={})".format(self.x, self.y, self.z, self.length)
class AnalysisAborted(Exception):
pass
@@ -147,8 +46,8 @@ class gcode(object):
def _load(self, gcodeFile, printer_profile, throttle=None):
filePos = 0
readBytes = 0
pos = Vector3D(0.0, 0.0, 0.0)
posOffset = Vector3D(0.0, 0.0, 0.0)
pos = [0.0, 0.0, 0.0]
posOffset = [0.0, 0.0, 0.0]
currentE = [0.0]
totalExtrusion = [0.0]
maxExtrusion = [0.0]
@@ -157,10 +56,10 @@ class gcode(object):
absoluteE = True
scale = 1.0
posAbs = True
feedrate = min(printer_profile["axes"]["x"]["speed"], printer_profile["axes"]["y"]["speed"])
if feedrate == 0:
feedRateXY = min(printer_profile["axes"]["x"]["speed"], printer_profile["axes"]["y"]["speed"])
if feedRateXY == 0:
# some somewhat sane default if axes speeds are insane...
feedrate = 2000
feedRateXY = 2000
offsets = printer_profile["extruder"]["offsets"]
for line in gcodeFile:
@@ -218,39 +117,56 @@ class gcode(object):
z = getCodeFloat(line, 'Z')
e = getCodeFloat(line, 'E')
f = getCodeFloat(line, 'F')
oldPos = pos
newPos = Vector3D(x if x is not None else pos.x,
y if y is not None else pos.y,
z if z is not None else pos.z)
pos = pos[:]
if posAbs:
pos = newPos * scale + posOffset
if x is not None:
pos[0] = x * scale + posOffset[0]
if y is not None:
pos[1] = y * scale + posOffset[1]
if z is not None:
pos[2] = z * scale + posOffset[2]
else:
pos += newPos * scale
if x is not None:
pos[0] += x * scale
if y is not None:
pos[1] += y * scale
if z is not None:
pos[2] += z * scale
if f is not None and f != 0:
feedrate = f
feedRateXY = f
moveType = 'move'
if e is not None:
if absoluteE:
# make sure e is relative
e -= currentE[currentExtruder]
if e > 0.0:
moveType = 'extrude'
if e < 0.0:
moveType = 'retract'
totalExtrusion[currentExtruder] += e
currentE[currentExtruder] += e
maxExtrusion[currentExtruder] = max(maxExtrusion[currentExtruder],
totalExtrusion[currentExtruder])
if totalExtrusion[currentExtruder] > maxExtrusion[currentExtruder]:
maxExtrusion[currentExtruder] = totalExtrusion[currentExtruder]
else:
e = 0.0
# move time in x, y, z, will be 0 if no movement happened
moveTimeXYZ = abs((oldPos - pos).length / feedrate)
# time needed for extruding, will be 0 if no extrusion happened
extrudeTime = abs(e / feedrate)
# time to add is maximum of both
totalMoveTimeMinute += max(moveTimeXYZ, extrudeTime)
if x is not None or y is not None or z is not None:
diffX = oldPos[0] - pos[0]
diffY = oldPos[1] - pos[1]
totalMoveTimeMinute += math.sqrt(diffX * diffX + diffY * diffY) / feedRateXY
elif moveType == "extrude":
diffX = oldPos[0] - pos[0]
diffY = oldPos[1] - pos[1]
time1 = math.sqrt(diffX * diffX + diffY * diffY) / feedRateXY
time2 = abs(e / feedRateXY)
totalMoveTimeMinute += max(time1, time2)
elif moveType == "retract":
totalMoveTimeMinute += abs(e / feedRateXY)
if moveType == 'move' and oldPos[2] != pos[2]:
if oldPos[2] > pos[2] and abs(oldPos[2] - pos[2]) > 5.0 and pos[2] < 1.0:
oldPos[2] = 0.0
elif G == 4: #Delay
S = getCodeFloat(line, 'S')
if S is not None:
@@ -266,17 +182,17 @@ class gcode(object):
x = getCodeFloat(line, 'X')
y = getCodeFloat(line, 'Y')
z = getCodeFloat(line, 'Z')
center = Vector3D(0.0, 0.0, 0.0)
center = [0.0,0.0,0.0]
if x is None and y is None and z is None:
pos = center
else:
pos = Vector3D(pos)
pos = pos[:]
if x is not None:
pos.x = center.x
pos[0] = center[0]
if y is not None:
pos.y = center.y
pos[1] = center[1]
if z is not None:
pos.z = center.z
pos[2] = center[2]
elif G == 90: #Absolute position
posAbs = True
elif G == 91: #Relative position
@@ -289,11 +205,11 @@ class gcode(object):
if e is not None:
currentE[currentExtruder] = e
if x is not None:
posOffset.x = pos.x - x
posOffset[0] = pos[0] - x
if y is not None:
posOffset.y = pos.y - y
posOffset[1] = pos[1] - y
if z is not None:
posOffset.z = pos.z - z
posOffset[2] = pos[2] - z
elif M is not None:
if M == 82: #Absolute E
@@ -305,13 +221,13 @@ class gcode(object):
if T > settings().getInt(["gcodeAnalysis", "maxExtruders"]):
self._logger.warn("GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis" % T)
else:
posOffset.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
posOffset.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
posOffset[0] -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
posOffset[1] -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
currentExtruder = T
posOffset.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
posOffset.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
posOffset[0] += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
posOffset[1] += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
if len(currentE) <= currentExtruder:
for i in range(len(currentE), currentExtruder + 1):
-68
View File
@@ -4,11 +4,8 @@ from __future__ import absolute_import
__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 logging
import os
from jinja2 import nodes
from jinja2.ext import Extension
from jinja2.loaders import FileSystemLoader, PrefixLoader, ChoiceLoader, \
TemplateNotFound, split_template_path
@@ -109,68 +106,3 @@ def get_all_asset_paths(env):
# intentionally ignored
pass
return result
class ExceptionHandlerExtension(Extension):
tags = {"try"}
def __init__(self, environment):
super(ExceptionHandlerExtension, self).__init__(environment)
self._logger = logging.getLogger(__name__)
def parse(self, parser):
token = parser.stream.next()
lineno = token.lineno
filename = parser.name
error = parser.parse_expression()
args = [error, nodes.Const(filename), nodes.Const(lineno)]
try:
body = parser.parse_statements(["name:endtry"], drop_needle=True)
node = nodes.CallBlock(self.call_method("_handle_body", args),
[], [], body).set_lineno(lineno)
except Exception as e:
# that was expected
self._logger.exception("Caught exception while parsing template")
node = nodes.CallBlock(self.call_method("_handle_error", [nodes.Const(self._format_error(error, e, filename, lineno))]),
[], [], []).set_lineno(lineno)
return node
def _handle_body(self, error, filename, lineno, caller):
try:
return caller()
except Exception as e:
self._logger.exception("Caught exception while compiling template {filename} at line {lineno}".format(**locals()))
error_string = self._format_error(error, e, filename, lineno)
return error_string if error_string else ""
def _handle_error(self, error, caller):
return error if error else ""
def _format_error(self, error, exception, filename, lineno):
if not error:
return ""
try:
return error.format(exception=exception, filename=filename, lineno=lineno)
except:
self._logger.exception("Error while compiling exception output for template {filename} at line {lineno}".format(**locals()))
return "Unknown error"
trycatch = ExceptionHandlerExtension
class MarkdownFilter(object):
def __init__(self, app, **markdown_options):
self._markdown_options = markdown_options
app.jinja_env.filters.setdefault("markdown", self)
def __call__(self, stream):
from jinja2 import Markup
from markdown import Markdown
# Markdown is not thread safe
markdown = Markdown(**self._markdown_options)
return Markup(markdown.convert(stream))
+417
View File
@@ -0,0 +1,417 @@
# coding=utf-8
"""
Unit tests for ``octoprint.util.comm``.
"""
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) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
from collections import deque
import Queue as queue
import re
import time
import threading
import unittest
import mock
import octoprint.util.comm
class FakeBareboneFirmware(object):
def __init__(self, serial_mock):
self.serial_mock = serial_mock
self.serial_mock.readline.side_effect = self.readline
self.serial_mock.write.side_effect = self.write
self.on_receive = None
self.outgoing = queue.Queue()
self.incoming = queue.Queue()
self._written = deque([])
self._read = deque([])
self._conditioned_answers = []
self._produce_read_timeout = 0
self._produce_write_timeout = 0
self._finishing = False
self._receive_lock = threading.Lock()
def produce_read_timeout(self):
self._produce_read_timeout = True
def readline(self):
line = self._get_next_line()
self._read.append(line)
return line
def write(self, data):
with self._receive_lock:
if self._finishing:
return
if self._produce_write_timeout:
self._produce_write_timeout -= 1
if self._produce_write_timeout <= 0:
self._produce_write_timeout = 0
import serial
raise serial.SerialTimeoutException()
self._written.append(data)
self._on_received_data(data)
for condition, lines in self._conditioned_answers:
if callable(condition) and condition(data):
self.return_lines(*lines)
def assert_written(self, *data):
if not data:
return True
all_written = list(self._written)
while all_written:
written = all_written[0]
if written == data[0]:
break
all_written.pop(0)
else:
raise AssertionError("{!r} is not contained in written data".format(data))
return self._check_written(all_written, data)
def assert_written_exactly(self, *data):
if not data:
return True
all_written = list(self._written)
return self._check_written(all_written, data)
def return_lines(self, *lines):
for line in lines:
if not line.endswith("\n"):
line += "\n"
self.outgoing.put(line)
def return_lines_if(self, condition, *lines):
self._conditioned_answers.append((condition, lines))
def finish(self):
self._finishing = True
self.outgoing.join()
def _check_written(self, expected, actual):
zipped = zip(expected, actual)
for a, b in zipped:
assert a == b
return True
def _get_next_line(self):
if self._produce_read_timeout:
self._produce_read_timeout -= 1
if self._produce_read_timeout <= 0:
self._produce_read_timeout = 0
return ""
try:
line = self.outgoing.get(timeout=self.serial_mock.timeout)
self.outgoing.task_done()
return line
except queue.Empty:
return ""
def _on_received_data(self, data):
if callable(self.on_receive):
return self.on_receive(self, data)
return False
class FakeGcodeFirmware(FakeBareboneFirmware):
command_regex = re.compile("^([GMTF])(\d+)")
def __init__(self, serial_mock, simulate_reset=True, require_checksum=False):
FakeBareboneFirmware.__init__(self, serial_mock)
self._require_checksum = require_checksum
self._line_number = 0
if simulate_reset:
self.return_lines("start")
else:
import random
self._line_number = random.randrange(1, stop=2342)
def _on_received_data(self, data):
print("firmware - received data: {!r}".format(data))
if FakeBareboneFirmware._on_received_data(self, data):
return True
data = data.strip()
# strip checksum
if "*" in data:
pos = data.rfind("*")
checksum = int(data[pos+1:])
data = data[:pos]
if checksum != self._get_checksum(data):
self._trigger_resend(checksum_wrong=True)
return True
elif self._require_checksum:
self.return_lines("Error: Missing checksum")
return True
# track line numbers
if "N" in data and "M110" in data:
linenumber = int(re.search("N([0-9]+)", data).group(1))
self._line_number = linenumber
self._trigger_ok()
return True
elif data.startswith("N"):
match = re.search("N([0-9]+)", data)
prefix = match.group(0)
linenumber = int(match.group(1))
expected = self._line_number + 1
if linenumber != expected:
self._trigger_resend(expected=expected, actual=linenumber)
return True
self._line_number = linenumber
data = data[len(prefix):].strip()
if self._process_line(data):
self._trigger_ok()
return True
def _trigger_ok(self):
print("firmware - sending ok")
self.return_lines("ok")
def _trigger_resend(self, checksum_wrong=False, actual=None, expected=None):
if expected is None:
expected = self._line_number + 1
if actual is not None:
print("firmware - Triggering resend for expected line incl. ok")
self.return_lines("Error: expected line {} got {}".format(expected, actual),
"Resend: {}".format(expected),
"ok")
elif checksum_wrong:
print("firmware - Triggering resend for wrong checksum incl. ok")
self.return_lines("Error: Wrong checksum",
"Resend: {}".format(expected),
"ok")
def _process_line(self, line):
command_match = self.command_regex.match(line)
if command_match is None:
return False
command = command_match.group(0)
letter = command_match.group(1)
# if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first
letter_handler = "_gcode_{}".format(letter)
if hasattr(self, letter_handler):
code = command_match.group(2)
handled = getattr(self, letter_handler)(code, line)
if handled:
return False
# then look for a method _gcode_<command> and execute that if it exists
command_handler = "_gcode_{}".format(command)
if hasattr(self, command_handler):
handled = getattr(self, command_handler)(line)
if handled:
return False
return True
@staticmethod
def _get_checksum(line):
checksum = 0
for c in line:
checksum ^= ord(c)
return checksum
class CommCallbackHelper(octoprint.util.comm.MachineComPrintCallback):
def __init__(self):
self._states = deque([])
import threading
self._state_change_event = threading.Event()
def wait_for_state(self, *states, **kwargs):
import octoprint.util.comm
timeout = kwargs.get("timeout", 10)
if not states:
return True
offset = len(self._states)
while True:
if not self._state_change_event.wait(timeout=timeout):
raise AssertionError("Timeout while waiting for any of states {}".format(states))
current_states = list(self._states)[offset:]
if current_states:
current_state = current_states[-1]
if current_state in states:
return True
elif current_state in (octoprint.util.comm.MachineCom.STATE_ERROR,
octoprint.util.comm.MachineCom.STATE_CLOSED_WITH_ERROR,
octoprint.util.comm.MachineCom.STATE_CLOSED):
raise AssertionError("Didn't get any of states {} but an error/a close instead: {}".format(states, current_state))
def on_comm_state_change(self, state):
self._states.append(state)
self._state_change_event.set()
def on_comm_log(self, message):
print("on_comm_log - {:.3f}: {}".format(time.time(), message))
def assert_states(self, *states):
all_states = list(self._states)
while all_states:
state = all_states[0]
if state == states[0]:
break
all_states.pop(0)
else:
raise AssertionError("{!r} is not contained in states".format(states))
return self._check_states(states, all_states)
def assert_states_exactly(self, *states):
all_states = list(self._states)
return self._check_states(states, all_states)
def _check_states(self, expected, actual):
zipped = zip(expected, actual)
for a, b in zipped:
assert a == b
return True
class CommsTestCase(unittest.TestCase):
def setUp(self):
import serial
from octoprint.settings import default_settings
from octoprint.printer.profile import PrinterProfileManager
self.default_settings = default_settings
# mock serial
self.serial_patcher = mock.patch("octoprint.util.comm.serial")
self.serial_module = self.serial_patcher.start()
self.serial_module.Serial = mock.MagicMock()
self.serial = mock.MagicMock(spec=serial.Serial)
def constructor(*args, **kwargs):
self.serial.timeout = kwargs.get("timeout", None)
return self.serial
self.serial_module.Serial.side_effect = constructor
# mock settings
self.settings_patcher = mock.patch("octoprint.util.comm.settings")
settings = self.settings_patcher.start()
self.settings = settings.return_value
self._mock_settings()
# mock plugin manager
self.plugin_manager_patcher = mock.patch("octoprint.plugin.plugin_manager")
self.plugin_manager = self.plugin_manager_patcher.start()
self._mock_hooks()
# mock printer profile manager
self.printer_profile_manager = mock.MagicMock(spec=PrinterProfileManager)
self.printer_profile_manager.get_current_or_default.return_value = dict(heatedBed=False,
extruder=dict(count=1))
# fake firmware
self.firmware = self._create_firmware()
# comm callback helper
self.callback = CommCallbackHelper()
def tearDown(self):
self.plugin_manager_patcher.stop()
self.settings_patcher.stop()
self.serial_patcher.stop()
def _start_comm(self, port, baudrate):
self.comm = octoprint.util.comm.MachineCom(port=port,
baudrate=baudrate,
callbackObject=self.callback,
printerProfileManager=self.printer_profile_manager)
return self.comm
def _stop_comm(self, timeout=10.0):
self.firmware.finish()
self.comm.close(timeout=timeout)
def _wait_for_operational(self, additional=0.0):
self.callback.wait_for_state(octoprint.util.comm.MachineCom.STATE_OPERATIONAL)
time.sleep(additional)
def _create_firmware(self):
return FakeGcodeFirmware(self.serial)
def _mock_hooks(self, hooks=None):
if hooks == None:
hooks = dict()
def get_hooks(hook):
return hooks.get(hook, dict())
self.plugin_manager.return_value.get_hooks.side_effect = get_hooks
def _mock_settings(self, overrides=None):
from octoprint.util import dict_merge
merged = dict_merge(self.default_settings, overrides)
def get(path, *args, **kwargs):
if len(path) == 3 and path[0:2] == ["serial", "timeout"]:
first, second, third = path
if first not in ("serial", "feature"):
return None
return merged[first][second][third]
elif len(path) == 2:
first, second = path
if first not in ("serial", "feature"):
return None
return merged[first][second]
else:
return None
def getBoolean(path, *args, **kwargs):
return get(path, *args, **kwargs)
def getFloat(path, *args, **kwargs):
return get(path, *args, **kwargs)
self.settings.get.side_effect = get
self.settings.getFloat.side_effect = getFloat
self.settings.getBoolean.side_effect = getBoolean
+148
View File
@@ -0,0 +1,148 @@
# coding=utf-8
"""
Unit tests for ``octoprint.util.comm``.
"""
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) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import CommsTestCase, FakeGcodeFirmware
import octoprint.util.comm
import mock
from ddt import ddt, data, unpack
class BasicCommsTest(CommsTestCase):
def _perform_simple_open_test(self, setting_overrides, expected_written_lines, not_written):
# prepare
self._mock_settings(overrides=setting_overrides)
# run
self._start_comm("/dev/ttyUSB0", 115200)
self._wait_for_operational(additional=1.0)
self._stop_comm()
# verify
self.serial_module.Serial.assert_called_once_with("/dev/ttyUSB0",
115200,
timeout=self.default_settings["serial"]["timeout"]["connection"],
writeTimeout=10000,
parity=octoprint.util.comm.serial.PARITY_ODD)
self.assertEquals(self.serial.close.call_count, 2)
self.assertEquals(self.serial.open.call_count, 1)
self.assertEqual(self.serial.parity, octoprint.util.comm.serial.PARITY_NONE)
expected_writes = []
for line in expected_written_lines:
expected_writes.append(mock.call(line + "\n"))
self.serial.write.assert_has_calls(expected_writes, any_order=True)
for line in not_written:
self.assertNotIn(mock.call(line + "\n"), self.serial.write.mock_calls)
@ddt
class BasicCommsResetTest(BasicCommsTest):
@data((dict(feature=dict(sdSupport=True,
sdAlwaysAvailable=False,
waitForStartOnConnect=False)),
["N0 M110 N0*125", # hello from tickling
"N0 M110 N0*125", # hello from start
"N0 M110 N0*125", # line number reset from connected handler
"M21"],
["M20"]), # sd card init from connected handler
# wait for start
(dict(feature=dict(sdSupport=True,
sdAlwaysAvailable=False,
waitForStartOnConnect=True)),
["N0 M110 N0*125", # hello from start
"N0 M110 N0*125", # line number reset from connected handler
"M21"], # sd card init from connected handler
["M20"]), # no M20 (no sd init success message)
# no sd
(dict(feature=dict(sdSupport=False,
sdAlwaysAvailable=False,
waitForStartOnConnect=False)),
["N0 M110 N0*125", # hello from tickling
"N0 M110 N0*125", # hello from start
"N0 M110 N0*125"], # line number reset from connected handler
["M20", "M21"]), # no M20 or M21 (no sd card support)
# no sd, wait for start
(dict(feature=dict(sdSupport=False,
sdAlwaysAvailable=False,
waitForStartOnConnect=True)),
["N0 M110 N0*125", # hello from start
"N0 M110 N0*125"], # line number reset from connected handler
["M20", "M21"]), # no M20 or M21 (no sd card support)
# sd assumed available, wait for start
(dict(feature=dict(sdSupport=True,
sdAlwaysAvailable=True,
waitForStartOnConnect=True)),
["N0 M110 N0*125", # hello from start
"N0 M110 N0*125", # line number reset from connected handler
"M21", # sd init, no response necessary
"M20"], # sd list (init assumed to be done)
[]),
)
@unpack
def test_simple_open(self, setting_overrides, expected_written_lines, not_written):
self._perform_simple_open_test(setting_overrides, expected_written_lines, not_written)
def _create_firmware(self):
return FakeGcodeFirmware(self.serial, simulate_reset=True)
@ddt
class BasicCommsNoResetTest(BasicCommsTest):
@data((dict(feature=dict(sdSupport=True,
sdAlwaysAvailable=False,
waitForStartOnConnect=False)),
["N0 M110 N0*125", # hello from tickling
"N0 M110 N0*125", # line number reset from connected handler
"M21"],
["M20"]), # sd card init from connected handler
# no sd
(dict(feature=dict(sdSupport=False,
sdAlwaysAvailable=False,
waitForStartOnConnect=False)),
["N0 M110 N0*125", # hello from tickling
"N0 M110 N0*125"], # line number reset from connected handler
["M20", "M21"]), # no M20 or M21 (no sd card support)
# no sd
(dict(feature=dict(sdSupport=False,
sdAlwaysAvailable=False,
waitForStartOnConnect=False)),
["N0 M110 N0*125", # hello from tickling
"N0 M110 N0*125"], # line number reset from connected handler
["M20", "M21"]), # no M20 or M21 (no sd card support)
# sd assumed available
(dict(feature=dict(sdSupport=True,
sdAlwaysAvailable=True,
waitForStartOnConnect=False)),
["N0 M110 N0*125", # hello from tickling
"N0 M110 N0*125", # line number reset from connected handler
"M21", # sd init, no response necessary
"M20"], # sd list (init assumed to be done)
[]),
)
@unpack
def test_simple_open(self, setting_overrides, expected_written_lines, not_written):
self._perform_simple_open_test(setting_overrides, expected_written_lines, not_written)
def _create_firmware(self):
return FakeGcodeFirmware(self.serial, simulate_reset=False)
Binary file not shown.
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more