Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6d7f8a2a64 | ||
|
|
8869748ecc | ||
|
|
e0b0f2ae18 | ||
|
|
440ccf165e | ||
|
|
e5caa3d0bf | ||
|
|
a821346b07 | ||
|
|
0ac9ea518c | ||
|
|
9f80aefcc9 | ||
|
|
c1fe8f5a35 | ||
|
|
fcecb5c0f0 | ||
|
|
25005b547c | ||
|
|
dbfe7fece1 | ||
|
|
9c5d996ea2 | ||
|
|
b8e7cfb506 | ||
|
|
822f757f9d | ||
|
|
b04aff7d5e | ||
|
|
028425542f | ||
|
|
339d1df5a9 | ||
|
|
2abe67a24c | ||
|
|
47267abcd1 | ||
|
|
23f130da58 | ||
|
|
9af6b42bdd | ||
|
|
7cb910a69a | ||
|
|
c30db16085 | ||
|
|
832a0c88aa | ||
|
|
972c2823a0 | ||
|
|
f10bfa67ca | ||
|
|
fb834f81ee | ||
|
|
957ba43320 | ||
|
|
133850f61c | ||
|
|
f782cfe83f | ||
|
|
70254e910c | ||
|
|
f981cca47e | ||
|
|
0224037478 | ||
|
|
e4914b8bd3 | ||
|
|
da2c9632ea | ||
|
|
8a3a87efac | ||
|
|
8cdae335a2 | ||
|
|
75ad9aeeb6 | ||
|
|
709f7a76f1 | ||
|
|
c04fade9a7 | ||
|
|
2ecbd9f8c8 | ||
|
|
3e24b68b45 | ||
|
|
46a0c3057f | ||
|
|
902407ed92 | ||
|
|
ccbe9311d7 | ||
|
|
82dffa50f7 | ||
|
|
0d51e5bb1c | ||
|
|
fd7fbcc113 | ||
|
|
5791562c6a | ||
|
|
6582740a1e | ||
|
|
73ce6f43ab | ||
|
|
bc746a49e9 | ||
|
|
e8d5449a8f | ||
|
|
01f5a58709 | ||
|
|
61769262f6 | ||
|
|
faa8174846 | ||
|
|
0eb441058e | ||
|
|
32a31a7d4a | ||
|
|
01bae0c95c | ||
|
|
ada873be1d | ||
|
|
a95407c815 | ||
|
|
e0722e6c28 | ||
|
|
e32aa3f2c8 | ||
|
|
8e764e34ee | ||
|
|
cfb0eb84e2 | ||
|
|
effefffe74 | ||
|
|
8148fd7679 | ||
|
|
f8079c3f50 | ||
|
|
4c3e44d50e | ||
|
|
a2ccf414e6 | ||
|
|
02c42ecdc0 | ||
|
|
c6dfdf8d4b | ||
|
|
10af43285b | ||
|
|
25dc4528af | ||
|
|
bb61bbb2b4 | ||
|
|
e6ec48b8a1 | ||
|
|
98c7ad0c20 | ||
|
|
52bb94e272 | ||
|
|
e0f8ae8986 | ||
|
|
291fa88a82 | ||
|
|
88b622e282 | ||
|
|
3fcd5adfbd | ||
|
|
1f9c9bed42 | ||
|
|
f1401d3f1e | ||
|
|
5216729834 | ||
|
|
bab4782b8c | ||
|
|
eada72a4d9 | ||
|
|
088b4a8059 | ||
|
|
90aa5ed3d4 | ||
|
|
3c8d2f2df5 | ||
|
|
283c44e35e | ||
|
|
125673b846 | ||
|
|
fb6ff04013 | ||
|
|
6a3f1d28fb | ||
|
|
2abff3b589 | ||
|
|
c84f49e852 | ||
|
|
de0660f678 | ||
|
|
ee36e2abd3 | ||
|
|
11eb731b3d | ||
|
|
01d37fc9ee | ||
|
|
59cbfaf8ff | ||
|
|
b8e4ac21d0 | ||
|
|
2db2532c2f | ||
|
|
d42c74d34a | ||
|
|
551d6aab68 | ||
|
|
2c87133f3d | ||
|
|
296af89b02 | ||
|
|
18ad764ef5 | ||
|
|
ec86b3328e | ||
|
|
820ad59539 | ||
|
|
b3fff6e95f | ||
|
|
763888e83a | ||
|
|
c6bb825f7e | ||
|
|
c3ba9c8453 | ||
|
|
a3ba266a6b | ||
|
|
9a8b8d86d5 | ||
|
|
b108fc939c | ||
|
|
40082456c1 | ||
|
|
541844ce3c | ||
|
|
33147b0305 | ||
|
|
55f5c472a0 | ||
|
|
d166bafa8d | ||
|
|
00e6a3856f | ||
|
|
1587ee6402 | ||
|
|
eadb4a5bb6 | ||
|
|
5c63e618b1 | ||
|
|
be3907c7d1 | ||
|
|
8732ec9756 | ||
|
|
7d3d3408eb | ||
|
|
6afb291440 | ||
|
|
522ee49b5b | ||
|
|
de9fdf79c4 | ||
|
|
26dbf59251 | ||
|
|
8ad0aadb52 | ||
|
|
87921061d9 | ||
|
|
6812001639 | ||
|
|
00616a3d73 | ||
|
|
a7a78c11d4 | ||
|
|
60c7974aa4 | ||
|
|
441db2dbbc | ||
|
|
066d3d7422 | ||
|
|
98b71a5870 | ||
|
|
77989d2a76 | ||
|
|
f35fe32a92 | ||
|
|
b79f669351 | ||
|
|
528bd90d02 | ||
|
|
b8d23c8bc1 | ||
|
|
bb822fb9dd | ||
|
|
77aeb6146e | ||
|
|
de253e5086 | ||
|
|
986591aed4 | ||
|
|
48f87b2979 | ||
|
|
ec12bd7cd4 | ||
|
|
b3b19dc136 | ||
|
|
9f1abee023 | ||
|
|
fca7005bfa | ||
|
|
fcf7358855 | ||
|
|
c050bd15ac | ||
|
|
3e236dc57d | ||
|
|
aa0ea299ea | ||
|
|
57a58b3bd7 | ||
|
|
67005577b7 | ||
|
|
b1f9e070a4 | ||
|
|
b5aae0b8fa | ||
|
|
1b5b243760 | ||
|
|
6545f9a816 | ||
|
|
c11288ff65 | ||
|
|
ed70944f69 | ||
|
|
88cb28cec9 | ||
|
|
15c390b199 | ||
|
|
8b09b11faa | ||
|
|
bad3612ed2 | ||
|
|
b079978384 | ||
|
|
13558c01f9 | ||
|
|
ef6b39757b | ||
|
|
2cae028d47 | ||
|
|
86934c8863 | ||
|
|
13eb5ec7ed | ||
|
|
6ce6160f3d | ||
|
|
9bdbb930ad | ||
|
|
03d24ff3b9 |
No files matched your search
+54
-34
@@ -1,29 +1,25 @@
|
||||
<!--
|
||||
READ THE FOLLOWING FIRST:
|
||||
|
||||
If not already done, please read the "guidelines for contributing"
|
||||
aka the Contribution Guidelines that are linked ^-- just up there
|
||||
in the big yellow box.
|
||||
If not already done, please read the the Contribution Guidelines that
|
||||
are linked to the right under "Helpful resources" > "Contributing".
|
||||
|
||||
Also read the FAQ: https://github.com/foosel/OctoPrint/wiki/FAQ.
|
||||
Also read the FAQ: https://faq.octoprint.org
|
||||
|
||||
This is a bug and feature tracker, please only use it to report bugs
|
||||
or request features within OctoPrint (not OctoPi, not any OctoPrint
|
||||
plugins and not unofficial OctoPrint versions).
|
||||
|
||||
Do not seek support here ("I need help with ...", "I have a
|
||||
question ..."), that belongs on the mailing list or the G+ community
|
||||
(both linked in the "guidelines for contributing" linked above, read
|
||||
them!), NOT here.
|
||||
question ..."), that belongs on the community forum at
|
||||
discourse.octoprint.org, NOT here.
|
||||
|
||||
Mark requests with a "[Request]" prefix in the title please. For bug
|
||||
reports fully fill out the bug reporting template (if you don't know
|
||||
where to find some information - it's all described in the Contribution
|
||||
Guidelines linked up there in the big yellow box).
|
||||
|
||||
When reporting a bug do NOT delete ANY lines from the template but
|
||||
those enclosed in [ and ] - and those please DO delete, they are
|
||||
only provided for your information and removing them makes your
|
||||
ticket more readable :)
|
||||
When reporting a bug do NOT delete ANY lines from the template.
|
||||
|
||||
Make sure any bug you want to report is still present with the CURRENT
|
||||
OctoPrint version and that it does not vanish when you start OctoPrint
|
||||
@@ -31,27 +27,26 @@ in safe mode - how to do that is also explained in the Contribution
|
||||
Guidelines linked up there in the big yellow box.
|
||||
|
||||
Thank you!
|
||||
|
||||
(Before submitting your ticket, please delete this text up to and
|
||||
including the line too - it's only here for you, we already know it
|
||||
by heart ;))
|
||||
|
||||
----
|
||||
-->
|
||||
|
||||
#### What were you doing?
|
||||
|
||||
[Please be as specific as possible here. The maintainers will need to
|
||||
<!--
|
||||
Please be as specific as possible here. The maintainers will need to
|
||||
reproduce your issue in order to fix it and that is not possible if they
|
||||
don't know what you did to get it to happen in the first place.
|
||||
|
||||
Ideally provide exact steps to follow in order to reproduce your problem:
|
||||
-->
|
||||
|
||||
1. ...
|
||||
2. ...
|
||||
3. ...
|
||||
|
||||
<!--
|
||||
If you encountered a problem with specific files of any sorts, make sure
|
||||
to also include a link to a file with which to reproduce the problem.]
|
||||
to also include a link to a file with which to reproduce the problem.
|
||||
-->
|
||||
|
||||
#### What did you expect to happen?
|
||||
|
||||
@@ -59,50 +54,75 @@ to also include a link to a file with which to reproduce the problem.]
|
||||
|
||||
#### Did the same happen when running OctoPrint in safe mode?
|
||||
|
||||
[Try to reproduce your problem in safe mode. You can find information
|
||||
on how to enable safe mode in the Contribution Guidelines.]
|
||||
<!--
|
||||
Test if you can reproduce your problem in safe mode. You can find information
|
||||
on how to enable safe mode in the Contribution Guidelines.
|
||||
|
||||
If you can't reproduce in safe mode, this is a bug with one of your
|
||||
installed third party plugins. Don't open a ticket here!
|
||||
|
||||
If you can't test this in safe mode, state why.
|
||||
-->
|
||||
|
||||
#### Version of OctoPrint
|
||||
|
||||
[Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.]
|
||||
<!--
|
||||
Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.
|
||||
-->
|
||||
|
||||
#### Operating System running OctoPrint
|
||||
|
||||
[OctoPi, Linux, Windows, MacOS, something else? With version please.
|
||||
OctoPi's version can be found in /etc/octopi_version]
|
||||
<!--
|
||||
OctoPi, Linux, Windows, MacOS, something else? With version please.
|
||||
OctoPi's version can be found in /etc/octopi_version or in the lower left
|
||||
corner of the web interface.
|
||||
-->
|
||||
|
||||
#### Printer model & used firmware incl. version
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
<!--
|
||||
If applicable, always include if unsure.
|
||||
-->
|
||||
|
||||
#### Browser and Version of Browser, Operating System running Browser
|
||||
#### Browser and version of browser, operating system running browser
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
<!--
|
||||
If applicable, always include if unsure.
|
||||
-->
|
||||
|
||||
#### Link to octoprint.log
|
||||
|
||||
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
|
||||
The Contribution Guidelines tell you where to find that.]
|
||||
<!--
|
||||
On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
|
||||
|
||||
The Contribution Guidelines tell you where to find that.
|
||||
-->
|
||||
|
||||
#### Link to contents of terminal tab or serial.log
|
||||
|
||||
[On gist.github.com or pastebin.com. If applicable, always include if unsure or
|
||||
<!--
|
||||
On gist.github.com or pastebin.com. If applicable, always include if unsure or
|
||||
reporting communication issues. Never truncate.
|
||||
|
||||
serial.log is usually not written due to performance reasons and must be
|
||||
enabled explicitly. Provide at the very least the FULL contents of your
|
||||
terminal tab at the time of the bug occurrence, even if you do not have
|
||||
a serial.log (which the Contribution Guidelines tell you where to find).]
|
||||
a serial.log (which the Contribution Guidelines tell you where to find).
|
||||
-->
|
||||
|
||||
#### Link to contents of Javascript console in the browser
|
||||
|
||||
[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||
<!--
|
||||
On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||
always include if unsure or reporting UI issues.
|
||||
|
||||
The Contribution Guidelines tell you where to find that.]
|
||||
The Contribution Guidelines tell you where to find that.
|
||||
-->
|
||||
|
||||
#### Screenshot(s)/video(s) showing the problem:
|
||||
|
||||
[If applicable. Always include if unsure or reporting UI issues.]
|
||||
<!--
|
||||
If applicable. Always include if unsure or reporting UI issues.
|
||||
-->
|
||||
|
||||
I have read the FAQ.
|
||||
@@ -1,3 +1,4 @@
|
||||
<!--
|
||||
Thank you for your interest into contributing to OctoPrint, it's
|
||||
highly appreciated!
|
||||
|
||||
@@ -7,6 +8,7 @@ as well that contains important information.
|
||||
|
||||
As a summary, please make sure you have ticked all points on this
|
||||
checklist:
|
||||
-->
|
||||
|
||||
* [ ] Your changes are not possible to do through a plugin and relevant
|
||||
to a large audience (ideally all users of OctoPrint)
|
||||
@@ -16,12 +18,13 @@ checklist:
|
||||
Brainstorming ticket
|
||||
* [ ] Your PR targets OctoPrint's devel branch, or maintenance if it's
|
||||
a bug fix for an issue present in the current stable version (no PRs
|
||||
against master or anything else)
|
||||
against master or anything else please)
|
||||
* [ ] Your PR was opened from a custom branch on your repository
|
||||
(no PRs from your version of master, maintenance or devel please),
|
||||
e.g. dev/my_new_feature
|
||||
e.g. dev/my_new_feature or fix/my_bugfix
|
||||
* [ ] Your PR only contains relevant changes: no unrelated files,
|
||||
no dead code, ideally only one commit - rebase your PR if necessary!
|
||||
no dead code, ideally only one commit - rebase and squash your PR
|
||||
if necessary!
|
||||
* [ ] Your changes follow the existing coding style
|
||||
* [ ] If your changes include style sheets: You have modified the
|
||||
.less source files, not the .css files (those are generated with
|
||||
@@ -32,11 +35,10 @@ checklist:
|
||||
nothing broke
|
||||
* [ ] You have added yourself to the AUTHORS.md file :)
|
||||
|
||||
Feel free to delete all this help text, then describe
|
||||
your PR further. You may use the template provided below to do that.
|
||||
The more details the better!
|
||||
|
||||
----
|
||||
<!--
|
||||
Describe your PR further using the template provided below. The more
|
||||
details the better!
|
||||
-->
|
||||
|
||||
#### What does this PR do and why is it necessary?
|
||||
|
||||
|
||||
+9
-8
@@ -7,8 +7,9 @@
|
||||
# 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 and rc shall not use the lookup table, only tags
|
||||
# master, meta, rc and prerelease shall not use the lookup table, only tags
|
||||
master
|
||||
meta/.*
|
||||
rc/.*
|
||||
prerelease
|
||||
|
||||
@@ -16,16 +17,16 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.6
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.7
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
fix/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
improve/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
|
||||
maintenance 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
|
||||
fix/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
|
||||
improve/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.6rc4
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.7rc4
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.6rc4 a8747f7e36a03ff2449b62cdf68b8a26a6fa61b3 pep440-dev
|
||||
regressionfix/.* 1.3.6rc4 a8747f7e36a03ff2449b62cdf68b8a26a6fa61b3 pep440-dev
|
||||
staging/maintenance 1.3.7rc4 9c5d996ea2b66a085392981a5e6e0ee341013674 pep440-dev
|
||||
regressionfix/.* 1.3.7rc4 9c5d996ea2b66a085392981a5e6e0ee341013674 pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
@@ -86,6 +86,7 @@ date of first contribution):
|
||||
* [Peter Backx](https://github.com/pbackx)
|
||||
* [Josh Major](https://github.com/astateofblank)
|
||||
* ["alex-gh"](https://github.com/alex-gh)
|
||||
* [Bernd Zeimetz](https://github.com/bzed)
|
||||
|
||||
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
|
||||
|
||||
+103
@@ -1,5 +1,108 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.3.7 (2018-04-09)
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#324](https://github.com/foosel/OctoPrint/issues/324) & [#2414](https://github.com/foosel/OctoPrint/issues/2414) - Native support for the following [@ commands](http://docs.octoprint.org/en/maintenance/features/atcommands.html): `@pause` (pauses the print), `@resume` (resumes the print), `@cancel` or `@abort` (cancels the print). More commands can be added through the plugin hooks [`octoprint.comm.protocol.atcommand.*`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-atcommand-phase).
|
||||
* [#1951](http://github.com/foosel/OctoPrint/issues/1951) - Fixed plugins being able to modify internal state data (e.g. progress, job), causing concurrent modification and resulting run time errors in the printer state processing.
|
||||
* [#2208](https://github.com/foosel/OctoPrint/issues/2208) - New plugin hook [`octoprint.comm.protocol.gcode.error`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-gcode-error) to allow plugins to override OctoPrint's handling of `Error:`/`!!` messages reported by the firmware. Can be used to "downgrade" errors that aren't actually fatal errors that make the printer halt.
|
||||
* [#2213](https://github.com/foosel/OctoPrint/issues/2213) - Made sure to prevent accidental configuration of a temperature cutoff value less than 1min for the temperature graph.
|
||||
* [#2250](https://github.com/foosel/OctoPrint/pull/2250) - Added [`octoprint.util.ResettableTimer`](http://docs.octoprint.org/en/maintenance/modules/util.html#octoprint.util.ResettableTimer) helper class.
|
||||
* [#2287](https://github.com/foosel/OctoPrint/issues/2287) - Added confirmation for attempting to disconnect during an ongoing print. See also [#2466](https://github.com/foosel/OctoPrint/pull/2466).
|
||||
* [#2302](https://github.com/foosel/OctoPrint/issues/2302) - Detect invalid tools as reported by firmware and blacklist them for `T` commands.
|
||||
* [#2317](https://github.com/foosel/OctoPrint/issues/2317) - Removed capturing of post roll images for time based timelapses, was causing too much confusion and surprise.
|
||||
* [#2335](https://github.com/foosel/OctoPrint/issues/2335) - First throw at detecting if a print from the printer's SD was started outside of OctoPrint via the printer's control panel. Requires some specific requirements to be fulfilled by the printer's firmware to function properly:
|
||||
* Firmware must send a "File opened: ..." message on start of the print
|
||||
* Firmware must respond to an immediately sent `M27` with `SD printing byte <current>/<total>`
|
||||
* Firmware must stay responsive during ongoing print to allow for regular M27 polls (or push those automatically) or M25 to pause/cancel the print through OctoPrint.
|
||||
* Firmware must send `Done printing file` or respond to `M27` with `Not SD printing` when SD printing finishes (either due to being done or to having been cancelled by the user).
|
||||
* [#2362](https://github.com/foosel/OctoPrint/issues/2362) - Added option to configure timelapse snapshot timeout.
|
||||
* [#2367](https://github.com/foosel/OctoPrint/issues/2367) - Added support for `//action:cancel` action command.
|
||||
* [#2378](https://github.com/foosel/OctoPrint/issues/2378) - Made GCODE viewer gracefully handle GCODE subcodes.
|
||||
* [#2385](https://github.com/foosel/OctoPrint/pull/2385) - Made valid boolean trues check case insensitive.
|
||||
* [#2304](https://github.com/foosel/OctoPrint/pull/2304) & [#2405](https://github.com/foosel/OctoPrint/pull/2405) - Added support to trust Basic Authentication headers for user login. Currently requires [manual configuration through `config.yaml`](http://docs.octoprint.org/en/maintenance/configuration/config_yaml.html#access-control), see the `accessControl.trustBasicAuthentication` and `accessControl.checkBasicAuthenticationPassword` settings.
|
||||
* [#2338](https://github.com/foosel/OctoPrint/pull/2338) - Allowed plugins to define GCODE script variables using the `octoprint.comm.protocol.scripts` hook.
|
||||
* [#2406](https://github.com/foosel/OctoPrint/pull/2406) - Extracted log management into its own bundled plugin and allow fine tuning of log levels.
|
||||
* [#2409](https://github.com/foosel/OctoPrint/pull/2409) - Added `m4v` and `mkv` to the list of accepted timelapse extensions.
|
||||
* [#2444](https://github.com/foosel/OctoPrint/pull/2444) - Support additional CSS classes on custom control buttons.
|
||||
* [#2448](https://github.com/foosel/OctoPrint/issues/2448) - Also detect plugins in `~/.octoprint/plugins` that are provided as bytecode `pyc` instead of source `py` files.
|
||||
* [#2455](https://github.com/foosel/OctoPrint/issues/2455) - Added option to configure SSL validation for snapshot URL.
|
||||
* Support `M114` response format of RepRapFirmware (uses `X:... Y:... Z:... E0:... E1:...` instead of
|
||||
`X:... Y:... Z:... E:...`)
|
||||
* Added refresh button to connection panel for easy refresh of the available ports to connect to without having to reload the whole page.
|
||||
* Increased upper bound of PySerial dependency from 2.7 to 3.4. See also [#2333](https://github.com/foosel/OctoPrint/issues/2333).
|
||||
* Switch to lower communication timeouts if support of the `busy` protocol by the firmware is detected.
|
||||
* Refactored serial settings dialog, now has sub tabs and more explanations.
|
||||
* Allow to disable support for certain firmware capabilities, even if reported as supported by the firmware: `busy` protocol, temperature auto reporting, SD status auto reporting
|
||||
* Attached tags to GCODE commands moving through the comm layer and allowed plugins to access and extend these tags through the GCODE hooks. Makes it possible for plugins to detect the origin of a command (streamed file vs. GCODE script vs. user input vs. plugin), the point where it entered the system and so on. Also added a new logger `octoprint.util.comm.command_phases` that if set to `DEBUG` will log the lifecycle of commands through the comm layer including tags to `octoprint.log`. See also [the docs here](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-gcode-phase).
|
||||
* Added new [`job_on_hold`](http://docs.octoprint.org/en/maintenance/modules/printer.html#octoprint.printer.PrinterInterface.job_on_hold) and [`set_job_on_hold`](http://docs.octoprint.org/en/maintenance/modules/printer.html#octoprint.printer.PrinterInterface.set_job_on_hold) methods on the printer instance, allowing plugins to quickly stall the streaming of a queue. This should be used sparingly - abuse will have significant negative effects on the print job. Read the docs if you plan to utilize this.
|
||||
* Support extraction of plugin metadata even from disabled and blacklisted plugins through the AST of the module.
|
||||
* Better logging of printer callback errors and utilization of `frozendict` for internal printer state propagation in an attempt to narrow down on [#1951](https://github.com/foosel/OctoPrint/issues/1951). Should `frozendict` cause issues it can be disabled through the settings in `config.yaml`, just set `devel.useFrozenDictForPrinterState` to `false`
|
||||
* Log comm state changes to `octoprint.log`.
|
||||
* Added a regular server heartbeat to the log (every 15min).
|
||||
* Support SD status auto report by the firmware.
|
||||
* Added `Not SD printing` to default "SD status" terminal filters.
|
||||
* Added custom `readline` implementation for the serial port. Instead of relying on PySerial's `readline` that depending on the installed version might only read from the port one byte at the time, we now wait for one byte and then read everything available into a persistent buffer which then is used to fetch lines from.
|
||||
* Ensure that `callViewModelIf` doesn't try to call null or uncallable `method`s.
|
||||
* Added links to the new [Community Forum](https://discourse.octoprint.org) and the new location of the [FAQ](https://faq.octoprint.org).
|
||||
* Improved pip utility logging, `LocalPipHelper` wasn't producing output, making it hard to debug such non writable install directories.
|
||||
* Added a new bundled plugin "Printer Safety Check" that will try to identify printer/printer firmware with known safety issues such as missing thermal runaway protection.
|
||||
* Plugin Manager: Reduce notification spam. See also [#2260](https://github.com/foosel/OctoPrint/issues/2260).
|
||||
* Software Update Plugin: Better detection if an update is already running.
|
||||
* Software Update Plugin: Refer to `plugin_softwareupdate_console.log` on update errors in log and notification.
|
||||
|
||||
### Bugfixes
|
||||
|
||||
* [#2294](https://github.com/foosel/OctoPrint/issues/2294) - Improved resilience against errors during gathering the file list (e.g. permission errors)
|
||||
* [#2296](https://github.com/foosel/OctoPrint/issues/2296) - Fixed `X-Forwarded-For` handling in Flask Login through monkey patched backport.
|
||||
* [#2297](https://github.com/foosel/OctoPrint/issues/2297) - Return `403` instead of `401` on missing/insufficient credentials.
|
||||
* [#2311](https://github.com/foosel/OctoPrint/issues/2311) - Fixed server not auto connecting on startup if port is set to `AUTO` (see also [#2311](https://github.com/foosel/OctoPrint/pull/2337)).
|
||||
* [#2316](https://github.com/foosel/OctoPrint/issues/2316) - Check for valid queue entry in file analysis queue before trying to dequeue, fix for a HTTP `500` on upload of a file not supported for analysis.
|
||||
* [#2321](https://github.com/foosel/OctoPrint/issues/2321) & [#2449](https://github.com/foosel/OctoPrint/issues/2449) - Fixed wrong queuing order of cancel script & first line from printed file on quick start-cancel-start scenarios by introducing a two new states "Cancelling" and "Pausing".
|
||||
* [#2324](https://github.com/foosel/OctoPrint/pull/2324) - Fixed 500 error when
|
||||
* [#2333](https://github.com/foosel/OctoPrint/issues/2333) (Part 1/3) - Workaround for an update problem caused by interaction of `pip` with dependencies formerly installed as eggs through `python setup.py install`.
|
||||
* [#2333](https://github.com/foosel/OctoPrint/issues/2333) (Part 2/3) - If supported by the underlying PySerial version, cancel all reads and writes on disconnect if possible for a faster connection release. Part 3 (forcing an upgrade of PySerial to 3.4 so this should work in more cases) will in OctoPrint 1.3.8.
|
||||
* [#2364](https://github.com/foosel/OctoPrint/issues/2364) - Fixed firmware error reporting in case of cancelling a print due to a firmware error.
|
||||
* [#2368](https://github.com/foosel/OctoPrint/issues/2368) - Fixed for incorrect handling of unicode filenames in cura slicer profiles
|
||||
* [#2371](https://github.com/foosel/OctoPrint/issues/2371) - Removed "just now"/"gerade eben" label from temperature graph to work around a graph resize issue caused by that.
|
||||
* [#2392](https://github.com/foosel/OctoPrint/issues/2392) - Fixed "Copy all" on terminal tab only working the first time.
|
||||
* [#2406](https://github.com/foosel/OctoPrint/pull/2406) - Fixed `showTab` JS function of about dialog.
|
||||
* [#2426](https://github.com/foosel/OctoPrint/issues/2426) - Made resend logging to `octoprint.log` unicode safe
|
||||
* [#2442](https://github.com/foosel/OctoPrint/issues/2442) - Don't even import disabled plugins, use a dummy entry for them just like for backlisted plugins. More resilience against misbehaving plugins.
|
||||
* [#2461](https://github.com/foosel/OctoPrint/issues/2461) - Fixed OctoPrint not properly disconnecting in case of a firmware error.
|
||||
* [#2494](https://github.com/foosel/OctoPrint/issues/2494) - Fixed `undefined` values not saving in the settings.
|
||||
* [#2499](https://github.com/foosel/OctoPrint/issues/2499) (regression) - Fixed communication error notification lacking the actual error message.
|
||||
* [#2501](https://github.com/foosel/OctoPrint/issues/2501) (regression) - Fixed a bug causing log downloads to fail with an HTTP 500 error.
|
||||
* [#2506](https://github.com/foosel/OctoPrint/issues/2506) (regression) - Fixed `printer.get_current_data` and `printer.get_current_job` returning `frozendict` instead of `dict` instances, causing issues with plugins relying on being able to modify the returned data (e.g. [dattas/OctoPrint-DetailedProgress#26](https://github.com/dattas/OctoPrint-DetailedProgress/issues/26)).
|
||||
* [#2508](https://github.com/foosel/OctoPrint/issues/2508) (regression) - Fixed HTTP 500 error on `/api/slicing` in case of an unconfigured slicer.
|
||||
* [#2524](https://github.com/foosel/OctoPrint/issues/2524) - Ignore `wait` while job is on hold.
|
||||
* [#2536](https://github.com/foosel/OctoPrint/issues/2536) - Fix a wrong state tracking when starting an SD print through the controller, causing a disconnect due to a timeout.
|
||||
* [#2544](https://github.com/foosel/OctoPrint/issues/2544) (regression) - Fix an exception when connecting to the raw websocket at `/sockjs/websocket` (instead of `/sockjs/<server_id>/<session_id>/websocket`).
|
||||
* [#2546](https://github.com/foosel/OctoPrint/issues/2546) (regression) - Fix the `PRINT_FAILED` event getting triggered twice on print failure due to disconnect
|
||||
* Use `pkg_resources` to determine pip version during environment check instead of `import pip; pip.__version__` since the latter causes issues with pip version 9.0.2. In the same spirit make `pip.main` approach of calling `pip` in the PipCaller the last resort during auto detection, only after trying `pip` or `pip.exe` inside the same folder as the Python executable.
|
||||
* Use `octoprint.util.monotonic_time` instead of `monotonic.monotonic` in comm layer.
|
||||
* Fixed timelapse not stopping on print failure due to firmware error due to missing `PrintFailed` event.
|
||||
* Announcement Plugin: Fixed a missing line break in case of more than three announcements in a notification.
|
||||
* Docs: Documentation for printer profile related bits and pieces
|
||||
* Docs: Various fixes of typos and grammar.
|
||||
* Have `OctoPrintJsonEncoder` fall back to regular flask JSON encoder, otherwise we might not be able to serialize some data types we need to be able to serialize. (regression)
|
||||
|
||||
### Known bugs
|
||||
|
||||
* [#2547](https://github.com/foosel/OctoPrint/issues/2547) - Error during processing of afterPrintJobDone script will trigger PRINT_FAILED event even though PRINT_DONE event was already triggered
|
||||
|
||||
### More Information
|
||||
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.6...1.3.7)
|
||||
* Release Candidates:
|
||||
* [1.3.7rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc1)
|
||||
* [1.3.7rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc2)
|
||||
* [1.3.7rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc3)
|
||||
* [1.3.7rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc4)
|
||||
* A special **Thank you!** to everyone who reported back on these release candidates this time:
|
||||
[aaronkeck](https://github.com/aaronkeck), [akurz42](https://github.com/akurz42), [andrivet](https://github.com/andrivet), [anthonyst91](https://github.com/anthonyst91), [arhi](https://github.com/arhi), [b-morgan](https://github.com/b-morgan), [BryanSmithDev](https://github.com/BryanSmithDev), [chippypilot](https://github.com/chippypilot), [ChrisHeerschap](https://github.com/ChrisHeerschap), [Crowlord](https://github.com/Crowlord), [dforsi](https://github.com/dforsi), [drdelaney](https://github.com/drdelaney), [FormerLurker](https://github.com/FormerLurker), [goeland86](https://github.com/goeland86), [inspiredbylife](https://github.com/inspiredbylife), [jbjones27](https://github.com/jbjones27), [jesasi](https://github.com/jesasi), [jneilliii](https://github.com/jneilliii), [JohnOCFII](https://github.com/JohnOCFII), [kantlivelong](https://github.com/kantlivelong), [lnx13](https://github.com/lnx13), [makaper](https://github.com/makaper), [markwal](https://github.com/markwal), [MiquelAdell](https://discourse.octoprint.org/u/MiquelAdell), [ml0w](https://github.com/ml0w), [mmotley999](https://github.com/mmotley999), [mrhanman](https://github.com/mrhanman), [SCiunczyk](https://github.com/SCiunczyk), [tdub415](https://github.com/tdub415), [tedder42](https://discourse.octoprint.org/u/tedder42), [thatjoshguy](https://github.com/thatjoshguy), [wescrockett](https://github.com/wescrockett)
|
||||
|
||||
## 1.3.6 (2017-12-12)
|
||||
|
||||
### Note for upgraders and plugin authors: Change in the bundling of JS assets can lead to issues in plugins
|
||||
|
||||
+143
-115
@@ -21,45 +21,41 @@ or **[creating pull requests](#pull-requests)**.
|
||||
|
||||
## Issues, Tickets, however you may call them
|
||||
|
||||
Please read the following short instructions fully and follow them. You can
|
||||
Please read the following instructions fully and follow them. You can
|
||||
help the project tremendously this way: not only do you help the maintainers
|
||||
to **address problems in a timely manner** but also keep it possible for them
|
||||
to **fix bugs, add new and improve on existing functionality** instead of doing
|
||||
nothing but ticket management.
|
||||
|
||||

|
||||

|
||||
|
||||
- **[Read the FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)**
|
||||
- **[Read the FAQ](https://faq.octoprint.org)**
|
||||
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
|
||||
and *[use the provided template](#what-should-i-include-in-a-ticket)*.
|
||||
You do not need to do anything else with your ticket.
|
||||
- If you want to post a **feature request** or a **documentation request**, add `[Request]`
|
||||
to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup
|
||||
something is **not** what qualifies as a request here, use the
|
||||
[Mailinglist](https://groups.google.com/group/octoprint) or the
|
||||
[Google+ Community](https://plus.google.com/communities/102771308349328485741) for
|
||||
[community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
|
||||
such support issues.
|
||||
- If you are a **developer** that wants to brainstorm a pull request or possible
|
||||
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
|
||||
`[Brainstorming] New plugin hook for doing some cool stuff`).
|
||||
- If you need **support**, have a **question** or some **other reason** that
|
||||
doesn't fit any of the above categories, the issue tracker is not the right place.
|
||||
Consult the [Mailinglist](https://groups.google.com/group/octoprint) or the
|
||||
[Google+ Community](https://plus.google.com/communities/102771308349328485741) instead.
|
||||
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org) instead.
|
||||
|
||||
No matter what kind of ticket you create, never mix two or more "ticket reasons"
|
||||
into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
|
||||
----
|
||||
|
||||
**Note**: A bot is in place that monitors new tickets, automatically
|
||||
categorizes them and checks new bug reports for usage of the provided template.
|
||||
That bot will only bother you if you open a ticket that appears to be a bug (no
|
||||
`[Request]` or `[Brainstorming]` in the title) without the template, and it
|
||||
will do that only to ensure that all information needed to solve the issue is
|
||||
available for the maintainers to directly start tackling that problem.
|
||||
|
||||
----
|
||||
> 👉 **Note**
|
||||
>
|
||||
> A bot is in place that monitors new tickets, automatically
|
||||
> categorizes them and checks new bug reports for usage of the provided template.
|
||||
> That bot will only bother you if you open a ticket that appears to be a bug (no
|
||||
> `[Request]` or `[Brainstorming]` in the title) without the complete template, and it
|
||||
> will do that only to ensure that all information needed to solve the issue is
|
||||
> available for the maintainers to directly start tackling that problem.
|
||||
|
||||
## How to file a bug report
|
||||
|
||||
@@ -72,22 +68,25 @@ following section *completely* and also follow the instructions in the
|
||||
|
||||
### What should I do before submitting a bug report?
|
||||
|
||||
1. **Make sure you are at the right location**. This is the Github repository
|
||||
1. **Make sure you are at the right location**. This is the bug tracker
|
||||
of the official version of OctoPrint, which is the 3D print server and
|
||||
corresponding web interface itself.
|
||||
|
||||
**This is not the Github respository of OctoPi**, which is the preconfigured
|
||||
|
||||
**OctoPrint doesn't manage your network connection or your webcam nor
|
||||
can it fix your printer not getting detected as a serial interface** -
|
||||
if you have any kinds of problems with that, get in touch on the
|
||||
[community forum](https://discourse.octoprint.org).
|
||||
|
||||
**This is not the bug tracker of OctoPi**, which is the preconfigured
|
||||
Raspberry Pi image including OctoPrint among other things - that one can be found
|
||||
[here](https://github.com/guysoft/OctoPi). Please note that while we do have
|
||||
some entries regarding OctoPi in the FAQ, any bugs should be reported in the
|
||||
[proper bug tracker](https://github.com/guysoft/OctoPi/issues) which - again -
|
||||
is not here.
|
||||
[here](https://github.com/guysoft/OctoPi). If you have any kind of specific
|
||||
issue with how the OctoPi system is setup, go there please.
|
||||
|
||||
**This is also not the Github repository of any OctoPrint Plugins you
|
||||
**This is also not the bug tracker of any OctoPrint Plugins you
|
||||
might have installed**. Report any issues with those in their corresponding
|
||||
bug tracker (probably linked to from the plugin's homepage).
|
||||
|
||||
Finally, **this is also not the right issue tracker if you are running a
|
||||
Finally, **this is also not the right bug tracker if you are running a
|
||||
forked version of OctoPrint**. Seek help for such unofficial versions from
|
||||
the people maintaining them instead.
|
||||
|
||||
@@ -101,7 +100,7 @@ following section *completely* and also follow the instructions in the
|
||||
more about safe mode in the [docs](http://docs.octoprint.org/en/master/features/safemode.html).
|
||||
|
||||
You might also want to try the current development version of OctoPrint
|
||||
(if you aren't already). Refer to the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)
|
||||
(if you aren't already). Refer to the [FAQ](https://faq.octoprint.org)
|
||||
for information on how to do this.
|
||||
|
||||
3. The problem still exists? Then please **look through the
|
||||
@@ -111,8 +110,8 @@ following section *completely* and also follow the instructions in the
|
||||
Sorting through duplicates of the same issue sometimes causes more work than
|
||||
fixing it. Take the time to filter through possible duplicates and be really
|
||||
sure that your problem definitely is a new one. Try more than one search query
|
||||
(e.g. do not only search for "webcam" if you happen to run into an issue
|
||||
with your webcam, also search for "timelapse" etc). Do not only read the subject lines
|
||||
(e.g. do not only search for "timelapse" if you happen to run into an issue
|
||||
with your webcam, also search for "recording" etc). Do not only read the subject lines
|
||||
of tickets that look like they might be related, but also read the ticket itself!
|
||||
|
||||
**Very important:** Please make absolutely sure that if you find a bug that looks like
|
||||
@@ -126,84 +125,149 @@ following section *completely* and also follow the instructions in the
|
||||
makes it more difficult due to on top of having to figure out the original problem
|
||||
there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be
|
||||
very diligent here!
|
||||
|
||||
|
||||
If in doubt about any of the above - get in touch on the [community forum](https://discourse.octoprint.org)
|
||||
instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together
|
||||
there.
|
||||
|
||||
### What should I include in a bug report?
|
||||
|
||||
First of all make sure your use **a descriptive title**. "It doesn't work"
|
||||
and similar unspecific complaints are NOT descriptive titles.
|
||||
|
||||
**Always use the following template** (please remove what's within `[...]`, that's
|
||||
only provided here as some additional information for you), **even if only adding a
|
||||
"me too" to an existing ticket**:
|
||||
**Always use the following template, even if only adding a "me too" to an
|
||||
existing ticket**:
|
||||
|
||||
#### What were you doing?
|
||||
```
|
||||
<!--
|
||||
READ THE FOLLOWING FIRST:
|
||||
|
||||
[Please be as specific as possible here. The maintainers will need to
|
||||
reproduce your issue in order to fix it and that is not possible if they
|
||||
don't know what you did to get it to happen in the first place.
|
||||
If not already done, please read the the Contribution Guidelines that
|
||||
are linked to the right under "Helpful resources" > "Contributing".
|
||||
|
||||
Ideally provide exact steps to follow in order to reproduce your problem:
|
||||
Also read the FAQ: https://faq.octoprint.org
|
||||
|
||||
1. ...
|
||||
2. ...
|
||||
3. ...
|
||||
This is a bug and feature tracker, please only use it to report bugs
|
||||
or request features within OctoPrint (not OctoPi, not any OctoPrint
|
||||
plugins and not unofficial OctoPrint versions).
|
||||
|
||||
If you encountered a problem with specific files of any sorts, make sure
|
||||
to also include a link to a file with which to reproduce the problem.]
|
||||
Do not seek support here ("I need help with ...", "I have a
|
||||
question ..."), that belongs on the community forum at
|
||||
discourse.octoprint.org, NOT here.
|
||||
|
||||
#### What did you expect to happen?
|
||||
Mark requests with a "[Request]" prefix in the title please. For bug
|
||||
reports fully fill out the bug reporting template (if you don't know
|
||||
where to find some information - it's all described in the Contribution
|
||||
Guidelines linked up there in the big yellow box).
|
||||
|
||||
#### What happened instead?
|
||||
When reporting a bug do NOT delete ANY lines from the template.
|
||||
|
||||
#### Did the same happen when running OctoPrint in safe mode?
|
||||
Make sure any bug you want to report is still present with the CURRENT
|
||||
OctoPrint version and that it does not vanish when you start OctoPrint
|
||||
in safe mode - how to do that is also explained in the Contribution
|
||||
Guidelines linked up there in the big yellow box.
|
||||
|
||||
[Try to reproduce your problem in safe mode. You can find information
|
||||
on how to enable safe mode in the Contribution Guidelines.]
|
||||
Thank you!
|
||||
-->
|
||||
|
||||
#### Version of OctoPrint
|
||||
#### What were you doing?
|
||||
|
||||
[Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.]
|
||||
<!--
|
||||
Please be as specific as possible here. The maintainers will need to
|
||||
reproduce your issue in order to fix it and that is not possible if they
|
||||
don't know what you did to get it to happen in the first place.
|
||||
|
||||
#### Operating System running OctoPrint
|
||||
Ideally provide exact steps to follow in order to reproduce your problem:
|
||||
-->
|
||||
|
||||
[OctoPi, Linux, Windows, MacOS, something else? With version please,
|
||||
OctoPi's version can be found in /etc/octopi_version]
|
||||
1. ...
|
||||
2. ...
|
||||
3. ...
|
||||
|
||||
#### Printer model & used firmware incl. version
|
||||
<!--
|
||||
If you encountered a problem with specific files of any sorts, make sure
|
||||
to also include a link to a file with which to reproduce the problem.
|
||||
-->
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
#### What did you expect to happen?
|
||||
|
||||
#### Browser and Version of Browser, Operating System running Browser
|
||||
#### What happened instead?
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
#### Did the same happen when running OctoPrint in safe mode?
|
||||
|
||||
#### Link to octoprint.log
|
||||
<!--
|
||||
Test if you can reproduce your problem in safe mode. You can find information
|
||||
on how to enable safe mode in the Contribution Guidelines.
|
||||
|
||||
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
|
||||
The Contribution Guidelines tell you where to find that.]
|
||||
If you can't reproduce in safe mode, this is a bug with one of your
|
||||
installed third party plugins. Don't open a ticket here!
|
||||
|
||||
#### Link to contents of terminal tab or serial.log
|
||||
If you can't test this in safe mode, state why.
|
||||
-->
|
||||
|
||||
[On gist.github.com or pastebin.com. If applicable, always include if unsure or
|
||||
reporting communication issues. Never truncate.
|
||||
#### Version of OctoPrint
|
||||
|
||||
serial.log is usually not written due to performance reasons and must be
|
||||
enabled explicitly. Provide at the very least the FULL contents of your
|
||||
terminal tab at the time of the bug occurrence, even if you do not have
|
||||
a serial.log.]
|
||||
<!--
|
||||
Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.
|
||||
-->
|
||||
|
||||
#### Link to contents of Javascript console in the browser
|
||||
#### Operating System running OctoPrint
|
||||
|
||||
[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||
always include if unsure or reporting UI issues.
|
||||
<!--
|
||||
OctoPi, Linux, Windows, MacOS, something else? With version please.
|
||||
OctoPi's version can be found in /etc/octopi_version or in the lower left
|
||||
corner of the web interface.
|
||||
-->
|
||||
|
||||
The Contribution Guidelines tell you where to find that.]
|
||||
#### Printer model & used firmware incl. version
|
||||
|
||||
#### Screenshot(s)/video(s) showing the problem:
|
||||
<!--
|
||||
If applicable, always include if unsure.
|
||||
-->
|
||||
|
||||
[If applicable. Always include if unsure or reporting UI issues.]
|
||||
#### Browser and version of browser, operating system running browser
|
||||
|
||||
I have read the FAQ.
|
||||
<!--
|
||||
If applicable, always include if unsure.
|
||||
-->
|
||||
|
||||
#### Link to octoprint.log
|
||||
|
||||
<!--
|
||||
On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
|
||||
|
||||
The Contribution Guidelines tell you where to find that.
|
||||
-->
|
||||
|
||||
#### Link to contents of terminal tab or serial.log
|
||||
|
||||
<!--
|
||||
On gist.github.com or pastebin.com. If applicable, always include if unsure or
|
||||
reporting communication issues. Never truncate.
|
||||
|
||||
serial.log is usually not written due to performance reasons and must be
|
||||
enabled explicitly. Provide at the very least the FULL contents of your
|
||||
terminal tab at the time of the bug occurrence, even if you do not have
|
||||
a serial.log (which the Contribution Guidelines tell you where to find).
|
||||
-->
|
||||
|
||||
#### Link to contents of Javascript console in the browser
|
||||
|
||||
<!--
|
||||
On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||
always include if unsure or reporting UI issues.
|
||||
|
||||
The Contribution Guidelines tell you where to find that.
|
||||
-->
|
||||
|
||||
#### Screenshot(s)/video(s) showing the problem:
|
||||
|
||||
<!--
|
||||
If applicable. Always include if unsure or reporting UI issues.
|
||||
-->
|
||||
|
||||
I have read the FAQ.
|
||||
```
|
||||
|
||||
Copy-paste this template **completely** (or use the version that gets pre-filled
|
||||
into the "new issue" form). Do not skip any lines or the bot *will* complain! Provide
|
||||
@@ -211,50 +275,11 @@ all requested information or your ticket will be closed.
|
||||
|
||||
### Where can I find which version and branch I'm on?
|
||||
|
||||
You can find out all of them by taking a look into the lower left corner of the
|
||||
OctoPrint UI:
|
||||
|
||||

|
||||
|
||||
If you don't have access to the UI you can find out that information via the
|
||||
command line as well. Either `octoprint --version` or `python setup.py version`
|
||||
in OctoPrint's folder will tell you the version of OctoPrint you are running
|
||||
(note: if it doesn't then you are running a version older than 1.1.0,
|
||||
*upgrade now*). A `git branch` in your OctoPrint installation folder will mark
|
||||
the branch you are on with a little *. `git rev-parse HEAD` will tell you the
|
||||
current commit.
|
||||
Please refer to [this FAQ entry](https://discourse.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1).
|
||||
|
||||
### Where can I find those log files you keep talking about?
|
||||
|
||||
OctoPrint by default provides two log outputs, a third one can be enabled if
|
||||
more information is needed.
|
||||
|
||||
One is contained in the **"Terminal" tab** within OctoPrint's UI and is a log
|
||||
of the last 300 lines of communication with the printer. Please copy-paste
|
||||
this *completely* somewhere (disable auto scroll to make copying the contents easier) -
|
||||
e.g. http://pastebin.com or http://gist.github.com - and include a link in
|
||||
your bug report.
|
||||
|
||||
There is also **OctoPrint's application log file** or in short `octoprint.log`,
|
||||
which is by default located at `~/.octoprint/logs/octoprint.log` on Linux,
|
||||
`%APPDATA%\OctoPrint\logs\octoprint.log` on Windows and
|
||||
`~/Library/Application Support/OctoPrint/logs/octoprint.log` on MacOS. You can
|
||||
also access it directly through OctoPrint via Settings > Logs. Please
|
||||
copy-paste this *completely* to pastebin or gist as well and include a link in your bug
|
||||
report.
|
||||
|
||||
It might happen that you are asked to provide a more **thorough log of the
|
||||
communication with the printer** if you haven't already done so, the `serial.log`.
|
||||
This is not written by default due to performance reasons, but you can enable
|
||||
it in the settings dialog. After enabling that log, please reproduce the problem
|
||||
again (connect to the printer, do whatever triggers it), then copy-paste
|
||||
`~/.octoprint/logs/serial.log` (Windows: `%APPDATA%\OctoPrint\logs\serial.log`,
|
||||
MacOS: `~/Library/Application Support/OctoPrint/logs/serial.log`) to pastebin
|
||||
or gist and include the link in the bug report.
|
||||
|
||||
You might also be asked to provide a log with an increased log level. You can
|
||||
find information on how to do just that in the
|
||||
[docs](http://docs.octoprint.org/en/master/configuration/logging_yaml.html).
|
||||
Please refer to [this FAQ entry](https://discourse.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1).
|
||||
|
||||
### Where can I find my browser's error console?
|
||||
|
||||
@@ -445,6 +470,9 @@ the local version identifier to allow for an exact determination of the active c
|
||||
by OctoPrint itself and not a misbehaving plugin.
|
||||
* 2017-03-27: Added safe mode section to ticket template.
|
||||
* 2017-11-22: Added note on how to run the unit tests
|
||||
* 2018-03-15: Link to new community forum and some clarifications re bug
|
||||
reporting
|
||||
* 2018-03-29: "Where to find version numbers" is now located on the FAQ
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
|
||||
@@ -7,6 +7,10 @@ and released under the [GNU Affero General Public License V3](http://www.gnu.org
|
||||
|
||||
Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The community forum is available at [discourse.octoprint.org](https://discourse.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The FAQ can be accessed by following [faq.octoprint.org](https://faq.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
|
||||
|
||||
The official plugin repository can be reached at [plugins.octoprint.org](https://plugins.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
@@ -19,17 +23,17 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!**
|
||||
You are currently looking at the source code repository of OctoPrint. If you already installed it
|
||||
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
|
||||
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
|
||||
might be of more interest for you. You might also want to subscribe to [the mailing list](https://groups.google.com/group/octoprint)
|
||||
or the [G+ Community](https://plus.google.com/communities/102771308349328485741) where there are other active users who might be
|
||||
might be of more interest for you. You might also want to subscribe to join
|
||||
[the community forum at discourse.octoprint.org](https://discourse.octoprint.org) where there are other active users who might be
|
||||
able to help you with any questions you might have.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
|
||||
[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](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
|
||||
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help
|
||||
in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
|
||||
[the community forum at discourse.octoprint.org](https://discourse.octoprint.org)
|
||||
and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
|
||||
|
||||
If you think something is bad 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
|
||||
@@ -54,23 +58,20 @@ you already have Python 2.7, pip and virtualenv set up on your system:
|
||||
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
|
||||
2. Change into the OctoPrint folder: `cd OctoPrint`
|
||||
3. Create a user-owned virtual environment therein: `virtualenv venv`
|
||||
4. Install OctoPrint *into that virtual environment*: `./venv/bin/python setup.py install`
|
||||
4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .`
|
||||
|
||||
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
|
||||
for details.
|
||||
|
||||
After installation, please make sure you follow the first-run wizard and set up
|
||||
access control as necessary. If you want to not only be notified about new
|
||||
releases, but also be able to automatically upgrade to them from within
|
||||
OctoPrint, take a look [at the documentation of the Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#making-octoprint-updateable-on-existing-installations)
|
||||
and at its settings.
|
||||
access control as necessary.
|
||||
|
||||
## Dependencies
|
||||
|
||||
OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing
|
||||
OctoPrint via `setup.py`:
|
||||
OctoPrint via `pip`:
|
||||
|
||||
python setup.py install
|
||||
pip install .
|
||||
|
||||
You should do this every time after pulling from the repository, since the dependencies may have changed.
|
||||
|
||||
@@ -78,9 +79,9 @@ OctoPrint currently only supports Python 2.7.
|
||||
|
||||
## Usage
|
||||
|
||||
Running the `setup.py` script via
|
||||
Running the pip install via
|
||||
|
||||
python setup.py install
|
||||
pip install .
|
||||
|
||||
installs the `octoprint` script in your Python installation's scripts folder
|
||||
(which, depending on whether you installed OctoPrint globally or into a virtual env, will be in your `PATH` or not). The
|
||||
|
||||
+8
-11
@@ -6,17 +6,13 @@ thanks to everyone who contributed!
|
||||
|
||||
## Patreon Patrons
|
||||
|
||||
* 3D Moniak
|
||||
* Aleph Objects, Inc.
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
* BEEVERYCREATIVE
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brian E. Tyler
|
||||
* Christian Petropolis
|
||||
* COLLE+McVOY
|
||||
* CreativeTools
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* E3D BigBox
|
||||
@@ -24,19 +20,21 @@ thanks to everyone who contributed!
|
||||
* F. Kunsmann
|
||||
* Frank Sander
|
||||
* Gary Deen
|
||||
* Gary N McKinney
|
||||
* George Robles
|
||||
* günter weber
|
||||
* James Seigel
|
||||
* Jason Lawrence
|
||||
* Jeff Moe
|
||||
* Jeff Renfer
|
||||
* Jefferson Hunt
|
||||
* Jeremiah Avery
|
||||
* Josh Daniels
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Kodama Inc.
|
||||
* LulzBot®
|
||||
* Makespace Madrid
|
||||
* Marcus Ackermann
|
||||
* Mark Walker
|
||||
* Martin Beattie
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* mitchell hirsch
|
||||
@@ -44,8 +42,8 @@ thanks to everyone who contributed!
|
||||
* Noe Ruiz
|
||||
* Patrick McGinnis
|
||||
* Peter Schmehl
|
||||
* PRINT3Dforum.com
|
||||
* Randy C. Will
|
||||
* Robert Gusek
|
||||
* Roger Strolz
|
||||
* Roy Cortes
|
||||
* Samer Najia
|
||||
@@ -55,7 +53,6 @@ thanks to everyone who contributed!
|
||||
* Sven Mueller
|
||||
* Symbiotic Devices
|
||||
* Thomas Hatley
|
||||
* Timeshell.ca
|
||||
* Trent Shumay
|
||||
|
||||
and 1062 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1233 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
@@ -44,6 +44,14 @@ Printer State
|
||||
- 1
|
||||
- Boolean
|
||||
- ``true`` if the printer is currently printing, ``false`` otherwise
|
||||
* - ``flags.pausing``
|
||||
- 1
|
||||
- Boolean
|
||||
- ``true`` if the printer is currently printing and in the process of pausing, ``false`` otherwise
|
||||
* - ``flags.cancelling``
|
||||
- 1
|
||||
- Boolean
|
||||
- ``true`` if the printer is currently printing and in the process of pausing, ``false`` otherwise
|
||||
* - ``flags.sdReady``
|
||||
- 1
|
||||
- Boolean
|
||||
|
||||
@@ -12,7 +12,7 @@ Authorization
|
||||
=============
|
||||
|
||||
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
|
||||
configured one, a user specific one if "Access Control" is enabled or an ref:`App Session Key <sec-api-apps-sessionkey>`.
|
||||
configured one, a user specific one if "Access Control" is enabled or an :ref:`App Session Key <sec-api-apps-sessionkey>`.
|
||||
Users are able to generate and revoke their custom API key via the "Change password" dialog.
|
||||
|
||||
The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
@@ -65,7 +65,7 @@ Please be advised that clients should use the header field variant if at all pos
|
||||
Content Type
|
||||
============
|
||||
|
||||
If not otherwise stated OctoPrint's API expects request bodies and issues response bodies as ``Content-Type: application/json``.
|
||||
If not otherwise stated, OctoPrint's API expects request bodies and issues response bodies as ``Content-Type: application/json``.
|
||||
|
||||
.. _sec-api-general-encoding:
|
||||
|
||||
|
||||
+5
-168
@@ -4,172 +4,9 @@
|
||||
Log file management
|
||||
*******************
|
||||
|
||||
.. note::
|
||||
Log file management (and logging configuration) was moved into a bundled plugin in OctoPrint 1.3.7. Refer to
|
||||
:ref:`the Logging's plugins API <sec-bundledplugins-logging-api>` for the API documentation.
|
||||
|
||||
All log file management operations require admin rights.
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-logs-list:
|
||||
|
||||
Retrieve a list of available log files
|
||||
======================================
|
||||
|
||||
.. http:get:: /api/logs
|
||||
|
||||
Retrieve information regarding all log files currently available and regarding the disk space still available
|
||||
in the system on the location the log files are being stored.
|
||||
|
||||
Returns a :ref:`Logfile Retrieve response <sec-api-logs-datamodel-retrieveresponse>`.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/logs HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"files" : [
|
||||
{
|
||||
"date" : 1393158814,
|
||||
"name" : "octoprint.log",
|
||||
"size" : 43712,
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/logs/octoprint.log",
|
||||
"download": "http://example.com/downloads/logs/octoprint.log"
|
||||
}
|
||||
},
|
||||
{
|
||||
"date" : 1392628936,
|
||||
"name" : "octoprint.log.2014-02-17",
|
||||
"size" : 13205,
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/logs/octoprint.log.2014-02-17",
|
||||
"download": "http://example.com/downloads/logs/octoprint.log.2014-02-17"
|
||||
}
|
||||
},
|
||||
{
|
||||
"date" : 1393158814,
|
||||
"name" : "serial.log",
|
||||
"size" : 1798419,
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/logs/serial.log",
|
||||
"download": "http://example.com/downloads/logs/serial.log"
|
||||
}
|
||||
}
|
||||
],
|
||||
"free": 12237201408
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
:statuscode 403: If the given API token did not have admin rights associated with it
|
||||
|
||||
.. _sec-api-logs-delete:
|
||||
|
||||
Delete a specific logfile
|
||||
=========================
|
||||
|
||||
.. http:delete:: /api/logs/(path:filename)
|
||||
|
||||
Delete the selected log file with name `filename`.
|
||||
|
||||
Returns a :http:statuscode:`204` after successful deletion.
|
||||
|
||||
**Example Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
DELETE /api/logs/octoprint.log.2014-02-17 HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
:param filename: The filename of the log file to delete
|
||||
:statuscode 204: No error
|
||||
:statuscode 403: If the given API token did not have admin rights associated with it
|
||||
:statuscode 404: If the file was not found
|
||||
|
||||
.. _sec-api-logs-datamodel:
|
||||
|
||||
Data model
|
||||
==========
|
||||
|
||||
.. _sec-api-logs-datamodel-retrieveresponse:
|
||||
|
||||
Logfile Retrieve Response
|
||||
-------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``files``
|
||||
- 0..*
|
||||
- Array of :ref:`File information items <sec-api-logs-datamodel-fileinfo>`
|
||||
- The list of requested files. Might be an empty list if no files are available
|
||||
* - ``free``
|
||||
- 1
|
||||
- String
|
||||
- The amount of disk space in bytes available in the local disk space (refers to OctoPrint's ``logs`` folder).
|
||||
|
||||
.. _sec-api-logs-datamodel-fileinfo:
|
||||
|
||||
File information
|
||||
----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- String
|
||||
- The name of the file
|
||||
* - ``size``
|
||||
- 1
|
||||
- Number
|
||||
- The size of the file in bytes.
|
||||
* - ``date``
|
||||
- 1
|
||||
- Unix timestamp
|
||||
- The timestamp when this file was last modified.
|
||||
* - ``refs``
|
||||
- 1
|
||||
- :ref:`sec-api-logs-datamodel-ref`
|
||||
- References relevant to this file
|
||||
|
||||
.. _sec-api-logs-datamodel-ref:
|
||||
|
||||
References
|
||||
----------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``resource``
|
||||
- 1
|
||||
- URL
|
||||
- The resource that represents the file (e.g. for deleting)
|
||||
* - ``download``
|
||||
- 1
|
||||
- URL
|
||||
- The download URL for the file
|
||||
The former endpoints ``/api/logs`` and ``api/logs/<path>`` are marked as deprecated but still work for now. New
|
||||
client implementations should directly use the new endpoints provided by the bundled plugin. Existing implementations
|
||||
should adapt their endpoints as soon as possible.
|
||||
@@ -149,6 +149,8 @@ Retrieve the current printer state
|
||||
"operational": true,
|
||||
"paused": false,
|
||||
"printing": false,
|
||||
"cancelling": false,
|
||||
"pausing": false,
|
||||
"sdReady": true,
|
||||
"error": false,
|
||||
"ready": true,
|
||||
@@ -179,6 +181,8 @@ Retrieve the current printer state
|
||||
"operational": true,
|
||||
"paused": false,
|
||||
"printing": false,
|
||||
"cancelling": false,
|
||||
"pausing": false,
|
||||
"sdReady": true,
|
||||
"error": false,
|
||||
"ready": true,
|
||||
@@ -213,7 +217,7 @@ Issue a print head command
|
||||
* ``z``: Optional. Amount/coordinate to jog print head on z axis, must be a valid number corresponding to the distance to travel in mm.
|
||||
* ``absolute``: Optional. Boolean value specifying whether to move relative to current position (provided
|
||||
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
|
||||
* ``speed``: Optiona. Speed at which to move. If not provided, minimum speed for all selected axes from printer
|
||||
* ``speed``: Optional. Speed at which to move. If not provided, minimum speed for all selected axes from printer
|
||||
profile will be used. If provided but ``false``, no speed parameter will be appended to the command. Otherwise
|
||||
interpreted as an integer signifying the speed in mm/s, to append to the command.
|
||||
|
||||
@@ -223,7 +227,7 @@ Issue a print head command
|
||||
* ``axes``: A list of axes which to home, valid values are one or more of ``x``, ``y``, ``z``.
|
||||
|
||||
feedrate
|
||||
Changes the feedrate factor to apply to the movement's of the axes.
|
||||
Changes the feedrate factor to apply to the movements of the axes.
|
||||
|
||||
* ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 50 and 200%.
|
||||
|
||||
|
||||
+1
-1
@@ -139,7 +139,7 @@ Execute a registered system command
|
||||
|
||||
.. http:post:: /api/system/commands/(string:source)/(string:action)
|
||||
|
||||
Execute the system command ``action`` on defined in ``source``.
|
||||
Execute the system command ``action`` defined in ``source``.
|
||||
|
||||
**Example**
|
||||
|
||||
|
||||
@@ -128,7 +128,7 @@ Rendered timelapse
|
||||
* - ``date``
|
||||
- 1
|
||||
- string
|
||||
- Formatted timestamp of the the timelapse creation date
|
||||
- Formatted timestamp of the timelapse creation date
|
||||
* - ``url``
|
||||
- 1
|
||||
- string
|
||||
@@ -162,7 +162,7 @@ Unrendered timelapse
|
||||
* - ``date``
|
||||
- 1
|
||||
- string
|
||||
- Formatted timestamp of the the timelapse job creation date
|
||||
- Formatted timestamp of the timelapse job creation date
|
||||
* - ``recording``
|
||||
- 1
|
||||
- bool
|
||||
|
||||
+4
-2
@@ -38,13 +38,15 @@ Test paths or URLs
|
||||
.. _sec-api-util-test-url:
|
||||
|
||||
url
|
||||
Tests whether a provided url responds. Request method and expected status codes can
|
||||
Tests whether a provided URL responds. Request method and expected status codes can
|
||||
optionally be specified as well. Supported parameters are:
|
||||
|
||||
* ``url``: The url to test. Mandatory.
|
||||
* ``url``: The URL to test. Mandatory.
|
||||
* ``method``: The request method to use for the test. Optional, defaults to ``HEAD``.
|
||||
* ``timeout``: A timeout for the request, in seconds. If no reply from the tested URL has been
|
||||
received within this time frame, the check will be considered a failure. Optional, defaults to 3 seconds.
|
||||
* ``validSsl``: Whether to validate the SSL connection if the ``url`` happens to be an HTTPS URL or not. Optional,
|
||||
defaults to ``True``.
|
||||
* ``status``: The status code(s) or named status range(s) to test for. Can be either a single
|
||||
value or a list of either HTTP status codes or any of the following named status ranges:
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
.. _sec-bundledplugins_cura:
|
||||
.. _sec-bundledplugins-cura:
|
||||
|
||||
Cura
|
||||
====
|
||||
|
||||
@@ -9,5 +9,7 @@ Bundled Plugins
|
||||
|
||||
cura.rst
|
||||
discovery.rst
|
||||
logging.rst
|
||||
pluginmanager.rst
|
||||
printer_safety_check.rst
|
||||
softwareupdate.rst
|
||||
@@ -0,0 +1,238 @@
|
||||
.. _sec-bundledplugins-logging:
|
||||
|
||||
Logging
|
||||
=======
|
||||
|
||||
The OctoPrint Logging plugin comes bundled with OctoPrint starting with version 1.3.7.
|
||||
|
||||
It implements the log management functionality that was formerly part of the core application and adds features to
|
||||
configure logging levels for sub modules through the included settings dialog.
|
||||
|
||||
.. _fig-bundledplugins-logging-settings:
|
||||
.. figure:: ../images/bundledplugins-logging-settings.png
|
||||
:align: center
|
||||
:alt: Logging plugin
|
||||
|
||||
The settings dialog of the Logging plugin
|
||||
|
||||
.. _sec-bundledplugins-logging-api:
|
||||
|
||||
API
|
||||
---
|
||||
|
||||
.. note::
|
||||
|
||||
All log file management operations require admin rights.
|
||||
|
||||
.. _sec-bundledplugins-logging-api-list_logs:
|
||||
|
||||
Retrieve a list of available log files
|
||||
++++++++++++++++++++++++++++++++++++++
|
||||
|
||||
.. http:get:: /plugin/logging/logs
|
||||
|
||||
Retrieve information regarding all log files currently available and regarding the disk space still available
|
||||
in the system on the location the log files are being stored.
|
||||
|
||||
Returns a :ref:`Logfile Retrieve response <sec-bundledplugins-logging-api-datamodel-retrieveresponse>`.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /plugin/logging/logs HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"files" : [
|
||||
{
|
||||
"date" : 1393158814,
|
||||
"name" : "octoprint.log",
|
||||
"size" : 43712,
|
||||
"refs": {
|
||||
"resource": "http://example.com/plugin/logging/logs/octoprint.log",
|
||||
"download": "http://example.com/downloads/logs/octoprint.log"
|
||||
}
|
||||
},
|
||||
{
|
||||
"date" : 1392628936,
|
||||
"name" : "octoprint.log.2014-02-17",
|
||||
"size" : 13205,
|
||||
"refs": {
|
||||
"resource": "http://example.com/plugin/logging/logs/octoprint.log.2014-02-17",
|
||||
"download": "http://example.com/downloads/logs/octoprint.log.2014-02-17"
|
||||
}
|
||||
},
|
||||
{
|
||||
"date" : 1393158814,
|
||||
"name" : "serial.log",
|
||||
"size" : 1798419,
|
||||
"refs": {
|
||||
"resource": "http://example.com/plugin/logging/logs/serial.log",
|
||||
"download": "http://example.com/downloads/logs/serial.log"
|
||||
}
|
||||
}
|
||||
],
|
||||
"free": 12237201408
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
:statuscode 403: If the given API token did not have admin rights associated with it
|
||||
|
||||
.. _sec-bundledplugins-logging-api-delete_logs:
|
||||
|
||||
Delete a specific logfile
|
||||
+++++++++++++++++++++++++
|
||||
|
||||
.. http:delete:: /plugin/logging/logs/(path:filename)
|
||||
|
||||
Delete the selected log file with name `filename`.
|
||||
|
||||
Returns a :http:statuscode:`204` after successful deletion.
|
||||
|
||||
**Example Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
DELETE /plugin/logging/logs/octoprint.log.2014-02-17 HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
:param filename: The filename of the log file to delete
|
||||
:statuscode 204: No error
|
||||
:statuscode 403: If the given API token did not have admin rights associated with it
|
||||
:statuscode 404: If the file was not found
|
||||
|
||||
.. _sec-bundledplugins-logging-api-datamodel:
|
||||
|
||||
Data model
|
||||
++++++++++
|
||||
|
||||
.. _sec-bundledplugins-logging-api-datamodel-retrieveresponse:
|
||||
|
||||
Logfile Retrieve Response
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``files``
|
||||
- 0..*
|
||||
- Array of :ref:`File information items <sec-bundledplugins-logging-api-datamodel-fileinfo>`
|
||||
- The list of requested files. Might be an empty list if no files are available
|
||||
* - ``free``
|
||||
- 1
|
||||
- String
|
||||
- The amount of disk space in bytes available in the local disk space (refers to OctoPrint's ``logs`` folder).
|
||||
|
||||
.. _sec-bundledplugins-logging-api-datamodel-fileinfo:
|
||||
|
||||
File information
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- String
|
||||
- The name of the file
|
||||
* - ``size``
|
||||
- 1
|
||||
- Number
|
||||
- The size of the file in bytes.
|
||||
* - ``date``
|
||||
- 1
|
||||
- Unix timestamp
|
||||
- The timestamp when this file was last modified.
|
||||
* - ``refs``
|
||||
- 1
|
||||
- :ref:`References <sec-bundledplugins-logging-api-datamodel-ref>`
|
||||
- References relevant to this file
|
||||
|
||||
.. _sec-bundledplugins-logging-api-datamodel-ref:
|
||||
|
||||
References
|
||||
~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``resource``
|
||||
- 1
|
||||
- URL
|
||||
- The resource that represents the file (e.g. for deleting)
|
||||
* - ``download``
|
||||
- 1
|
||||
- URL
|
||||
- The download URL for the file
|
||||
|
||||
.. _sec-bundledplugins-logging-jsclientlib:
|
||||
|
||||
JS Client Library
|
||||
-----------------
|
||||
|
||||
:mod:`OctoPrintClient.plugins.logging`
|
||||
--------------------------------------
|
||||
|
||||
.. note::
|
||||
|
||||
All methods here require that the used API token or the existing browser session
|
||||
has admin rights.
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.logging.listLogs(opts)
|
||||
|
||||
Retrieves a list of log files.
|
||||
|
||||
See :ref:`Retrieve a list of available log files <sec-bundledplugins-logging-api-list_logs>` for details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.logging.deleteLog(path, opts)
|
||||
|
||||
Deletes the specified log ``path``.
|
||||
|
||||
See :ref:`Delete a specific log file <sec-bundledplugins-logging-api-delete_logs>` for details.
|
||||
|
||||
:param string path: The path to the log file to delete
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.plugins.logging.downloadLog(path, opts)
|
||||
|
||||
Downloads the specified log ``file``.
|
||||
|
||||
See :js:func:`OctoPrint.download` for more details on the underlying library download mechanism.
|
||||
|
||||
:param string path: The path to the log file to download
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. _sec-bundledplugins-logging-sourcecode:
|
||||
|
||||
Source Code
|
||||
-----------
|
||||
|
||||
The source of the Logging plugin is bundled with OctoPrint and can be found in its source repository under ``src/octoprint/plugins/logging``.
|
||||
@@ -0,0 +1,43 @@
|
||||
.. _sec-bundledplugins-printer_safety_check:
|
||||
|
||||
Printer Safety Check
|
||||
====================
|
||||
|
||||
The Printer Safety Check plugin comes bundled with OctoPrint starting with version 1.3.7.
|
||||
|
||||
It tries to identify printers or rather printer firmwares with known safety issues, such as
|
||||
disabled thermal runaway protection, and displays a warning box to logged in users on
|
||||
such identification.
|
||||
|
||||
.. _fig-bundledplugins-printer_safety_check-example:
|
||||
.. figure:: ../images/bundledplugins-printer_safety_check-example.png
|
||||
:align: center
|
||||
:alt: Printer Safety Check warning example
|
||||
|
||||
An example of a warning generated by the Printer Safety Check
|
||||
|
||||
Currently the following firmwares produce this warning:
|
||||
|
||||
* Anet A8 stock firmware
|
||||
|
||||
If you know of further printers/printer firmwares that need to be added here, please
|
||||
`get in touch on the forum and provide their response to an M115 <https://faq.octoprint.org/warning-firmware-unsafe>`_.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
|
||||
|
||||
.. note::
|
||||
|
||||
Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though
|
||||
that even if your printer might be running totally fine with a known unsafe configuration, that might change
|
||||
unexpectedly and with `catastrophic <https://www.thissmarthouse.net/dont-burn-your-house-down-3d-printing-a-cautionary-tale/>`_
|
||||
`results <https://www.reddit.com/r/3Dprinting/comments/6cekgk/house_fire_thanks_to_cheap_printer_from_china/>`_.
|
||||
|
||||
.. _sec-bundledplugins-printer_safety_check-source:
|
||||
|
||||
Source Code
|
||||
-----------
|
||||
|
||||
The source of the Printer Safety Check plugin is bundled with OctoPrint and can be
|
||||
found in its source repository under ``src/octoprint/plugins/printer_safety_check``.
|
||||
@@ -46,7 +46,7 @@ There you can adjust the following settings:
|
||||
for the various components registered with the plugin, so that they don't have to be queried from the internet every time
|
||||
you load the page. Defaults to 24h, you usually shouldn't need to change that value.
|
||||
|
||||
More settings are available by :ref:`editing the correspondi.. _section in config.yaml <sec-bundledplugins-softwareupdate-configuration>`.
|
||||
More settings are available by :ref:`editing the corresponding section in config.yaml <sec-bundledplugins-softwareupdate-configuration>`.
|
||||
|
||||
That restart commands for OctoPrint and the whole server can be configured under Settings > Server.
|
||||
|
||||
@@ -56,9 +56,9 @@ Command line usage
|
||||
------------------
|
||||
|
||||
The functionality of the Software Update Plugin is also available on OctoPrint's command line interface under the
|
||||
``plugins`` sub command. It's is possible to check for updates via ``octoprint plugins softwareupdate:check``
|
||||
and to apply available updates via ``octoprint plugins softwareupdate:update``. Please the corresponding
|
||||
``--help`` pages on details:
|
||||
``plugins`` sub command. It's possible to check for updates via ``octoprint plugins softwareupdate:check``
|
||||
and to apply available updates via ``octoprint plugins softwareupdate:update``. Please see the corresponding
|
||||
``--help`` pages for details:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
@@ -126,7 +126,7 @@ Configuring the Plugin
|
||||
checks:
|
||||
# "octoprint" is reserved for OctoPrint
|
||||
octoprint:
|
||||
# this defines an version check that will check against releases
|
||||
# this defines a version check that will check against releases
|
||||
# published on OctoPrint's Github repository and pip as update method
|
||||
# against the release archives on Github - this is the default
|
||||
type: github_release
|
||||
@@ -135,7 +135,7 @@ Configuring the Plugin
|
||||
method: pip
|
||||
pip: 'https://github.com/foosel/OctoPrint/archive/{target_version}.zip'
|
||||
|
||||
# further checks may be define here
|
||||
# further checks may be defined here
|
||||
|
||||
# pip command, if another one than the automatically detected one should be
|
||||
# used - should normally NOT be necessary and hence set
|
||||
@@ -209,10 +209,21 @@ Version checks
|
||||
:ref:`hook <sec-bundledplugins-softwareupdate-hooks>`. Additional config
|
||||
parameters:
|
||||
|
||||
* ``python_checker``: (mandatory) A python callable which returns version
|
||||
* ``python_checker``: (mandatory) A Python callable which returns version
|
||||
information and whether the current version is up-to-date or not, see
|
||||
below for details.
|
||||
|
||||
* ``always_current``: Always reports that no update is necessary. Useful for debugging
|
||||
software update mechanisms during development. Additional config parameters:
|
||||
|
||||
* ``current_version``: Version to report for both local and remote version.
|
||||
|
||||
* ``never_current``: Always reports that an update is necessary. Useful for debugging
|
||||
software update mechanisms during development. Additional config parameters:
|
||||
|
||||
* ``local_version``: Current local version. Defaults to ``1.0.0``.
|
||||
* ``remote_version``: Remote version to offer update to. Defaults to ``1.0.1``.
|
||||
|
||||
.. _sec-bundledplugins-softwareupdate-configuration-updatemethods:
|
||||
|
||||
Update methods
|
||||
@@ -230,8 +241,11 @@ Update methods
|
||||
``update_folder`` setting or if the ``git_commit`` check is used its
|
||||
``checkout_folder`` setting.
|
||||
* ``python_updater``: Can only be specified by plugins through the
|
||||
:ref:`hook <sec-bundledplugins-softwareupdate-hooks>`. A python callable
|
||||
:ref:`hook <sec-bundledplugins-softwareupdate-hooks>`. A Python callable
|
||||
which performs the update, see below for details.
|
||||
* ``sleep_a_bit``: Does nothing but block for a configurable ``duration`` and log
|
||||
a countdown in the meantime. Useful for debugging software update mechanisms
|
||||
during development.
|
||||
|
||||
.. note::
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ Use the following settings to enable access control:
|
||||
|
||||
# If set to true, will automatically log on clients originating from any of the networks defined in
|
||||
# "localNetworks" as the user defined in "autologinAs". Defaults to false.
|
||||
autologinLocal: true
|
||||
autologinLocal: false
|
||||
|
||||
# The name of the user to automatically log on clients originating from "localNetworks" as. Must
|
||||
# be the name of one of your configured users.
|
||||
@@ -51,6 +51,17 @@ Use the following settings to enable access control:
|
||||
- 127.0.0.0/8
|
||||
- 192.168.1.0/24
|
||||
|
||||
# Whether to trust Basic Authentication headers. If you have setup Basic Authentication in front of
|
||||
# OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will
|
||||
# be logged into OctoPrint as the user user during Basic Authentication. Your should ONLY ENABLE THIS if your
|
||||
# OctoPrint instance is only accessible through a connection locked down through Basic Authentication!
|
||||
trustBasicAuthentication: false
|
||||
|
||||
# Whether to also check the password provided through Basic Authentication if the Basic Authentication
|
||||
# header is to be trusted. Disabling this will only match the user name in the Basic Authentication
|
||||
# header and login the user without further checks. Use with caution.
|
||||
checkBasicAuthenticationPassword: true
|
||||
|
||||
.. _sec-configuration-config_yaml-api:
|
||||
|
||||
API
|
||||
@@ -522,52 +533,16 @@ Use the following settings to enable or disable OctoPrint features:
|
||||
.. code-block:: yaml
|
||||
|
||||
feature:
|
||||
|
||||
# Whether to enable the gcode viewer in the UI or not
|
||||
gCodeVisualizer: true
|
||||
|
||||
# Whether to enable the temperature graph in the UI or not
|
||||
temperatureGraph: true
|
||||
|
||||
# Specifies whether OctoPrint should wait for the start response from the printer before trying to send commands
|
||||
# during connect.
|
||||
waitForStartOnConnect: false
|
||||
|
||||
# Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for
|
||||
# successful communication with Repetier firmware
|
||||
alwaysSendChecksum: false
|
||||
|
||||
# Specifies whether OctoPrint should also send linenumber + checksum with commands that are *not*
|
||||
# detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)").
|
||||
sendChecksumWithUnknownCommands: false
|
||||
|
||||
# Specifies whether OctoPrint should also use up acknowledgments ("ok") for commands that are *not*
|
||||
# detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)").
|
||||
unknownCommandsNeedAck: false
|
||||
|
||||
# Whether to ignore the first ok after a resend response. Needed for successful communication with
|
||||
# Repetier firmware
|
||||
swallowOkAfterResend: false
|
||||
|
||||
# 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
|
||||
|
||||
# Whether the printer sends repetier style target temperatures in the format
|
||||
# TargetExtr0:<temperature>
|
||||
# instead of attaching that information to the regular M105 responses
|
||||
repetierTargetTemp: false
|
||||
|
||||
# Whether to enable external heatup detection (to detect heatup triggered e.g. through the printer's LCD panel or
|
||||
# while printing from SD) or not. Causes issues with Repetier's "first ok then response" approach to
|
||||
# communication, so disable for printers running Repetier firmware.
|
||||
externalHeatupDetection: true
|
||||
|
||||
# Whether to enable the keyboard control feature in the control tab
|
||||
keyboardControl: true
|
||||
|
||||
@@ -575,28 +550,16 @@ Use the following settings to enable or disable OctoPrint features:
|
||||
# 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
|
||||
|
||||
# Whether to support F on its own as a valid GCODE command (true) or not (false)
|
||||
supportFAsCommand: false
|
||||
|
||||
# Whether to enable model size detection and warning (true) or not (false)
|
||||
modelSizeDetection: true
|
||||
|
||||
# Whether to attempt to auto detect the firmware of the printer and adjust settings
|
||||
# accordingly (true) or not and rely on manual configuration (false)
|
||||
firmwareDetection: true
|
||||
|
||||
# Whether to show a confirmation on print cancelling (true) or not (false)
|
||||
printCancelConfirmation: true
|
||||
|
||||
# Whether to block all sending to the printer while a G4 (dwell) command is active (true, repetier)
|
||||
# or not (false)
|
||||
blockWhileDwelling: false
|
||||
# Commands that should never be auto-uppercased when sent to the printer through the Terminal tab.
|
||||
# Defaults to only M117.
|
||||
autoUppercaseBlacklist:
|
||||
- M117
|
||||
|
||||
.. _sec-configuration-config_yaml-folder:
|
||||
|
||||
@@ -800,6 +763,10 @@ Use the following settings to configure the serial connection to the printer:
|
||||
# Defaults to 30 sec
|
||||
communication: 30
|
||||
|
||||
# Timeout during serial communication when busy protocol support is detected, in seconds.
|
||||
# Defaults to 3 sec
|
||||
communicationBusy: 3
|
||||
|
||||
# Timeout after which to query temperature when no target is set
|
||||
temperature: 5
|
||||
|
||||
@@ -824,7 +791,7 @@ Use the following settings to configure the serial connection to the printer:
|
||||
|
||||
# Maximum number of write attempts to serial during which nothing can be written before the communication
|
||||
# with the printer is considered dead and OctoPrint will disconnect with an error
|
||||
maxWritePasses:
|
||||
maxWritePasses: 5
|
||||
|
||||
# Use this to define additional patterns to consider for serial port listing. Must be a valid
|
||||
# "glob" pattern (see http://docs.python.org/2/library/glob.html). Defaults to not set.
|
||||
@@ -858,10 +825,6 @@ Use the following settings to configure the serial connection to the printer:
|
||||
helloCommand:
|
||||
- M110 N0
|
||||
|
||||
# Commands that should never be auto-uppercased when sent to the printer. Defaults to only M117.
|
||||
autoUppercaseBlacklist:
|
||||
- M117
|
||||
|
||||
# Whether to disconnect on errors or not
|
||||
disconnectOnErrors: true
|
||||
|
||||
@@ -872,6 +835,60 @@ Use the following settings to configure the serial connection to the printer:
|
||||
# impact, leave on if possible please
|
||||
logResends: true
|
||||
|
||||
# Specifies whether OctoPrint should wait for the start response from the printer before trying to send commands
|
||||
# during connect.
|
||||
waitForStartOnConnect: false
|
||||
|
||||
# Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for
|
||||
# successful communication with Repetier firmware
|
||||
alwaysSendChecksum: false
|
||||
|
||||
# Specifies whether OctoPrint should also send linenumber + checksum with commands that are *not*
|
||||
# detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)").
|
||||
sendChecksumWithUnknownCommands: false
|
||||
|
||||
# Specifies whether OctoPrint should also use up acknowledgments ("ok") for commands that are *not*
|
||||
# detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)").
|
||||
unknownCommandsNeedAck: false
|
||||
|
||||
# Whether to ignore the first ok after a resend response. Needed for successful communication with
|
||||
# Repetier firmware
|
||||
swallowOkAfterResend: false
|
||||
|
||||
# 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
|
||||
|
||||
# Whether the printer sends repetier style target temperatures in the format
|
||||
# TargetExtr0:<temperature>
|
||||
# instead of attaching that information to the regular M105 responses
|
||||
repetierTargetTemp: false
|
||||
|
||||
# Whether to enable external heatup detection (to detect heatup triggered e.g. through the printer's LCD panel or
|
||||
# while printing from SD) or not. Causes issues with Repetier's "first ok then response" approach to
|
||||
# communication, so disable for printers running Repetier firmware.
|
||||
externalHeatupDetection: true
|
||||
|
||||
# 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
|
||||
|
||||
# Whether to support F on its own as a valid GCODE command (true) or not (false)
|
||||
supportFAsCommand: false
|
||||
|
||||
# Whether to attempt to auto detect the firmware of the printer and adjust settings
|
||||
# accordingly (true) or not and rely on manual configuration (false)
|
||||
firmwareDetection: true
|
||||
|
||||
# Whether to block all sending to the printer while a G4 (dwell) command is active (true, repetier)
|
||||
# or not (false)
|
||||
blockWhileDwelling: false
|
||||
|
||||
# Whether to support resends without follow-up ok or not
|
||||
supportResendsWithoutOk: false
|
||||
|
||||
@@ -879,6 +896,14 @@ Use the following settings to configure the serial connection to the printer:
|
||||
# the responds skips on the ok)
|
||||
triggerOkForM29: true
|
||||
|
||||
capabilities:
|
||||
|
||||
# Whether to enable temperature autoreport in the firmware if its support is detected
|
||||
autoreport_temp: true
|
||||
|
||||
# Whether to shorten the communication timeout if the firmware seems to support the busy protocol
|
||||
busy_protocol: true
|
||||
|
||||
.. _sec-configuration-config_yaml-server:
|
||||
|
||||
Server
|
||||
@@ -1082,7 +1107,7 @@ OctoPrint is running is allowed to do this without password entry:
|
||||
command: sudo shutdown -h now
|
||||
confirm: You are about to shutdown the system.
|
||||
|
||||
You can also add an divider by setting action to divider like this:
|
||||
You can also add a divider by setting action to divider like this:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
|
||||
+12
-2
@@ -265,7 +265,7 @@ MetadataAnalysisFinished
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the file's origin storage location
|
||||
* ``result``: the analysis result -- this is a python object currently only available for internal use
|
||||
* ``result``: the analysis result -- this is a Python object currently only available for internal use
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
@@ -363,8 +363,18 @@ PrintDone
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
PrintCancelling
|
||||
The print is about to be cancelled.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
|
||||
* ``firmwareError``: the firmware error that caused cancelling the print job, if any
|
||||
|
||||
PrintCancelled
|
||||
The print has been cancelled via the cancel button.
|
||||
The print has been cancelled.
|
||||
|
||||
Payload:
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ Rerunning the wizard
|
||||
--------------------
|
||||
|
||||
In case Access Control was disabled in the configuration wizard, it is
|
||||
possibly to re-run it by editing ``config.yaml`` [#f1]_ and setting ``firstRun``
|
||||
possible to re-run it by editing ``config.yaml`` [#f1]_ and setting ``firstRun``
|
||||
in the ``server`` section and ``enabled`` in the ``accessControl`` section to
|
||||
``true``:
|
||||
|
||||
|
||||
@@ -21,16 +21,20 @@ Action commands are a feature defined for the GCODE based RepRap communication p
|
||||
|
||||
OctoPrint out of the box supports handling of the above mentioned commands:
|
||||
|
||||
cancel
|
||||
When this command is received from the printer, OctoPrint will cancel a current print job like if the
|
||||
"Cancel" button had been clicked.
|
||||
|
||||
pause
|
||||
When this command is received from the printer, OctoPrint will pause streaming of a current print job just like if the
|
||||
When this command is received from the printer, OctoPrint will pause a current print job just like if the
|
||||
"Pause" button had been clicked.
|
||||
|
||||
resume
|
||||
When this command is received from the printer, OctoPrint will resume streaming of a current print job just like if
|
||||
When this command is received from the printer, OctoPrint will resume a current print job just like if
|
||||
the "Resume" button had been clicked.
|
||||
|
||||
disconnect
|
||||
When this command is Received from the printer, OctoPrint will immediately disconnect from it.
|
||||
When this command is received from the printer, OctoPrint will immediately disconnect from it.
|
||||
|
||||
Support for additional commands may be added by plugins by implementing a handler for the
|
||||
:ref:`octoprint.comm.protocol.action <sec-plugins-hook-comm-protocol-action>` hook.
|
||||
@@ -0,0 +1,30 @@
|
||||
.. _sec-features-atcommands:
|
||||
|
||||
@ Commands
|
||||
==========
|
||||
|
||||
@ commands (also known as host commands elsewhere) are special commands you may include in GCODE files streamed
|
||||
through OctoPrint to your printer or send as part of GCODE scripts, through the Terminal Tab, the API or plugins.
|
||||
Contrary to other commands they will never be sent to the printer but instead trigger functions inside OctoPrint.
|
||||
|
||||
They are always of the form ``@<command>[ <parameters>]``, e.g. ``@pause`` or ``@custom_command with some parameters``.
|
||||
|
||||
Out of the box OctoPrint supports handling of these commands starting with version 1.3.7:
|
||||
|
||||
@cancel
|
||||
OctoPrint will cancel the current print job like if the "Cancel" button had been clicked. This command doesn't
|
||||
take any parameters.
|
||||
|
||||
@abort
|
||||
Same as ``cancel``.
|
||||
|
||||
@pause
|
||||
OctoPrint will pause the current print job just like if the "Pause" button had been clicked. This command doesn't
|
||||
take any parameters.
|
||||
|
||||
@resume
|
||||
OctoPrint will resume the current print job just like if the "Resume" button had been clicked. This command doesn't
|
||||
take any parameters.
|
||||
|
||||
Support for additional commands may be added by plugins by implementing a handler for one of the
|
||||
:ref:`octoprint.comm.protocol.atcommand <sec-plugins-hook-comm-protocol-atcommand-phase>` hooks.
|
||||
@@ -166,6 +166,10 @@ Controls
|
||||
clicked. This allows to override the direct sending of the command or commands to the printer with more
|
||||
sophisticated behaviour. The JavaScript snippet is ``eval``'d and processed in a context where the control
|
||||
it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``.
|
||||
* - ``additionalClasses``
|
||||
- (Optional) Additional classes to apply to the button of a ``command``, ``commands``, ``script`` or ``javascript``
|
||||
control, other than the default ``btn``. Can be used to visually style the button, e.g. set to ``btn-danger`` to
|
||||
turn the button red.
|
||||
* - ``enabled``
|
||||
- (Optional) A JavaScript snippet returning either ``true`` or ``false`` determining whether the control
|
||||
should be enabled or not. This allow to override the default logic for this (disabled if printer is offline
|
||||
|
||||
@@ -66,7 +66,7 @@ Context
|
||||
|
||||
All GCODE scripts have access to the following template variables through the template context:
|
||||
|
||||
* ``printer_profile``: The currently selected Printer Profile, including
|
||||
* ``printer_profile``: The currently selected :ref:`Printer Profile <sec-modules-printer-profile>`, including
|
||||
information such as the extruder count, the build volume size, the filament diameter etc.
|
||||
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!).
|
||||
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
|
||||
@@ -80,6 +80,7 @@ All GCODE scripts have access to the following template variables through the te
|
||||
note that ``actual`` and ``target`` might be ``None``.
|
||||
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
|
||||
and ``script.name`` respectively.
|
||||
* ``plugins``: An object containing variables provided by plugins (e.g ``plugins.myplugin.myvariable``)
|
||||
|
||||
There are a few additional template variables available for the following specific scripts:
|
||||
|
||||
|
||||
@@ -15,5 +15,6 @@ Features
|
||||
custom_controls.rst
|
||||
gcode_scripts.rst
|
||||
action_commands.rst
|
||||
atcommands.rst
|
||||
plugins.rst
|
||||
safemode.rst
|
||||
@@ -46,7 +46,7 @@ Manual Installation
|
||||
|
||||
If you don't want or can't use the Plugin Manager, plugins may also be installed manually either by copying and
|
||||
unpacking them into one of the configured plugin folders (regularly those are ``<octoprint source root>/plugins`` and
|
||||
``<octoprint config folder>/plugins`` [#f1]_ or by installing them as regular python modules via ``pip`` [#f2]_.
|
||||
``<octoprint config folder>/plugins`` [#f1]_ or by installing them as regular Python modules via ``pip`` [#f2]_.
|
||||
|
||||
For a plugin available on the Python Package Index (PyPi), the process is as simple as issuing a
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 68 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 6.5 KiB |
+18
-3
@@ -6,9 +6,24 @@ Welcome to OctoPrint's documentation!
|
||||
:alt: The OctoPrint Logo
|
||||
:align: right
|
||||
|
||||
This documentation is still in the process of being migrated from
|
||||
`OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki>`_, so also take
|
||||
a look there!
|
||||
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
|
||||
and released under the `GNU Affero General Public License V3 <http://www.gnu.org/licenses/agpl.html>`_.
|
||||
|
||||
Its website can be found at `octoprint.org <https://octoprint.org/>`_.
|
||||
|
||||
The community forum is available at `discourse.octoprint.org <https://discourse.octoprint.org/>`_.
|
||||
|
||||
The FAQ can be accessed by following `faq.octoprint.org <https://faq.octoprint.org/>`_.
|
||||
|
||||
The official plugin repository can be reached at `plugins.octoprint.org <https://plugins.octoprint.org/>`_.
|
||||
|
||||
OctoPrint's development wouldn't be possible without the `financial support by its community <https://octoprint.org/support-octoprint/>`_.
|
||||
If you enjoy OctoPrint, please consider becoming a regular supporter!
|
||||
|
||||
.. note::
|
||||
|
||||
This documentation currently focuses primarily on developers and less on end users. If you are interested in
|
||||
helping to change this, please get in touch `on the forum <https://discourse.octoprint.org/>`_!
|
||||
|
||||
Contents
|
||||
========
|
||||
|
||||
@@ -32,7 +32,7 @@ correct URL prefix:
|
||||
-->
|
||||
<script type="text/javascript" src="{{ url_for("static", filename="js/app/client/<component>.js") }}"></script>
|
||||
|
||||
Regardless of which way you use to include the library, you'll also need to make sure you included JQuery and lodash,
|
||||
Regardless of which way you use to include the library, you'll also need to make sure you included jQuery and lodash,
|
||||
because the library depends on those to be available (as ``$`` and ``_``). You can embed those like this:
|
||||
|
||||
.. code-block:: html+jinja
|
||||
@@ -45,7 +45,7 @@ number of components, make sure to at the very least include that one to be able
|
||||
|
||||
When you import the client library as described above, a global variable ``OctoPrint`` will become available, which is
|
||||
a prepared instance of the ``OctoPrintClient`` class the library assembles from registered components. You can directly
|
||||
used that singular ``OctoPrint`` instance if you only need to talk to one OctoPrint server:
|
||||
use that singular ``OctoPrint`` instance if you only need to talk to one OctoPrint server:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
|
||||
.. js:function:: OctoPrintClient.job.resume(opts)
|
||||
|
||||
Resumes the current job if it's currently pause, does nothing if it's running.
|
||||
Resumes the current job if it's currently paused, does nothing if it's running.
|
||||
|
||||
See :ref:`Issue a job command <sec-api-jobs-command>` for details.
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
.. note::
|
||||
|
||||
All methods here require that the used API token or a the existing browser session
|
||||
All methods here require that the used API token or the existing browser session
|
||||
has admin rights.
|
||||
|
||||
.. js:function:: OctoPrintClient.languages.list(opts)
|
||||
|
||||
@@ -3,37 +3,9 @@
|
||||
:mod:`OctoPrintClient.logs`
|
||||
---------------------------
|
||||
|
||||
.. note::
|
||||
|
||||
All methods here require that the used API token or a the existing browser session
|
||||
has admin rights.
|
||||
|
||||
.. js:function:: OctoPrintClient.logs.list(opts)
|
||||
|
||||
Retrieves a list of log files.
|
||||
|
||||
See :ref:`Retrieve a list of available log files <sec-api-logs-list>` for details.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.logs.delete(path, opts)
|
||||
|
||||
Deletes the specified log ``path``.
|
||||
|
||||
See :ref:`Delete a specific log file <sec-api-logs-delete>` for details.
|
||||
|
||||
:param string path: The path to the log file to delete
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.logs.download(path, opts)
|
||||
|
||||
Downloads the specified log ``file``.
|
||||
|
||||
See :js:func:`OctoPrint.download` for more details on the underlying library download mechanism.
|
||||
|
||||
:param string path: The path to the log file to download
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
Log file management (and logging configuration) was moved into a bundled plugin in OctoPrint 1.3.7. Refer to
|
||||
:ref:`the Logging's plugins JS Client Library <sec-bundledplugins-logging-jsclientlib>` for the JS Client documentation.
|
||||
|
||||
The former module ``OctoPrintClient.logs`` and its methods are marked as deprecated but still work for now. New
|
||||
client implementations should directly use the new module provided by the bundled plugin. Existing implementations
|
||||
should adapt their used module as soon as possible.
|
||||
@@ -174,7 +174,7 @@
|
||||
|
||||
Sets the given temperature on the printer's heated bed (if available).
|
||||
|
||||
``target`` is expected to be a the target temperature as a float value.
|
||||
``target`` is expected to be the target temperature as a float value.
|
||||
|
||||
**Example:**
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
.. note::
|
||||
|
||||
All methods here require that the used API token or a the existing browser session
|
||||
All methods here require that the used API token or the existing browser session
|
||||
has admin rights.
|
||||
|
||||
.. js:function:: OctoPrintClient.system.getCommands(opts)
|
||||
@@ -35,4 +35,4 @@
|
||||
.. seealso::
|
||||
|
||||
:ref:`System API <sec-api-system>`
|
||||
Documentation of the underlying system API
|
||||
Documentation of the underlying system API.
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
.. js:function:: OctoPrintClient.timelapse.list(opts)
|
||||
|
||||
Get the lists of rendered and unrendered timelapses. The returned promis
|
||||
Get the lists of rendered and unrendered timelapses. The returned promise
|
||||
will be resolved with an object containing the properties ``rendered``
|
||||
which will have the list of rendered timelapses, and ``unrendered`` which
|
||||
will have the list of unrendered timelapses.
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
.. note::
|
||||
|
||||
Most methods here require that the used API token or a the existing browser session
|
||||
Most methods here require that the used API token or the existing browser session
|
||||
has admin rights *or* corresponds to the user to be modified. Some methods
|
||||
definitely require admin rights.
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
.. note::
|
||||
|
||||
All methods here require that the used API token or a the existing browser session
|
||||
All methods here require that the used API token or the existing browser session
|
||||
has admin rights.
|
||||
|
||||
.. js:function:: OctoPrintClient.util.test(command, parameters, opts)
|
||||
@@ -206,4 +206,4 @@
|
||||
.. seealso::
|
||||
|
||||
:ref:`Util API <sec-api-util>`
|
||||
Documentation of the underlying util API
|
||||
Documentation of the underlying util API.
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
.. note::
|
||||
|
||||
All methods here require that the used API token or a the existing browser session
|
||||
All methods here require that the used API token or the existing browser session
|
||||
has admin rights.
|
||||
|
||||
.. js:function:: OctoPrintClient.wizard.get(opts)
|
||||
|
||||
@@ -4,3 +4,10 @@ octoprint.printer
|
||||
-----------------
|
||||
|
||||
.. automodule:: octoprint.printer
|
||||
|
||||
.. _sec-modules-printer-profile:
|
||||
|
||||
octoprint.printer.profile
|
||||
-------------------------
|
||||
|
||||
.. automodule:: octoprint.printer.profile
|
||||
@@ -23,9 +23,9 @@ Lifecycle
|
||||
|
||||
There are three sources of installed plugins that OctoPrint will check during start up:
|
||||
|
||||
* it's own ``octoprint/plugins`` folder (this is where the bundled plugins reside),
|
||||
* its own ``octoprint/plugins`` folder (this is where the bundled plugins reside),
|
||||
* the ``plugins`` folder in its configuration directory (e.g. ``~/.octoprint/plugins`` on Linux),
|
||||
* any python packages registered for the entry point ``octoprint.plugin``.
|
||||
* any Python packages registered for the entry point ``octoprint.plugin``.
|
||||
|
||||
Each plugin that OctoPrint finds it will first load, then enable. On enabling a plugin, OctoPrint will
|
||||
register its declared :ref:`hook handlers <sec-plugins-hooks>` and :ref:`helpers <sec-plugins-helpers>`, apply
|
||||
@@ -36,7 +36,7 @@ any :ref:`settings overlays <sec-plugins-controlproperties-plugin_settings_overl
|
||||
On disabling a plugin, its hook handlers, helpers, mixin implementations and settings overlays will be de-registered again.
|
||||
|
||||
Some plugin types require a reload of the frontend or a restart of OctoPrint for enabling/disabling them. You
|
||||
can recognized such plugins by their implementations implementing :class:`~octoprint.plugin.ReloadNeedingPlugin` or
|
||||
can recognize such plugins by their implementations implementing :class:`~octoprint.plugin.ReloadNeedingPlugin` or
|
||||
:class:`~octoprint.plugin.RestartNeedingPlugin` or providing handlers for one of the hooks marked correspondingly.
|
||||
|
||||
.. image:: ../images/plugins_lifecycle.png
|
||||
|
||||
@@ -134,7 +134,7 @@ as a simple python file following the naming convention ``<plugin identifier>.py
|
||||
``~/.octoprint/plugins`` folder. You already know how that works. But let's say you have more than just a simple plugin
|
||||
that can be done in one file. Distributing multiple files and getting your users to install them in the right way
|
||||
so that OctoPrint will be able to actually find and load them is certainly not impossible, but we want to do it in the
|
||||
best way possible, meaning we want to make our plugin a fully installable python module that your users will be able to
|
||||
best way possible, meaning we want to make our plugin a fully installable Python module that your users will be able to
|
||||
install directly via `OctoPrint's built-in Plugin Manager <https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager>`_
|
||||
or alternatively manually utilizing Python's standard package manager ``pip`` directly.
|
||||
|
||||
@@ -282,7 +282,7 @@ of information now defined twice:
|
||||
plugin_version = "1.0.0"
|
||||
plugin_description = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
|
||||
The nice thing about our plugin now being a proper python package is that OctoPrint can and will access the metadata defined
|
||||
The nice thing about our plugin now being a proper Python package is that OctoPrint can and will access the metadata defined
|
||||
within ``setup.py``! So, we don't really need to define all this data twice. Remove ``__plugin_name__``, ``__plugin_version__``
|
||||
and ``__plugin_description__`` from ``__init__.py``:
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ system. They are registered with the OctoPrint plugin system through the use of
|
||||
|
||||
An example for providing some helper functions to the system can be found in the
|
||||
`Discovery Plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_,
|
||||
which provides it's SSDP browsing and Zeroconf browsing and publishing functions as helper methods.
|
||||
which provides its SSDP browsing and Zeroconf browsing and publishing functions as helper methods.
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
+128
-15
@@ -408,6 +408,45 @@ octoprint.comm.protocol.action
|
||||
:param str action: The parsed out action command, so for a ``line`` like ``// action:some_command`` this will be
|
||||
``some_command``
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-atcommand-phase:
|
||||
|
||||
octoprint.comm.protocol.atcommand.<phase>
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
This describes actually two hooks:
|
||||
|
||||
* ``octoprint.comm.protocol.atcommand.queuing``
|
||||
* ``octoprint.comm.protocol.atcommand.sending``
|
||||
|
||||
.. py:function:: protocol_atcommandphase_hook(comm_instance, phase, command, parameters, tags=None, *args, **kwargs)
|
||||
|
||||
Trigger on :ref:`@ commands <sec-features-atcommands>` as they progress through the ``queuing`` and ``sending``
|
||||
phases of the comm layer. See :ref:`the gcode phase hook <sec-plugins-hook-comm-protocol-gcode-phase>` for a
|
||||
detailed description of each of these phases.
|
||||
|
||||
Hook handlers may use this to react to arbitrary :ref:`@ commands <sec-features-atcommands>` included in GCODE files
|
||||
streamed to the printer or sent as part of GCODE scripts, through the API or plugins.
|
||||
|
||||
Please note that these hooks do not allow to rewrite, suppress or expand @ commands, they are merely callbacks to
|
||||
trigger the *actual execution* of whatever functionality lies behind a given @ command, similar to
|
||||
:ref:`the action command hook <sec-plugins-hook-comm-protocol-action>`.
|
||||
|
||||
**Example**
|
||||
|
||||
Pause the print on ``@wait`` (this mirrors the implementation of the built-in ``@pause`` command, just with a
|
||||
different name).
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_atcommand.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `custom_action_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_atcommand.py>`__
|
||||
|
||||
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
|
||||
:param str phase: The current phase in the command progression, either ``queuing`` or ``sending``. Will always
|
||||
match the ``<phase>`` of the hook.
|
||||
:param str cmd: The @ command without the leading @
|
||||
:param str parameters: Any parameters provided to the @ command. If none were provided this will be an empty string.
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-gcode-phase:
|
||||
|
||||
octoprint.comm.protocol.gcode.<phase>
|
||||
@@ -420,7 +459,7 @@ This describes actually four hooks:
|
||||
* ``octoprint.comm.protocol.gcode.sending``
|
||||
* ``octoprint.comm.protocol.gcode.sent``
|
||||
|
||||
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, *args, **kwargs)
|
||||
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs)
|
||||
|
||||
Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases
|
||||
are the following:
|
||||
@@ -443,7 +482,39 @@ This describes actually four hooks:
|
||||
the communication layer or before they are actually sent over the serial port, or to react to the queuing or sending
|
||||
of commands after the fact. The hook handler will be called with the processing ``phase``, the ``cmd`` to be sent to
|
||||
the printer as well as the ``cmd_type`` parameter used for enqueuing (OctoPrint will make sure that the send queue
|
||||
will never contain more than one line with the same ``cmd_type``) and the detected gcode command (if it is one).
|
||||
will never contain more than one line with the same ``cmd_type``) and the detected ``gcode`` command (if it is one)
|
||||
as well as its ``subcode`` (if it has one). OctoPrint will also provide any ``tags`` attached to the command throughout
|
||||
its lifecycle.
|
||||
|
||||
Tags are arbitrary strings that can be attached to a command as it moves through the various phases and can be used to e.g.
|
||||
distinguish between commands that originated in a printed file (``source:file``) vs. a configured GCODE script
|
||||
(``source:script``) vs. an API call (``source:api``) vs. a plugin (``source:plugin`` or ``source:rewrite`` and
|
||||
``plugin:<plugin identifier>``). If during development you want to get an idea of the various possible tags, set
|
||||
the logger ``octoprint.util.comm.command_phases`` to ``DEBUG``, connect to a printer (real or virtual) and take a
|
||||
look at your ``octoprint.log`` during serial traffic:
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
2018-02-16 18:20:31,213 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
|
||||
2018-02-16 18:20:31,216 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
|
||||
2018-02-16 18:20:31,217 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
|
||||
2018-02-16 18:20:31,217 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
|
||||
2018-02-16 18:20:31,219 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
|
||||
2018-02-16 18:20:31,220 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
|
||||
2018-02-16 18:20:31,230 - tornado.access - INFO - 204 POST /api/printer/command (127.0.0.1) 23.00ms
|
||||
2018-02-16 18:20:31,232 - tornado.access - INFO - 200 POST /api/printer/command (127.0.0.1) 25.00ms
|
||||
2018-02-16 18:20:31,232 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
|
||||
2018-02-16 18:20:31,234 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
|
||||
2018-02-16 18:20:31,242 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
|
||||
2018-02-16 18:20:31,243 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
|
||||
2018-02-16 18:20:38,552 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
|
||||
2018-02-16 18:20:38,552 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
|
||||
2018-02-16 18:20:38,553 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
|
||||
2018-02-16 18:20:38,553 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G1 X10 F6000 | gcode: G1 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
|
||||
2018-02-16 18:20:38,555 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G1 X10 F6000 | gcode: G1 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
|
||||
2018-02-16 18:20:38,556 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
|
||||
2018-02-16 18:20:38,556 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G90 | gcode: G90 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
|
||||
2018-02-16 18:20:38,558 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G90 | gcode: G90 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
|
||||
|
||||
Defining a ``cmd_type`` other than None will make sure OctoPrint takes care of only having one command of that type
|
||||
in its sending queue. Predefined types are ``temperature_poll`` for temperature polling via ``M105`` and
|
||||
@@ -482,6 +553,8 @@ This describes actually four hooks:
|
||||
should use this option.
|
||||
* A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``.
|
||||
Handlers which wish to rewrite both the command and the command type should use this option.
|
||||
* A 3-tuple consisting of a rewritten version of the ``cmd``, the ``cmd_type`` and any additional ``tags`` you might
|
||||
want to attach to the lifecycle of the command in a set, e.g. ``return "M105", "temperature_poll", {"my_custom_tag"}``
|
||||
* **"queuing" phase only**: A list of any of the above to allow for expanding one command into
|
||||
many. The following example shows how any queued command could be turned into a sequence of a temperature query,
|
||||
line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example
|
||||
@@ -489,7 +562,7 @@ This describes actually four hooks:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
|
||||
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None *args, **kwargs):
|
||||
if gcode or not cmd.startswith("@foo"):
|
||||
return
|
||||
|
||||
@@ -524,6 +597,7 @@ This describes actually four hooks:
|
||||
:param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed
|
||||
:param str subcode: Parsed subcode of the GCODE command, e.g. ``1`` for ``M80.1``. Will be None if no subcode was provided
|
||||
or no command could be parsed.
|
||||
:param tags: Tags attached to the command
|
||||
:return: None, 1-tuple, 2-tuple or string, see the description above for details.
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-gcode-received:
|
||||
@@ -534,7 +608,7 @@ octoprint.comm.protocol.gcode.received
|
||||
.. py:function:: gcode_received_hook(comm_instance, line, *args, **kwargs)
|
||||
|
||||
Get the returned lines sent by the printer. Handlers should return the received line or in any case, the modified
|
||||
version of it. If the the handler returns None, processing will be aborted and the communication layer will get an
|
||||
version of it. If the handler returns None, processing will be aborted and the communication layer will get an
|
||||
empty string as the received line. Note that Python functions will also automatically return ``None`` if an empty
|
||||
``return`` statement is used or just nothing is returned explicitly from the handler.
|
||||
|
||||
@@ -552,6 +626,36 @@ octoprint.comm.protocol.gcode.received
|
||||
:return: The received line or in any case, a modified version of it.
|
||||
:rtype: str
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-gcode-error:
|
||||
|
||||
octoprint.comm.protocol.gcode.error
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: gcode_error_hook(comm_instance, error_message, *args, **kwargs)
|
||||
|
||||
Get the messages of any errors messages sent by the printer, with the leading ``Error:`` or ``!!`` already
|
||||
stripped. Handlers should return True if they handled that error internally and it should not be processed by
|
||||
the system further. Normal processing of these kinds of errors - depending on the configuration of error
|
||||
handling - involves canceling the ongoing print and possibly also disconnecting.
|
||||
|
||||
Plugins might utilize this hook to handle errors generated by the printer that are recoverable in one way or
|
||||
the other and should not trigger the normal handling that assumes the worst.
|
||||
|
||||
**Example:**
|
||||
|
||||
Looks for error messages containing "fan error" or "bed missing" (ignoring case) and marks them as handled by the
|
||||
plugin.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/comm_error_handler_test.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `comm_error_handler_test.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/comm_error_handler_test.py>`_
|
||||
|
||||
:param MachineCom comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
|
||||
:param str error_message: The error message received from the printer.
|
||||
:return: True if the error was handled in the plugin and should not be processed further, False (or None) otherwise.
|
||||
:rtype: bool
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-scripts:
|
||||
|
||||
octoprint.comm.protocol.scripts
|
||||
@@ -559,19 +663,19 @@ octoprint.comm.protocol.scripts
|
||||
|
||||
.. py:function:: protocol_scripts_hook(comm_instance, script_type, script_name, *args, **kwargs)
|
||||
|
||||
Return a prefix to prepend and a postfix to append to the script ``script_name`` of type ``type``. Handlers should
|
||||
Return a prefix to prepend, postfix to append, and optionally a dictionary of variables to provide to the script ``script_name`` of type ``type``. Handlers should
|
||||
make sure to only proceed with returning additional scripts if the ``script_type`` and ``script_name`` match
|
||||
handled scripts. If not, None should be returned directly.
|
||||
|
||||
If the hook handler has something to add to the specified script, it may return a 2-tuple, with the first entry
|
||||
defining the prefix (what to *prepend* to the script in question) and the last entry defining the postfix (what to
|
||||
*append* to the script in question). Both prefix and postfix can be None to signify that nothing should be prepended
|
||||
If the hook handler has something to add to the specified script, it may return a 2-tuple or a 3-tuple with the first entry
|
||||
defining the prefix (what to *prepend* to the script in question), the second entry defining the postfix (what to
|
||||
*append* to the script in question), and finally if desired a dictionary of variables to be made available to the script. Both prefix and postfix can be None to signify that nothing should be prepended
|
||||
respectively appended.
|
||||
|
||||
The returned entries may be either iterables of script lines or a string including newlines of the script lines (which
|
||||
The returned prefix and postfix entries may be either iterables of script lines or a string including newlines of the script lines (which
|
||||
will be split by the caller if necessary).
|
||||
|
||||
**Example:**
|
||||
**Example 1:**
|
||||
|
||||
Appends an ``M117 OctoPrint connected`` to the configured ``afterPrinterConnected`` GCODE script.
|
||||
|
||||
@@ -580,10 +684,19 @@ octoprint.comm.protocol.scripts
|
||||
:tab-width: 4
|
||||
:caption: `message_on_connect.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/message_on_connect.py>`_
|
||||
|
||||
**Example 2:**
|
||||
|
||||
Provides the variable ``myvariable`` to the configured ``beforePrintStarted`` GCODE script.
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/gcode_script_variables.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `gcode_script_variables.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/gcode_script_variables.py>`_
|
||||
|
||||
:param MachineCom comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
|
||||
:param str script_type: The type of the script for which the hook was called, currently only "gcode" is supported here.
|
||||
:param str script_name: The name of the script for which the hook was called.
|
||||
:return: A 2-tuple in the form ``(prefix, postfix)`` or None
|
||||
:return: A 2-tuple in the form ``(prefix, postfix)``, 3-tuple in the form ``(prefix, postfix, variables)``, or None
|
||||
:rtype: tuple or None
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-temperatures-received:
|
||||
@@ -738,7 +851,7 @@ octoprint.filemanager.preprocessor
|
||||
|
||||
``file_object`` will be a subclass of :class:`~octoprint.filemanager.util.AbstractFileWrapper`. Handlers may
|
||||
access the raw data of the file via :func:`~octoprint.filemanager.util.AbstractFileWrapper.stream`, e.g.
|
||||
to wrap it further. Handlers which do not wish to handle the `file_object`
|
||||
to wrap it further. Handlers which do not wish to handle the `file_object` should just return it untouched.
|
||||
|
||||
**Example**
|
||||
|
||||
@@ -783,7 +896,7 @@ octoprint.printer.factory
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``printer`` instance.
|
||||
|
||||
If no of the registered factories return a printer instance, the default :class:`~octoprint.printer.standard.Printer`
|
||||
If none of the registered factories return a printer instance, the default :class:`~octoprint.printer.standard.Printer`
|
||||
class will be instantiated.
|
||||
|
||||
:param dict components: System components to use for printer instance initialization
|
||||
@@ -885,7 +998,7 @@ octoprint.server.http.routes
|
||||
that allows delivery of the requested resource as attachment and access validation through an optional callback.
|
||||
:class:`~octoprint.server.util.tornado.UrlForwardHandler`
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies
|
||||
requests to a preconfigured url and returns the response.
|
||||
requests to a preconfigured URL and returns the response.
|
||||
|
||||
:param list server_routes: read-only list of the currently configured server routes
|
||||
:return: a list of 3-tuples with additional routes as defined above
|
||||
@@ -1028,7 +1141,7 @@ octoprint.users.factory
|
||||
|
||||
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
|
||||
|
||||
If no of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
|
||||
If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
|
||||
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
|
||||
:class:`~octoprint.users.FilebasedUserManager` will be instantiated, linked to the default user storage
|
||||
file ``~/.octoprint/users.yaml``.
|
||||
|
||||
@@ -51,7 +51,7 @@ An overview of these properties follows.
|
||||
.. seealso::
|
||||
|
||||
:class:`~octoprint.plugin.core.Plugin` and :class:`~octoprint.plugin.types.OctoPrintPlugin`
|
||||
Class documentation also containing the properties shared among all mixing implementations.
|
||||
Class documentation also containing the properties shared among all mixin implementations.
|
||||
|
||||
:ref:`Available Mixins <sec-plugins-mixins-available>`
|
||||
Some mixin types trigger the injection of additional properties.
|
||||
|
||||
@@ -153,7 +153,7 @@ An overview of these properties can be found in the section :ref:`Injected Prope
|
||||
.. seealso::
|
||||
|
||||
:class:`~octoprint.plugin.core.Plugin` and :class:`~octoprint.plugin.types.OctoPrintPlugin`
|
||||
Class documentation also containing the properties shared among all mixing implementations.
|
||||
Class documentation also containing the properties shared among all mixin implementations.
|
||||
|
||||
.. _sec-plugins-mixins-available:
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ gcodeFilesViewModel
|
||||
logViewModel
|
||||
View model for the logfile settings dialog.
|
||||
loginStateViewModel
|
||||
View model for the current loginstate of the user, very interesting for plugins that need to
|
||||
View model for the current login state of the user, very interesting for plugins that need to
|
||||
evaluate the current login state or information about the current user, e.g. associated roles.
|
||||
navigationViewModel
|
||||
View model for the navigation bar.
|
||||
@@ -168,7 +168,7 @@ OctoPrint's web application will call several callbacks on all registered view m
|
||||
Those are listed below:
|
||||
|
||||
onStartup()
|
||||
Called when the first initialization has been done: All view models are constructed and hence their dependencies
|
||||
Called when the first initialization has been done. All view models are constructed and hence their dependencies
|
||||
resolved, no bindings have been done yet.
|
||||
|
||||
onBeforeBinding()
|
||||
@@ -210,7 +210,7 @@ onDataUpdaterPluginMessage(plugin, message)
|
||||
Called when a plugin message is pushed from the server with the identifier of the calling plugin as first
|
||||
and the actual message as the second parameter. Note that the latter might be a full fledged object, depending
|
||||
on the plugin sending the message. You can use this method to asynchronously push data from your plugin's server
|
||||
component to it's frontend component.
|
||||
component to its frontend component.
|
||||
|
||||
onUserLoggedIn(user)
|
||||
Called when a user gets logged into the web app, either passively (upon initial load of the page due to a valid
|
||||
|
||||
@@ -30,7 +30,7 @@ INSTALL_REQUIRES = [
|
||||
"Flask-Babel>=0.9,<0.10",
|
||||
"Flask-Assets>=0.10,<0.11",
|
||||
"markdown>=2.6.4,<2.7",
|
||||
"pyserial>=2.7,<2.8",
|
||||
"pyserial>=2.7,<3.5",
|
||||
"netaddr>=0.7.17,<0.8",
|
||||
"watchdog>=0.8.3,<0.9",
|
||||
"sarge>=0.1.4,<0.2",
|
||||
@@ -52,7 +52,8 @@ INSTALL_REQUIRES = [
|
||||
"wrapt>=1.10.10,<1.11",
|
||||
"futures>=3.1.1,<3.2",
|
||||
"emoji>=0.4.5,<0.5",
|
||||
"monotonic>=1.3,<1.4"
|
||||
"monotonic>=1.3,<1.4",
|
||||
"frozendict>=1.2,<1.3"
|
||||
]
|
||||
|
||||
if sys.platform == "darwin":
|
||||
|
||||
@@ -322,12 +322,9 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
|
||||
plugin_validators = []
|
||||
if safe_mode:
|
||||
def validator(phase, plugin_info):
|
||||
if phase == "after_load":
|
||||
if phase in ("before_import", "before_load", "before_enable"):
|
||||
setattr(plugin_info, "safe_mode_victim", not plugin_info.bundled)
|
||||
setattr(plugin_info, "safe_mode_enabled", False)
|
||||
elif phase == "before_enable":
|
||||
if not plugin_info.bundled:
|
||||
setattr(plugin_info, "safe_mode_enabled", True)
|
||||
return False
|
||||
return True
|
||||
plugin_validators.append(validator)
|
||||
@@ -440,7 +437,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
result.append((entry["plugin"], version))
|
||||
else:
|
||||
logger.debug("Blacklisted plugin: {}".format(entry["plugin"]))
|
||||
result.append(entry["key"])
|
||||
result.append(entry["plugin"])
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -305,7 +305,6 @@ def git_parse_lookup_file(path):
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
|
||||
import re
|
||||
lookup = []
|
||||
with open(path, "r") as f:
|
||||
for line in f:
|
||||
|
||||
@@ -6,7 +6,7 @@ Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
import sys, os, time, signal, io
|
||||
import sys, os, time, signal
|
||||
|
||||
class Daemon:
|
||||
"""
|
||||
|
||||
@@ -83,8 +83,8 @@ class EnvironmentDetector(object):
|
||||
|
||||
# try to find pip version
|
||||
try:
|
||||
import pip
|
||||
result["pip"] = pip.__version__
|
||||
import pkg_resources
|
||||
result["pip"] = pkg_resources.get_distribution("pip").version
|
||||
except:
|
||||
self._logger.exception("Error detecting pip version")
|
||||
|
||||
|
||||
@@ -69,6 +69,7 @@ class Events(object):
|
||||
PRINT_STARTED = "PrintStarted"
|
||||
PRINT_DONE = "PrintDone"
|
||||
PRINT_FAILED = "PrintFailed"
|
||||
PRINT_CANCELLING = "PrintCancelling"
|
||||
PRINT_CANCELLED = "PrintCancelled"
|
||||
PRINT_PAUSED = "PrintPaused"
|
||||
PRINT_RESUMED = "PrintResumed"
|
||||
@@ -87,6 +88,7 @@ class Events(object):
|
||||
EJECT = "Eject"
|
||||
E_STOP = "EStop"
|
||||
POSITION_UPDATE = "PositionUpdate"
|
||||
FIRMWARE_DATA = "FirmwareData"
|
||||
TOOL_CHANGE = "ToolChange"
|
||||
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
|
||||
|
||||
|
||||
@@ -470,7 +470,9 @@ class FileManager(object):
|
||||
file_object = hook_file_object
|
||||
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
self._analysis_queue.dequeue(queue_entry)
|
||||
|
||||
if queue_entry is not None:
|
||||
self._analysis_queue.dequeue(queue_entry)
|
||||
|
||||
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display)
|
||||
|
||||
|
||||
@@ -76,6 +76,9 @@ class AnalysisQueue(object):
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def enqueue(self, entry, high_priority=False):
|
||||
if entry is None:
|
||||
return False
|
||||
|
||||
if not entry.type in self._queues:
|
||||
return False
|
||||
|
||||
@@ -83,6 +86,9 @@ class AnalysisQueue(object):
|
||||
return True
|
||||
|
||||
def dequeue(self, entry):
|
||||
if entry is None:
|
||||
return False
|
||||
|
||||
if not entry.type in self._queues:
|
||||
return False
|
||||
|
||||
|
||||
@@ -695,7 +695,7 @@ class LocalFileStorage(StorageInterface):
|
||||
display = destination_data["display"]
|
||||
else:
|
||||
display = None
|
||||
|
||||
|
||||
destination_meta = self._get_metadata_entry(destination_data["path"], destination_data["name"],
|
||||
default=dict())
|
||||
if display:
|
||||
@@ -712,14 +712,14 @@ class LocalFileStorage(StorageInterface):
|
||||
shutil.copytree(source_data["fullpath"], destination_data["fullpath"])
|
||||
except Exception as e:
|
||||
raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
|
||||
|
||||
|
||||
self._set_display_metadata(destination_data, source_data=source_data)
|
||||
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
def move_folder(self, source, destination):
|
||||
source_data, destination_data = self._get_source_destination_data(source, destination)
|
||||
|
||||
|
||||
# only a display rename? Update that and bail early
|
||||
if source_data["fullpath"] == destination_data["fullpath"]:
|
||||
self._set_display_metadata(destination_data)
|
||||
@@ -839,7 +839,7 @@ class LocalFileStorage(StorageInterface):
|
||||
destination_data["path"], destination_data["name"],
|
||||
delete_source=True)
|
||||
self._set_display_metadata(destination_data, source_data=source_data)
|
||||
|
||||
|
||||
return self.path_in_storage(destination_data["fullpath"])
|
||||
|
||||
def has_analysis(self, path):
|
||||
@@ -988,7 +988,7 @@ class LocalFileStorage(StorageInterface):
|
||||
absolute path including leading ``basefolder`` path.
|
||||
"""
|
||||
path = to_unicode(path)
|
||||
|
||||
|
||||
if len(path):
|
||||
if path[0] == u"/":
|
||||
path = path[1:]
|
||||
@@ -1316,91 +1316,96 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
path_in_location = entry_name if not base else base + entry_name
|
||||
|
||||
# file handling
|
||||
if entry_is_file:
|
||||
type_path = octoprint.filemanager.get_file_type(entry_name)
|
||||
if not type_path:
|
||||
# only supported extensions
|
||||
continue
|
||||
else:
|
||||
file_type = type_path[0]
|
||||
try:
|
||||
# file handling
|
||||
if entry_is_file:
|
||||
type_path = octoprint.filemanager.get_file_type(entry_name)
|
||||
if not type_path:
|
||||
# only supported extensions
|
||||
continue
|
||||
else:
|
||||
file_type = type_path[0]
|
||||
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
metadata_dirty = True
|
||||
else:
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
metadata=metadata)
|
||||
metadata_dirty = True
|
||||
else:
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
metadata=metadata)
|
||||
metadata_dirty = True
|
||||
|
||||
# TODO extract model hash from source if possible to recreate link
|
||||
# TODO extract model hash from source if possible to recreate link
|
||||
|
||||
if not entry_filter or entry_filter(entry_name, entry_metadata):
|
||||
# only add files passing the optional filter
|
||||
extended_entry_data = dict()
|
||||
extended_entry_data.update(entry_metadata)
|
||||
extended_entry_data["name"] = entry_name
|
||||
extended_entry_data["display"] = entry_metadata.get("display", entry_name)
|
||||
extended_entry_data["path"] = path_in_location
|
||||
extended_entry_data["type"] = file_type
|
||||
extended_entry_data["typePath"] = type_path
|
||||
stat = entry_stat
|
||||
if stat:
|
||||
extended_entry_data["size"] = stat.st_size
|
||||
extended_entry_data["date"] = int(stat.st_mtime)
|
||||
if not entry_filter or entry_filter(entry_name, entry_metadata):
|
||||
# only add files passing the optional filter
|
||||
extended_entry_data = dict()
|
||||
extended_entry_data.update(entry_metadata)
|
||||
extended_entry_data["name"] = entry_name
|
||||
extended_entry_data["display"] = entry_metadata.get("display", entry_name)
|
||||
extended_entry_data["path"] = path_in_location
|
||||
extended_entry_data["type"] = file_type
|
||||
extended_entry_data["typePath"] = type_path
|
||||
stat = entry_stat
|
||||
if stat:
|
||||
extended_entry_data["size"] = stat.st_size
|
||||
extended_entry_data["date"] = int(stat.st_mtime)
|
||||
|
||||
result[entry_name] = extended_entry_data
|
||||
result[entry_name] = extended_entry_data
|
||||
|
||||
# folder recursion
|
||||
elif entry_is_dir:
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
# folder recursion
|
||||
elif entry_is_dir:
|
||||
if entry_name in metadata and isinstance(metadata[entry_name], dict):
|
||||
entry_metadata = metadata[entry_name]
|
||||
if not "display" in entry_metadata and entry_display != entry_name:
|
||||
metadata[entry_name]["display"] = entry_display
|
||||
entry_metadata["display"] = entry_display
|
||||
metadata_dirty = True
|
||||
elif entry_name != entry_display:
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
metadata=metadata)
|
||||
metadata_dirty = True
|
||||
elif entry_name != entry_display:
|
||||
entry_metadata = self._add_basic_metadata(path, entry_name,
|
||||
display_name=entry_display,
|
||||
save=False,
|
||||
metadata=metadata)
|
||||
metadata_dirty = True
|
||||
else:
|
||||
entry_metadata = dict()
|
||||
else:
|
||||
entry_metadata = dict()
|
||||
|
||||
entry_data = dict(
|
||||
name=entry_name,
|
||||
display=entry_metadata.get("display", entry_name),
|
||||
path=path_in_location,
|
||||
type="folder",
|
||||
typePath=["folder"]
|
||||
)
|
||||
if recursive:
|
||||
sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
|
||||
recursive=recursive)
|
||||
entry_data["children"] = sub_result
|
||||
|
||||
if not entry_filter or entry_filter(entry_name, entry_data):
|
||||
def get_size():
|
||||
total_size = 0
|
||||
for element in entry_data["children"].values():
|
||||
if "size" in element:
|
||||
total_size += element["size"]
|
||||
|
||||
return total_size
|
||||
|
||||
# only add folders passing the optional filter
|
||||
extended_entry_data = dict()
|
||||
extended_entry_data.update(entry_data)
|
||||
entry_data = dict(
|
||||
name=entry_name,
|
||||
display=entry_metadata.get("display", entry_name),
|
||||
path=path_in_location,
|
||||
type="folder",
|
||||
typePath=["folder"]
|
||||
)
|
||||
if recursive:
|
||||
extended_entry_data["size"] = get_size()
|
||||
sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
|
||||
recursive=recursive)
|
||||
entry_data["children"] = sub_result
|
||||
|
||||
result[entry_name] = extended_entry_data
|
||||
if not entry_filter or entry_filter(entry_name, entry_data):
|
||||
def get_size():
|
||||
total_size = 0
|
||||
for element in entry_data["children"].values():
|
||||
if "size" in element:
|
||||
total_size += element["size"]
|
||||
|
||||
return total_size
|
||||
|
||||
# only add folders passing the optional filter
|
||||
extended_entry_data = dict()
|
||||
extended_entry_data.update(entry_data)
|
||||
if recursive:
|
||||
extended_entry_data["size"] = get_size()
|
||||
|
||||
result[entry_name] = extended_entry_data
|
||||
except:
|
||||
# So something went wrong somewhere while processing this file entry - log that and continue
|
||||
self._logger.exception("Error while processing entry {}".format(entry_path))
|
||||
continue
|
||||
|
||||
# TODO recreate links if we have metadata less entries
|
||||
|
||||
|
||||
+155
-50
@@ -137,13 +137,14 @@ class PluginInfo(object):
|
||||
attr_disable = '__plugin_disable__'
|
||||
""" Module attribute which to call when disabling the plugin. """
|
||||
|
||||
def __init__(self, key, location, instance, name=None, version=None, description=None, author=None, url=None, license=None):
|
||||
def __init__(self, key, location, instance, name=None, version=None, description=None, author=None, url=None, license=None, parsed_metadata=None):
|
||||
self.key = key
|
||||
self.location = location
|
||||
self.instance = instance
|
||||
self.origin = None
|
||||
self.enabled = True
|
||||
self.blacklisted = False
|
||||
self.forced_disabled = False
|
||||
self.bundled = False
|
||||
self.loaded = False
|
||||
self.managable = True
|
||||
@@ -156,10 +157,17 @@ class PluginInfo(object):
|
||||
self._url = url
|
||||
self._license = license
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._cached_parsed_metadata = parsed_metadata
|
||||
|
||||
def validate(self, phase, additional_validators=None):
|
||||
result = True
|
||||
|
||||
if phase == "before_load":
|
||||
if phase == "before_import":
|
||||
result = not self.forced_disabled and not self.blacklisted and result
|
||||
|
||||
elif phase == "before_load":
|
||||
# if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__
|
||||
if hasattr(self.instance, self.__class__.attr_init):
|
||||
if not hasattr(self.instance, self.__class__.attr_load):
|
||||
@@ -193,7 +201,7 @@ class PluginInfo(object):
|
||||
|
||||
if additional_validators is not None:
|
||||
for validator in additional_validators:
|
||||
result = result and validator(phase, self)
|
||||
result = validator(phase, self) and result
|
||||
|
||||
return result
|
||||
|
||||
@@ -288,7 +296,9 @@ class PluginInfo(object):
|
||||
Returns:
|
||||
str: Name of the plugin, fallback is the plugin's identifier.
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_name, defaults=(self._name, self.key))
|
||||
return self._get_instance_attribute(self.__class__.attr_name,
|
||||
defaults=(self._name, self.key),
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def description(self):
|
||||
@@ -300,7 +310,9 @@ class PluginInfo(object):
|
||||
Returns:
|
||||
str or None: Description of the plugin.
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_description, default=self._description)
|
||||
return self._get_instance_attribute(self.__class__.attr_description,
|
||||
default=self._description,
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def disabling_discouraged(self):
|
||||
@@ -324,7 +336,9 @@ class PluginInfo(object):
|
||||
Returns:
|
||||
str or None: Version of the plugin.
|
||||
"""
|
||||
return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=self._version)
|
||||
return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version,
|
||||
default=self._version,
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def author(self):
|
||||
@@ -335,7 +349,9 @@ class PluginInfo(object):
|
||||
Returns:
|
||||
str or None: Author of the plugin.
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_author, default=self._author)
|
||||
return self._get_instance_attribute(self.__class__.attr_author,
|
||||
default=self._author,
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
@@ -346,7 +362,9 @@ class PluginInfo(object):
|
||||
Returns:
|
||||
str or None: Website URL for the plugin.
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_url, default=self._url)
|
||||
return self._get_instance_attribute(self.__class__.attr_url,
|
||||
default=self._url,
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def license(self):
|
||||
@@ -357,7 +375,9 @@ class PluginInfo(object):
|
||||
Returns:
|
||||
str or None: License of the plugin.
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_license, default=self._license)
|
||||
return self._get_instance_attribute(self.__class__.attr_license,
|
||||
default=self._license,
|
||||
incl_metadata=True)
|
||||
|
||||
@property
|
||||
def hooks(self):
|
||||
@@ -448,15 +468,79 @@ class PluginInfo(object):
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_disable, default=lambda: True)
|
||||
|
||||
def _get_instance_attribute(self, attr, default=None, defaults=None):
|
||||
def _get_instance_attribute(self, attr, default=None, defaults=None, incl_metadata=False):
|
||||
if self.instance is None or not hasattr(self.instance, attr):
|
||||
if defaults is not None:
|
||||
if incl_metadata and attr in self.parsed_metadata:
|
||||
return self.parsed_metadata[attr]
|
||||
|
||||
elif defaults is not None:
|
||||
for value in defaults:
|
||||
if callable(value):
|
||||
value = value()
|
||||
if value is not None:
|
||||
return value
|
||||
|
||||
return default
|
||||
|
||||
return getattr(self.instance, attr)
|
||||
|
||||
@property
|
||||
def parsed_metadata(self):
|
||||
if self._cached_parsed_metadata is None:
|
||||
self._cached_parsed_metadata = self._parse_metadata()
|
||||
return self._cached_parsed_metadata
|
||||
|
||||
def _parse_metadata(self):
|
||||
result = dict()
|
||||
|
||||
path = self.location
|
||||
if not path:
|
||||
return result
|
||||
|
||||
if os.path.isdir(path):
|
||||
path = os.path.join(self.location, "__init__.py")
|
||||
|
||||
if not os.path.isfile(path):
|
||||
return result
|
||||
|
||||
if not path.endswith(".py"):
|
||||
# we only support parsing plain text source files
|
||||
return result
|
||||
|
||||
self._logger.debug("Parsing plugin metadata for {} from AST of {}".format(self.key, path))
|
||||
|
||||
try:
|
||||
import ast
|
||||
|
||||
with open(path, "rb") as f:
|
||||
root = ast.parse(f.read())
|
||||
|
||||
assignments = filter(lambda x: isinstance(x, ast.Assign) and x.targets,
|
||||
root.body)
|
||||
|
||||
def extract_target_ids(node):
|
||||
return map(lambda x: x.id,
|
||||
filter(lambda x: isinstance(x, ast.Name), node.targets))
|
||||
|
||||
for key in (self.__class__.attr_name, self.__class__.attr_version, self.__class__.attr_author,
|
||||
self.__class__.attr_description, self.__class__.attr_url, self.__class__.attr_license):
|
||||
for a in reversed(assignments):
|
||||
targets = extract_target_ids(a)
|
||||
if key in targets:
|
||||
if isinstance(a.value, ast.Str):
|
||||
result[key] = a.value.s
|
||||
|
||||
elif isinstance(a.value, ast.Call) and hasattr(a.value, "func") \
|
||||
and a.value.func.id == "gettext" and a.value.args \
|
||||
and isinstance(a.value.args[0], ast.Str):
|
||||
result[key] = a.value.args[0].s
|
||||
|
||||
break
|
||||
except:
|
||||
pass
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class PluginManager(object):
|
||||
"""
|
||||
@@ -587,29 +671,37 @@ class PluginManager(object):
|
||||
|
||||
for entry in scandir(folder):
|
||||
try:
|
||||
if entry.is_dir() and os.path.isfile(os.path.join(entry.path, "__init__.py")):
|
||||
key = entry.name
|
||||
elif entry.is_file() and entry.name.endswith(".py"):
|
||||
key = entry.name[:-3] # strip off the .py extension
|
||||
if key.startswith("__"):
|
||||
# might be an __init__.py in our plugins folder, or something else we don't want
|
||||
# to handle
|
||||
if entry.is_dir():
|
||||
init_py = os.path.join(entry.path, "__init__.py")
|
||||
init_pyc = os.path.join(entry.path, "__init__.pyc")
|
||||
|
||||
if not os.path.isfile(init_py) and not os.path.isfile(init_pyc):
|
||||
# neither does exist, we ignore this
|
||||
continue
|
||||
|
||||
key = entry.name
|
||||
|
||||
elif entry.is_file():
|
||||
key, ext = os.path.splitext(entry.name)
|
||||
if ext not in (".py", ".pyc") or key.startswith("__"):
|
||||
# neither py nor pyc, or starts with __ (like __init__), we ignore this
|
||||
continue
|
||||
|
||||
else:
|
||||
# whatever this is, we ignore it
|
||||
continue
|
||||
|
||||
if key in existing or key in result or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]):
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
plugin = self._import_plugin_from_module(key, folder=folder)
|
||||
bundled = flagged_readonly
|
||||
|
||||
plugin = self._import_plugin_from_module(key, folder=folder, bundled=bundled)
|
||||
if plugin:
|
||||
plugin.origin = FolderOrigin("folder", folder)
|
||||
plugin.managable = not flagged_readonly and not actual_readonly
|
||||
plugin.bundled = flagged_readonly
|
||||
|
||||
plugin.enabled = False
|
||||
|
||||
result[key] = plugin
|
||||
except:
|
||||
self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder))
|
||||
@@ -676,6 +768,7 @@ class PluginManager(object):
|
||||
plugin = self._import_plugin_from_module(key, **kwargs)
|
||||
if plugin:
|
||||
plugin.origin = EntryPointOrigin("entry_point", group, module_name, package_name, version)
|
||||
plugin.enabled = False
|
||||
|
||||
# plugin is manageable if its location is writable and OctoPrint
|
||||
# is either not running from a virtual env or the plugin is
|
||||
@@ -685,19 +778,19 @@ class PluginManager(object):
|
||||
plugin.managable = os.access(plugin.location, os.W_OK) \
|
||||
and (not self._python_virtual_env
|
||||
or is_sub_path_of(plugin.location, self._python_prefix)
|
||||
or is_editable_install(self._python_install_dir,
|
||||
package_name,
|
||||
module_name,
|
||||
plugin.location))
|
||||
or is_editable_install(self._python_install_dir,
|
||||
package_name,
|
||||
module_name,
|
||||
plugin.location))
|
||||
|
||||
plugin.enabled = False
|
||||
result[key] = plugin
|
||||
except:
|
||||
self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
|
||||
|
||||
return result
|
||||
|
||||
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None):
|
||||
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None,
|
||||
author=None, url=None, license=None, bundled=False):
|
||||
# TODO error handling
|
||||
try:
|
||||
if folder:
|
||||
@@ -710,14 +803,41 @@ class PluginManager(object):
|
||||
self.logger.warn("Could not locate plugin {key}".format(key=key))
|
||||
return None
|
||||
|
||||
if self._is_plugin_blacklisted(key) or (version is not None and self._is_plugin_version_blacklisted(key, version)):
|
||||
plugin = PluginInfo(key, module[1], None, name=name, version=version, description=summary, author=author, url=url, license=license)
|
||||
# Create a simple dummy entry first ...
|
||||
plugin = PluginInfo(key, module[1], None, name=name, version=version, description=summary, author=author,
|
||||
url=url, license=license)
|
||||
plugin.bundled = bundled
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
self.logger.info("Plugin {} is disabled.".format(plugin))
|
||||
plugin.forced_disabled = True
|
||||
|
||||
if self._is_plugin_blacklisted(key) or (plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version)):
|
||||
self.logger.warn("Plugin {} is blacklisted.".format(plugin))
|
||||
plugin.blacklisted = True
|
||||
self.logger.warn("Plugin {} is blacklisted. Not importing it, only registering a dummy entry.".format(plugin))
|
||||
|
||||
if not plugin.validate("before_import", additional_validators=self.plugin_validators):
|
||||
return plugin
|
||||
|
||||
plugin = self._import_plugin(key, *module, name=name, version=version, summary=summary, author=author, url=url, license=license)
|
||||
if plugin is None:
|
||||
# ... then create and return the real one
|
||||
return self._import_plugin(key, *module,
|
||||
name=name, version=version, summary=summary, author=author, url=url,
|
||||
license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata)
|
||||
|
||||
def _import_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
|
||||
try:
|
||||
instance = imp.load_module(key, f, filename, description)
|
||||
plugin = PluginInfo(key, filename, instance,
|
||||
name=name,
|
||||
version=version,
|
||||
description=summary,
|
||||
author=author,
|
||||
url=url,
|
||||
license=license,
|
||||
parsed_metadata=parsed_metadata)
|
||||
plugin.bundled = bundled
|
||||
except:
|
||||
self.logger.exception("Error loading plugin {key}".format(key=key))
|
||||
return None
|
||||
|
||||
if plugin.check():
|
||||
@@ -726,15 +846,6 @@ class PluginManager(object):
|
||||
self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin)))
|
||||
return None
|
||||
|
||||
|
||||
def _import_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None):
|
||||
try:
|
||||
instance = imp.load_module(key, f, filename, description)
|
||||
return PluginInfo(key, filename, instance, name=name, version=version, description=summary, author=author, url=url, license=license)
|
||||
except:
|
||||
self.logger.exception("Error loading plugin {key}".format(key=key))
|
||||
return None
|
||||
|
||||
def _is_plugin_disabled(self, key):
|
||||
return key in self.plugin_disabled_list or key.endswith('disabled')
|
||||
|
||||
@@ -765,7 +876,7 @@ class PluginManager(object):
|
||||
# 1st pass: loading the plugins
|
||||
for name, plugin in plugins.items():
|
||||
try:
|
||||
if not plugin.blacklisted:
|
||||
if not plugin.blacklisted and not plugin.forced_disabled:
|
||||
self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations)
|
||||
except PluginNeedsRestart:
|
||||
pass
|
||||
@@ -779,7 +890,7 @@ class PluginManager(object):
|
||||
# 2nd pass: enabling those plugins that need enabling
|
||||
for name, plugin in plugins.items():
|
||||
try:
|
||||
if plugin.loaded and not self._is_plugin_disabled(name):
|
||||
if plugin.loaded and not plugin.forced_disabled:
|
||||
if plugin.blacklisted:
|
||||
self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin))
|
||||
continue
|
||||
@@ -836,14 +947,8 @@ class PluginManager(object):
|
||||
plugin.load()
|
||||
plugin.validate("after_load", additional_validators=self.plugin_validators)
|
||||
self.on_plugin_loaded(name, plugin)
|
||||
|
||||
plugin.loaded = True
|
||||
|
||||
# we might only now have a version, so check again if we are blacklisted
|
||||
if not plugin.blacklisted and plugin.version and self._is_plugin_version_blacklisted(plugin.key,
|
||||
plugin.version):
|
||||
plugin.blacklisted = True
|
||||
|
||||
self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals()))
|
||||
except PluginLifecycleException as e:
|
||||
raise e
|
||||
|
||||
@@ -1481,7 +1481,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
:return: the current settings of the plugin, as a dictionary
|
||||
"""
|
||||
from flask.ext.login import current_user
|
||||
from flask_login import current_user
|
||||
import copy
|
||||
|
||||
data = copy.deepcopy(self._settings.get_all_data(merged=True))
|
||||
@@ -1861,6 +1861,47 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
destination_extensions=["gco", "gcode", "g"]
|
||||
)
|
||||
|
||||
def get_slicer_profiles(self, profile_path):
|
||||
"""
|
||||
Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer.
|
||||
|
||||
For compatibility reasons with existing slicing plugins this method defaults to returning profiles parsed from
|
||||
.profile files in the plugin's ``profile_path``, utilizing the :func:`SlicingPlugin.get_slicer_profile` method
|
||||
of the plugin implementation.
|
||||
|
||||
Arguments:
|
||||
profile_path (str): The base folder where OctoPrint stores this slicer plugin's profiles
|
||||
"""
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
import octoprint.util
|
||||
|
||||
profiles = dict()
|
||||
for entry in scandir(profile_path):
|
||||
if not entry.name.endswith(".profile") or octoprint.util.is_hidden_path(entry.name):
|
||||
# we are only interested in profiles and no hidden files
|
||||
continue
|
||||
|
||||
profile_name = entry.name[:-len(".profile")]
|
||||
profiles[profile_name] = self.get_slicer_profile(entry.path)
|
||||
return profiles
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_slicer_profiles_lastmodified(self, profile_path):
|
||||
import os
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
lms = [os.stat(profile_path).st_mtime]
|
||||
lms += [os.stat(entry.path).st_mtime for entry in scandir(profile_path) if entry.name.endswith(".profile")]
|
||||
return max(lms)
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_slicer_default_profile(self):
|
||||
"""
|
||||
|
||||
@@ -23,7 +23,7 @@ from collections import OrderedDict
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.util import utmify
|
||||
from flask.ext.babel import gettext
|
||||
from flask_babel import gettext
|
||||
from octoprint import __version__ as OCTOPRINT_VERSION
|
||||
|
||||
class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
@@ -256,7 +256,7 @@ $(function() {
|
||||
text += "</ul>";
|
||||
|
||||
if (rest) {
|
||||
text += gettext(_.sprintf("... and %(rest)d more.", {rest: rest}));
|
||||
text += "<p>" + gettext(_.sprintf("... and %(rest)d more.", {rest: rest})) + "</p>";
|
||||
}
|
||||
|
||||
text += "<small>" + gettext("You can edit your announcement subscriptions under Settings > Announcements.") + "</small>";
|
||||
|
||||
@@ -6,7 +6,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from flask.ext.babel import gettext
|
||||
from flask_babel import gettext
|
||||
from .subwizards import Subwizards
|
||||
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import octoprint.plugin
|
||||
|
||||
import sys
|
||||
import inspect
|
||||
from flask.ext.babel import gettext
|
||||
from flask_babel import gettext
|
||||
|
||||
|
||||
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
|
||||
|
||||
@@ -83,8 +83,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
engine = self._settings.get(["cura_engine"])
|
||||
if not self._is_engine_configured(cura_engine=engine):
|
||||
self._logger.info("Path to CuraEngine has not been configured or does not exist (currently set to %r), "
|
||||
"Cura will not be selectable for slicing" % engine)
|
||||
self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), "
|
||||
u"Cura will not be selectable for slicing" % engine)
|
||||
|
||||
##~~ BlueprintPlugin API
|
||||
|
||||
@@ -101,23 +101,23 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
try:
|
||||
profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path])
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while converting the imported profile")
|
||||
return flask.make_response("Something went wrong while converting imported profile: {message}".format(message=str(e)), 500)
|
||||
self._logger.exception(u"Error while converting the imported profile")
|
||||
return flask.make_response(u"Something went wrong while converting imported profile: {message}".format(message=str(e)), 500)
|
||||
|
||||
else:
|
||||
self._logger.warn("No profile file included for importing, aborting")
|
||||
return flask.make_response("No file included", 400)
|
||||
self._logger.warn(u"No profile file included for importing, aborting")
|
||||
return flask.make_response(u"No file included", 400)
|
||||
|
||||
if profile_dict is None:
|
||||
self._logger.warn("Could not convert profile, aborting")
|
||||
return flask.make_response("Could not convert Cura profile", 400)
|
||||
self._logger.warn(u"Could not convert profile, aborting")
|
||||
return flask.make_response(u"Could not convert Cura profile", 400)
|
||||
|
||||
name, _ = os.path.splitext(filename)
|
||||
|
||||
# default values for name, display name and description
|
||||
profile_name = _sanitize_name(name)
|
||||
profile_display_name = name
|
||||
profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now()))
|
||||
profile_description = u"Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now()))
|
||||
profile_allow_overwrite = False
|
||||
profile_make_default = False
|
||||
|
||||
@@ -142,15 +142,15 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
display_name=profile_display_name,
|
||||
description=profile_description)
|
||||
except octoprint.slicing.ProfileAlreadyExists:
|
||||
self._logger.warn("Profile {profile_name} already exists, aborting".format(**locals()))
|
||||
return flask.make_response("A profile named {profile_name} already exists for slicer cura".format(**locals()), 409)
|
||||
self._logger.warn(u"Profile {profile_name} already exists, aborting".format(**locals()))
|
||||
return flask.make_response(u"A profile named {profile_name} already exists for slicer cura".format(**locals()), 409)
|
||||
|
||||
if profile_make_default:
|
||||
try:
|
||||
self._slicing_manager.set_default_profile("cura", profile_name)
|
||||
except octoprint.slicing.UnknownProfile:
|
||||
self._logger.warn("Profile {profile_name} could not be set as default, aborting".format(**locals()))
|
||||
return flask.make_response("The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500)
|
||||
self._logger.warn(u"Profile {profile_name} could not be set as default, aborting".format(**locals()))
|
||||
return flask.make_response(u"The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500)
|
||||
|
||||
result = dict(
|
||||
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
|
||||
@@ -183,8 +183,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
new_debug_logging = self._settings.get_boolean(["debug_logging"])
|
||||
|
||||
if old_engine != new_engine and not self._is_engine_configured(new_engine):
|
||||
self._logger.info("Path to CuraEngine has not been configured or does not exist (currently set to %r), "
|
||||
"Cura will not be selectable for slicing" % new_engine)
|
||||
self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), "
|
||||
u"Cura will not be selectable for slicing" % new_engine)
|
||||
|
||||
if old_debug_logging != new_debug_logging:
|
||||
if new_debug_logging:
|
||||
@@ -276,7 +276,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
executable = normalize_path(self._settings.get(["cura_engine"]))
|
||||
if not executable:
|
||||
return False, "Path to CuraEngine is not configured "
|
||||
return False, u"Path to CuraEngine is not configured "
|
||||
|
||||
working_dir = os.path.dirname(executable)
|
||||
|
||||
@@ -463,7 +463,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
try:
|
||||
profile_dict = yaml.safe_load(f)
|
||||
except:
|
||||
raise IOError("Couldn't read profile from {path}".format(path=path))
|
||||
raise IOError(u"Couldn't read profile from {path}".format(path=path))
|
||||
|
||||
if "gcode_flavor" in profile_dict and not isinstance(profile_dict["gcode_flavor"], (list, tuple)):
|
||||
profile_dict["gcode_flavor"] = parse_gcode_flavor(profile_dict["gcode_flavor"])
|
||||
@@ -485,7 +485,7 @@ def _sanitize_name(name):
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
raise ValueError(u"name must not contain / or \\")
|
||||
|
||||
import string
|
||||
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
|
||||
|
||||
@@ -11,7 +11,7 @@ The SSDP/UPNP implementations has been largely inspired by https://gist.github.c
|
||||
|
||||
import logging
|
||||
import flask
|
||||
from flask.ext.babel import gettext
|
||||
from flask_babel import gettext
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from builtins import range
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
from octoprint.settings import settings
|
||||
|
||||
from octoprint.server import NO_CONTENT, admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
from flask_babel import gettext
|
||||
from werkzeug.utils import secure_filename
|
||||
from werkzeug.exceptions import BadRequest
|
||||
import yaml
|
||||
|
||||
import os
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
class LoggingPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.BlueprintPlugin):
|
||||
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def get_all(self):
|
||||
files = self._getLogFiles()
|
||||
free, total = self._get_usage()
|
||||
loggers = self._get_available_loggers()
|
||||
levels = self._get_logging_levels()
|
||||
return jsonify(logs=dict(files=files, free=free, total=total),
|
||||
setup=dict(loggers=loggers, levels=levels))
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def get_log_files(self):
|
||||
files = self._getLogFiles()
|
||||
free, total = self._get_usage()
|
||||
return jsonify(files=files, free=free, total=total)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def download_log(self, filename):
|
||||
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def delete_log(self, filename):
|
||||
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
|
||||
if not os.path.exists(secure):
|
||||
return make_response("File not found: %s" % filename, 404)
|
||||
|
||||
os.remove(secure)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def get_logging_setup(self):
|
||||
loggers = self._get_available_loggers()
|
||||
levels = self._get_logging_levels()
|
||||
return jsonify(loggers=loggers, levels=levels)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def get_logging_levels_api(self):
|
||||
return jsonify(self._get_logging_levels())
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def set_logging_levels_api(self):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not isinstance(json_data, dict):
|
||||
return make_response("Invalid log level configuration", 400)
|
||||
|
||||
# TODO validate further
|
||||
|
||||
self._set_logging_levels(json_data)
|
||||
return self.get_logging_levels_api()
|
||||
|
||||
def _get_usage(self):
|
||||
import psutil
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
|
||||
return usage.free, usage.total
|
||||
|
||||
def _getLogFiles(self):
|
||||
files = []
|
||||
basedir = settings().getBaseFolder("logs")
|
||||
for entry in scandir(basedir):
|
||||
files.append({
|
||||
"name": entry.name,
|
||||
"date": int(entry.stat().st_mtime),
|
||||
"size": entry.stat().st_size,
|
||||
"refs": {
|
||||
"resource": url_for(".download_log", filename=entry.name, _external=True),
|
||||
"download": url_for("index", _external=True) + "downloads/logs/" + entry.name
|
||||
}
|
||||
})
|
||||
|
||||
return files
|
||||
|
||||
def _get_available_loggers(self):
|
||||
return filter(lambda x: self._is_managed_logger(x), self._logger.manager.loggerDict.keys())
|
||||
|
||||
def _get_logging_file(self):
|
||||
# TODO this might not be the logging config we are actually using here (command line parameter...)
|
||||
return os.path.join(self._settings.getBaseFolder("base"), "logging.yaml")
|
||||
|
||||
def _get_logging_config(self):
|
||||
logging_file = self._get_logging_file()
|
||||
|
||||
config_from_file = {}
|
||||
if os.path.exists(logging_file) and os.path.isfile(logging_file):
|
||||
import yaml
|
||||
with open(logging_file, "r") as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
return config_from_file
|
||||
|
||||
def _get_logging_levels(self):
|
||||
config = self._get_logging_config()
|
||||
if config is None or not isinstance(config, dict):
|
||||
return dict()
|
||||
|
||||
return dict((key, value.get("level"))
|
||||
for key, value in config.get("loggers", dict()).items()
|
||||
if isinstance(value, dict) and "level" in value)
|
||||
|
||||
def _set_logging_levels(self, new_levels):
|
||||
import logging
|
||||
|
||||
config = self._get_logging_config()
|
||||
|
||||
# clear all configured logging levels
|
||||
if config.has_key("loggers"):
|
||||
purge = []
|
||||
for component in config["loggers"]:
|
||||
if not self._is_managed_logger(component): continue
|
||||
try:
|
||||
del config["loggers"][component]["level"]
|
||||
self._logger.manager.loggerDict[component].setLevel(logging.INFO)
|
||||
except:
|
||||
pass
|
||||
if len(config["loggers"][component]) == 0:
|
||||
purge.append(component)
|
||||
else:
|
||||
config["loggers"] = dict()
|
||||
|
||||
# update all logging levels
|
||||
for logger, level in new_levels.items():
|
||||
if not config["loggers"].has_key(logger):
|
||||
config["loggers"][logger] = dict()
|
||||
config["loggers"][logger]["level"] = level
|
||||
|
||||
# delete empty entries
|
||||
config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)}
|
||||
|
||||
# save
|
||||
with octoprint.util.atomic_write(self._get_logging_file(), "wb", max_permissions=0o666) as f:
|
||||
yaml.safe_dump(config, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
# set runtime logging levels now
|
||||
for logger, level in new_levels.items():
|
||||
level = logging.getLevelName(level)
|
||||
|
||||
self._logger.info("Setting logger {} level to {}".format(logger, level))
|
||||
self._logger.manager.loggerDict[logger].setLevel(level)
|
||||
|
||||
def _is_managed_logger(self, logger):
|
||||
return logger and (logger.startswith("octoprint") or logger.startswith("tornado"))
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="settings", custom_bindings=True)
|
||||
]
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=["js/logging.js"],
|
||||
less=["less/logging.less"],
|
||||
css=["css/logging.css"])
|
||||
|
||||
__plugin_name__ = "Logging"
|
||||
__plugin_author__ = "Shawn Bruce, based on work by Gina Häußge and Marc Hannappel"
|
||||
__plugin_description__ = "Provides access to OctoPrint's logs and logging configuration."
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to retrieve "
|
||||
"OctoPrint's logs or modify the current logging levels through "
|
||||
"the web interface.")
|
||||
__plugin_implementation__ = LoggingPlugin()
|
||||
@@ -0,0 +1 @@
|
||||
table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default}
|
||||
@@ -0,0 +1,214 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
|
||||
var OctoPrintLoggingClient = function(base) {
|
||||
this.base = base;
|
||||
|
||||
this.baseUrl = this.base.getBlueprintUrl("logging");
|
||||
this.logsUrl = this.baseUrl + "logs";
|
||||
this.setupUrl = this.baseUrl + "setup";
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.baseUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.listLogs = function(opts) {
|
||||
return this.base.get(this.logsUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) {
|
||||
var fileUrl = this.logsUrl + "/" + file;
|
||||
return this.base.delete(fileUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) {
|
||||
var fileUrl = this.logsUrl + "/" + file;
|
||||
return this.base.download(fileUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) {
|
||||
return this.base.putJson(this.setupUrl + "/levels", config, opts);
|
||||
};
|
||||
|
||||
//~~ wrapper for backwards compatibility
|
||||
|
||||
var DeprecatedOctoPrintLogsClient = function(base) {
|
||||
this.base = base;
|
||||
this.wrapped = this.base.plugins.logging;
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.list = function(opts) {
|
||||
log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead");
|
||||
return this.wrapped.listLogs(opts);
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) {
|
||||
log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead");
|
||||
return this.wrapped.deleteLog(file, opts);
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) {
|
||||
log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead");
|
||||
return this.wrapped.downloadLog(file, opts);
|
||||
};
|
||||
|
||||
// register plugin component
|
||||
OctoPrintClient.registerPluginComponent("logging", OctoPrintLoggingClient);
|
||||
|
||||
// also register deprecated client under old endpoint
|
||||
OctoPrintClient.registerComponent("logs", DeprecatedOctoPrintLogsClient);
|
||||
|
||||
return OctoPrintLoggingClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
function LoggingViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.availableLoggers = ko.observableArray();
|
||||
self.availableLoggersName = ko.observable();
|
||||
self.availableLoggersLevel = ko.observable();
|
||||
self.configuredLoggers = ko.observableArray();
|
||||
self.configuredLoggersChanged = false;
|
||||
|
||||
self.availableLoggersSorted = ko.computed(function() {
|
||||
return _.sortBy(self.availableLoggers());
|
||||
});
|
||||
|
||||
self.configuredLoggersSorted = ko.computed(function() {
|
||||
return _.sortBy(self.configuredLoggers(), function (o) {
|
||||
o.level();
|
||||
return o.component;
|
||||
});
|
||||
});
|
||||
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
"logFiles",
|
||||
{
|
||||
"name": function(a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
},
|
||||
"modification": function(a, b) {
|
||||
// sorts descending
|
||||
if (a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
},
|
||||
"size": function(a, b) {
|
||||
// sorts descending
|
||||
if (a["size"] > b["size"]) return -1;
|
||||
if (a["size"] < b["size"]) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
CONFIG_LOGFILESPERPAGE
|
||||
);
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.logging.get()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.fromLogsResponse(response.logs);
|
||||
self.fromSetupResponse(response.setup);
|
||||
};
|
||||
|
||||
self.fromLogsResponse = function(response) {
|
||||
if (!response) return;
|
||||
|
||||
var files = response.files;
|
||||
if (files === undefined)
|
||||
return;
|
||||
|
||||
self.listHelper.updateItems(files);
|
||||
};
|
||||
|
||||
self.fromSetupResponse = function(response) {
|
||||
if (!response) return;
|
||||
|
||||
// levels
|
||||
var levels = [];
|
||||
var configuredLoggers = [];
|
||||
_.each(response.levels, function(level, logger) {
|
||||
var item = {component: logger, level: ko.observable(level)};
|
||||
item.level.subscribe(function() {
|
||||
self.configuredLoggersHasChanged();
|
||||
});
|
||||
levels.push(item);
|
||||
configuredLoggers.push(logger);
|
||||
});
|
||||
self.configuredLoggers(levels);
|
||||
|
||||
// loggers
|
||||
var availableLoggers = _.without(response.loggers, configuredLoggers);
|
||||
self.availableLoggers(availableLoggers);
|
||||
};
|
||||
|
||||
self.configuredLoggersHasChanged = function () {
|
||||
self.configuredLoggersChanged = true;
|
||||
};
|
||||
|
||||
self.addLogger = function() {
|
||||
var component = self.availableLoggersName();
|
||||
var level = self.availableLoggersLevel();
|
||||
|
||||
self.configuredLoggers.push({component: component, level: ko.observable(level)});
|
||||
self.availableLoggers.remove(component);
|
||||
|
||||
self.configuredLoggersHasChanged();
|
||||
};
|
||||
|
||||
self.removeLogger = function(logger) {
|
||||
self.configuredLoggers.remove(logger);
|
||||
self.availableLoggers.push(logger.component);
|
||||
|
||||
self.configuredLoggersHasChanged();
|
||||
};
|
||||
|
||||
self.removeFile = function(filename) {
|
||||
OctoPrint.plugins.logging.deleteLog(filename)
|
||||
.done(self.requestData);
|
||||
};
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onSettingsBeforeSave = function () {
|
||||
if ( self.configuredLoggersChanged ) {
|
||||
console.log("ConfiguredLoggers has changed. Saving!");
|
||||
var levels = {};
|
||||
_.each(self.configuredLoggers(), function(data) {
|
||||
levels[data.component] = data.level();
|
||||
});
|
||||
OctoPrint.plugins.logging.updateLevels(levels);
|
||||
} else {
|
||||
console.log("ConfiguredLoggers has not changed. Not saving.");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: LoggingViewModel,
|
||||
additionalNames: ["logsViewModel"],
|
||||
dependencies: ["loginStateViewModel"],
|
||||
elements: ["#settings_plugin_logging"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
table {
|
||||
th, td {
|
||||
&.settings_logs_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&.settings_logs_size {
|
||||
text-align: right;
|
||||
width: 70px;
|
||||
}
|
||||
|
||||
&.settings_logs_date {
|
||||
text-align: left;
|
||||
width: 130px;
|
||||
}
|
||||
|
||||
&.settings_logs_action {
|
||||
width: 70px;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<h3>{{ _('Logs') }}</h3>
|
||||
|
||||
<div class="pull-right">
|
||||
<small>
|
||||
{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('modification'); }">{{ _('Modification date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a>
|
||||
</small>
|
||||
</div>
|
||||
<table class="table table-striped table-hover table-condensed table-hover" id="log_files">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_logs_name">{{ _('Name') }}</th>
|
||||
<th class="settings_logs_size">{{ _('Size') }}</th>
|
||||
<th class="settings_logs_date">{{ _('Date') }}</th>
|
||||
<th class="settings_logs_action">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: listHelper.paginatedItems">
|
||||
<tr data-bind="attr: {title: name}">
|
||||
<td class="settings_logs_name" data-bind="text: name"></td>
|
||||
<td class="settings_logs_size" data-bind="text: formatSize(size)"></td>
|
||||
<td class="settings_logs_date" data-bind="text: formatDate(date)"></td>
|
||||
<td class="settings_logs_action">
|
||||
<a href="#" class="icon-trash" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeFile($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a> | <a href="#" class="icon-download" data-bind="attr: {href: refs.download}"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: listHelper.currentPage() === 0}">
|
||||
<a href="#" data-bind="click: listHelper.prevPage">«</a>
|
||||
</li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: listHelper.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.listHelper.currentPage(), disabled: $data.number === -1 }">
|
||||
<a href="#" data-bind="text: $data.text, click: function() { $root.listHelper.changePage($data.number); }"></a>
|
||||
</li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: listHelper.currentPage() === listHelper.lastPage()}">
|
||||
<a href="#" data-bind="click: listHelper.nextPage">»</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Logging Levels') }}</h3>
|
||||
<form class="form-horizontal">
|
||||
|
||||
<div class="row-fluid">
|
||||
<div class="span8"><h5>{{ _('Name') }}</h5></div>
|
||||
<div class="span2"><h5>{{ _('Level') }}</h5></div>
|
||||
</div>
|
||||
<div data-bind="foreach: configuredLoggersSorted">
|
||||
<div class="row-fluid" style="margin-bottom: 5px">
|
||||
<div class="span8">
|
||||
<span data-bind="text: component"></span>
|
||||
</div>
|
||||
<div class="span3">
|
||||
<select data-bind="value: level, event: { change: $parent.configuredLoggersHasChanged }" class="input-medium">
|
||||
<option value="DEBUG">DEBUG</option>
|
||||
<option value="INFO">INFO</option>
|
||||
<option value="WARNING">WARNING</option>
|
||||
<option value="ERROR">ERROR</option>
|
||||
<option value="CRITICAL">CRITICAL</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="span1">
|
||||
<a title="{{ _('Remove') }}" class="btn btn-danger" data-bind="click: $parent.removeLogger"><i class="icon-trash"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="row-fluid" style="margin-bottom: 5px">
|
||||
<div class="span8">
|
||||
<select class="input-block-level" data-bind="options: availableLoggersSorted, value: availableLoggersName"></select>
|
||||
</div>
|
||||
<div class="span3">
|
||||
<select class="input-medium" data-bind="value: availableLoggersLevel">
|
||||
<option value="DEBUG">DEBUG</option>
|
||||
<option value="INFO">INFO</option>
|
||||
<option value="WARNING">WARNING</option>
|
||||
<option value="ERROR">ERROR</option>
|
||||
<option value="CRITICAL">CRITICAL</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="span1">
|
||||
<a title="{{ _('Add') }}" class="btn btn-primary" data-bind="click: $root.addLogger"><i class="icon-plus"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
|
||||
import flask
|
||||
import os
|
||||
|
||||
from flask.ext.babel import gettext
|
||||
from flask_babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ from octoprint.util.version import get_octoprint_version_string, get_octoprint_v
|
||||
from octoprint.util.platform import get_os
|
||||
|
||||
from flask import jsonify, make_response
|
||||
from flask.ext.babel import gettext
|
||||
from flask_babel import gettext
|
||||
|
||||
import logging
|
||||
import sarge
|
||||
@@ -561,13 +561,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if plugin.key == "pluginmanager":
|
||||
return make_response("Can't enable/disable Plugin Manager", 400)
|
||||
|
||||
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
|
||||
safe_mode_victim = getattr(plugin, "safe_mode_victim", False)
|
||||
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
|
||||
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
|
||||
|
||||
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
|
||||
safe_mode_victim = getattr(plugin, "safe_mode_victim", False)
|
||||
needs_restart_api = (needs_restart or safe_mode_victim) and not pending
|
||||
needs_restart_api = (needs_restart or safe_mode_victim or plugin.forced_disabled) and not pending
|
||||
needs_refresh_api = needs_refresh and not pending
|
||||
needs_reconnect_api = needs_reconnect and not pending
|
||||
|
||||
@@ -677,12 +678,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._settings.global_set(["plugins", "_disabled"], disabled_list)
|
||||
self._settings.save(force=True)
|
||||
|
||||
if not needs_restart and not getattr(plugin, "safe_mode_victim", False):
|
||||
if not needs_restart and not plugin.forced_disabled and not getattr(plugin, "safe_mode_victim", False):
|
||||
self._plugin_manager.enable_plugin(plugin.key)
|
||||
else:
|
||||
if plugin.key in self._pending_disable:
|
||||
self._pending_disable.remove(plugin.key)
|
||||
elif (not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_enable:
|
||||
elif not plugin.enabled and plugin.key not in self._pending_enable:
|
||||
self._pending_enable.add(plugin.key)
|
||||
|
||||
def _mark_plugin_disabled(self, plugin, needs_restart=False):
|
||||
@@ -692,12 +693,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._settings.global_set(["plugins", "_disabled"], disabled_list)
|
||||
self._settings.save(force=True)
|
||||
|
||||
if not needs_restart and not getattr(plugin, "safe_mode_victim", False):
|
||||
if not needs_restart and not plugin.forced_disabled and not getattr(plugin, "safe_mode_victim", False):
|
||||
self._plugin_manager.disable_plugin(plugin.key)
|
||||
else:
|
||||
if plugin.key in self._pending_enable:
|
||||
self._pending_enable.remove(plugin.key)
|
||||
elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable:
|
||||
elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable:
|
||||
self._pending_disable.add(plugin.key)
|
||||
|
||||
def _fetch_all_data(self, async=False):
|
||||
@@ -920,10 +921,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
managable=plugin.managable,
|
||||
enabled=plugin.enabled,
|
||||
blacklisted=plugin.blacklisted,
|
||||
forced_disabled=plugin.forced_disabled,
|
||||
safe_mode_victim=getattr(plugin, "safe_mode_victim", False),
|
||||
safe_mode_enabled=getattr(plugin, "safe_mode_enabled", False),
|
||||
pending_enable=(not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False) and plugin.key in self._pending_enable),
|
||||
pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key in self._pending_disable),
|
||||
pending_enable=(not plugin.enabled and not getattr(plugin, "safe_mode_victim", False) and plugin.key in self._pending_enable),
|
||||
pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key in self._pending_disable),
|
||||
pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")),
|
||||
pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")),
|
||||
origin=plugin.origin.type,
|
||||
|
||||
@@ -205,6 +205,16 @@ $(function() {
|
||||
self.hiddenNoticeNotifications = {};
|
||||
self.noticeCount = ko.observable(0);
|
||||
|
||||
self.notification = undefined;
|
||||
self.logContents = {
|
||||
steps: [],
|
||||
action: {
|
||||
reload: false,
|
||||
refresh: false,
|
||||
reconnect: false
|
||||
}
|
||||
};
|
||||
|
||||
self.noticeCountText = ko.pureComputed(function() {
|
||||
var count = self.noticeCount();
|
||||
if (count == 0) {
|
||||
@@ -222,7 +232,7 @@ $(function() {
|
||||
|
||||
self.enableToggle = function(data) {
|
||||
var command = self._getToggleCommand(data);
|
||||
var not_safemode_victim = !data.safe_mode_victim || data.safe_mode_enabled;
|
||||
var not_safemode_victim = !data.safe_mode_victim;
|
||||
var not_blacklisted = !data.blacklisted;
|
||||
return self.enableManagement() && (command == "disable" || (not_safemode_victim && not_blacklisted)) && data.key != 'pluginmanager';
|
||||
};
|
||||
@@ -462,7 +472,7 @@ $(function() {
|
||||
};
|
||||
|
||||
if (self._getToggleCommand(data) == "enable") {
|
||||
if (data.safe_mode_victim && !data.safe_mode_enabled) return;
|
||||
if (data.safe_mode_victim) return;
|
||||
OctoPrint.plugins.pluginmanager.enable(data.key)
|
||||
.done(onSuccess)
|
||||
.fail(onError);
|
||||
@@ -701,133 +711,138 @@ $(function() {
|
||||
return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible"));
|
||||
};
|
||||
|
||||
self._displayNotification = function(response, action, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError) {
|
||||
var notification;
|
||||
self._displayPluginManagementNotification = function(response, action, plugin) {
|
||||
self.logContents.action.restart = self.logContents.action.restart || response.needs_restart;
|
||||
self.logContents.action.refresh = self.logContents.action.refresh || response.needs_refresh;
|
||||
self.logContents.action_reconnect = self.logContents.action.reconnect || response.needs_reconnect;
|
||||
self.logContents.steps.push({action: action, plugin: plugin, result: response.result});
|
||||
|
||||
var beforeClose = function(notification) {
|
||||
self.notifications = _.without(self.notifications, notification);
|
||||
};
|
||||
var title = gettext("Plugin management log");
|
||||
var text = "<p><ul>";
|
||||
|
||||
if (response.result) {
|
||||
if (action == "install" && response.plugin && response.plugin.blacklisted) {
|
||||
notification = new PNotify({
|
||||
title: titleSuccess,
|
||||
text: textSuccess,
|
||||
type: "warning",
|
||||
callbacks: {
|
||||
before_close: beforeClose
|
||||
},
|
||||
hide: false
|
||||
})
|
||||
} else if (response.needs_restart) {
|
||||
var options = {
|
||||
title: titleSuccess,
|
||||
text: textRestart,
|
||||
buttons: {
|
||||
closer: true,
|
||||
sticker: false
|
||||
},
|
||||
callbacks: {
|
||||
before_close: beforeClose
|
||||
},
|
||||
hide: false
|
||||
};
|
||||
|
||||
var restartClicked = false;
|
||||
if (self.restartCommandSpec) {
|
||||
options.confirm = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Restart now"),
|
||||
click: function (notice) {
|
||||
if (restartClicked) return;
|
||||
restartClicked = true;
|
||||
showConfirmationDialog({
|
||||
message: gettext("<strong>This will restart your OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
|
||||
onproceed: function() {
|
||||
OctoPrint.system.executeCommand("core", "restart")
|
||||
.done(function() {
|
||||
notice.remove();
|
||||
new PNotify({
|
||||
title: gettext("Restart in progress"),
|
||||
text: gettext("The server is now being restarted in the background")
|
||||
})
|
||||
})
|
||||
.fail(function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
text: gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.")
|
||||
})
|
||||
});
|
||||
},
|
||||
onclose: function() {
|
||||
restartClicked = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
notification = PNotify.singleButtonNotify(options);
|
||||
} else if (response.needs_refresh) {
|
||||
var refreshClicked = false;
|
||||
notification = PNotify.singleButtonNotify({
|
||||
title: titleSuccess,
|
||||
text: textReload,
|
||||
confirm: {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Reload now"),
|
||||
click: function () {
|
||||
if (refreshClicked) return;
|
||||
refreshClicked = true;
|
||||
location.reload(true);
|
||||
}
|
||||
}]
|
||||
},
|
||||
buttons: {
|
||||
closer: true,
|
||||
sticker: false
|
||||
},
|
||||
callbacks: {
|
||||
before_close: beforeClose
|
||||
},
|
||||
hide: false
|
||||
})
|
||||
} else if (response.needs_reconnect) {
|
||||
notification = new PNotify({
|
||||
title: titleSuccess,
|
||||
text: textReconnect,
|
||||
callbacks: {
|
||||
before_close: beforeClose
|
||||
},
|
||||
hide: false
|
||||
})
|
||||
var steps = self.logContents.steps;
|
||||
if (steps.length > 5) {
|
||||
var count = steps.length - 5;
|
||||
var line;
|
||||
if (count > 1) {
|
||||
line = gettext("%(count)d earlier actions...");
|
||||
} else {
|
||||
notification = new PNotify({
|
||||
title: titleSuccess,
|
||||
text: textSuccess,
|
||||
type: "success",
|
||||
callbacks: {
|
||||
before_close: beforeClose
|
||||
},
|
||||
hide: false
|
||||
})
|
||||
line = gettext("%(count)d earlier action");
|
||||
}
|
||||
} else {
|
||||
notification = new PNotify({
|
||||
title: titleError,
|
||||
text: textError,
|
||||
type: "error",
|
||||
callbacks: {
|
||||
before_close: beforeClose
|
||||
},
|
||||
hide: false
|
||||
});
|
||||
text += "<li><em>" + _.sprintf(line, {count: count}) + "</em></li>";
|
||||
steps = steps.slice(steps.length - 5);
|
||||
}
|
||||
|
||||
self.notifications.push(notification);
|
||||
_.each(steps, function(step) {
|
||||
var line = undefined;
|
||||
|
||||
switch (step.action) {
|
||||
case "install": {
|
||||
line = gettext("Install <em>%(plugin)s</em>: %(result)s");
|
||||
break;
|
||||
}
|
||||
case "uninstall": {
|
||||
line = gettext("Uninstall <em>%(plugin)s</em>: %(result)s");
|
||||
break;
|
||||
}
|
||||
case "enable": {
|
||||
line = gettext("Enable <em>%(plugin)s</em>: %(result)s");
|
||||
break;
|
||||
}
|
||||
case "disable": {
|
||||
line = gettext("Disable <em>%(plugin)s</em>: %(result)s");
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
text += "<li>"
|
||||
+ _.sprintf(line, {plugin: step.plugin, result: step.result ? "<i class=\"fa fa-check\"></i>" : "<i class=\"fa fa-remove\"></i>"})
|
||||
+ "</li>";
|
||||
});
|
||||
text += "</ul></p>";
|
||||
|
||||
var confirm = undefined;
|
||||
var type = "success";
|
||||
if (self.logContents.action.restart) {
|
||||
text += "<p>" + gettext("A restart is needed for the changes to take effect.") + "</p>";
|
||||
type = "warning";
|
||||
|
||||
if (self.restartCommandSpec) {
|
||||
var restartClicked = false;
|
||||
confirm = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Restart now"),
|
||||
click: function (notice) {
|
||||
if (restartClicked) return;
|
||||
restartClicked = true;
|
||||
showConfirmationDialog({
|
||||
message: gettext("<strong>This will restart your OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
|
||||
onproceed: function() {
|
||||
OctoPrint.system.executeCommand("core", "restart")
|
||||
.done(function() {
|
||||
notice.remove();
|
||||
new PNotify({
|
||||
title: gettext("Restart in progress"),
|
||||
text: gettext("The server is now being restarted in the background")
|
||||
})
|
||||
})
|
||||
.fail(function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
text: gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.")
|
||||
})
|
||||
});
|
||||
},
|
||||
onclose: function() {
|
||||
restartClicked = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}]
|
||||
}
|
||||
}
|
||||
} else if (self.logContents.action.refresh) {
|
||||
text += "<p>" + gettext("A refresh is needed for the changes to take effect.") + "</p>";
|
||||
type = "warning";
|
||||
|
||||
var refreshClicked = false;
|
||||
confirm = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Reload now"),
|
||||
click: function () {
|
||||
if (refreshClicked) return;
|
||||
refreshClicked = true;
|
||||
location.reload(true);
|
||||
}
|
||||
}]
|
||||
}
|
||||
} else if (self.logContents.action_reconnect) {
|
||||
text += "<p>" + gettext("A reconnect to the printer is needed for the changes to take effect.") + "</p>";
|
||||
type = "warning";
|
||||
}
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
text: text,
|
||||
type: type
|
||||
};
|
||||
|
||||
if (self.logNotification !== undefined) {
|
||||
self.logNotification.remove();
|
||||
}
|
||||
|
||||
if (confirm !== undefined) {
|
||||
options.confirm = confirm;
|
||||
options.hide = false;
|
||||
self.logNotification = PNotify.singleButtonNotify(options);
|
||||
} else {
|
||||
self.logNotification = new PNotify(options);
|
||||
}
|
||||
};
|
||||
|
||||
self._markWorking = function(title, line) {
|
||||
@@ -857,7 +872,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self._getToggleCommand = function(data) {
|
||||
var disable = (data.enabled || data.pending_enable || (data.safe_mode_victim && data.safe_mode_enabled)) && !data.pending_disable;
|
||||
var disable = (data.enabled || (data.safe_mode_victim && !data.forced_disabled) || data.pending_enable)
|
||||
&& !data.pending_disable;
|
||||
return disable ? "disable" : "enable";
|
||||
};
|
||||
|
||||
@@ -873,7 +889,7 @@ $(function() {
|
||||
if (command == "enable") {
|
||||
if (data.blacklisted) {
|
||||
return gettext("Blacklisted");
|
||||
} else if (data.safe_mode_victim && !data.safe_mode_enabled) {
|
||||
} else if (data.safe_mode_victim) {
|
||||
return gettext("Disabled due to active safe mode");
|
||||
} else {
|
||||
return gettext("Enable Plugin");
|
||||
@@ -1067,14 +1083,26 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self._closeAllNotifications();
|
||||
self._resetNotifications();
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
self.requestData({eval_notices: true});
|
||||
};
|
||||
|
||||
self._resetNotifications = function() {
|
||||
self._closeAllNotifications();
|
||||
self.logContents.action.restart
|
||||
= self.logContents.action.reload
|
||||
= self.logContents.action.reconnect
|
||||
= false;
|
||||
self.logContents.steps = [];
|
||||
};
|
||||
|
||||
self._closeAllNotifications = function() {
|
||||
if (self.logNotification) {
|
||||
self.logNotification.remove();
|
||||
}
|
||||
if (self.notifications) {
|
||||
_.each(self.notifications, function(notification) {
|
||||
notification.remove();
|
||||
@@ -1083,7 +1111,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onServerDisconnect = function() {
|
||||
self._closeAllNotifications();
|
||||
self._resetNotifications();
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -1094,7 +1122,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin != "pluginmanager") {
|
||||
if (plugin !== "pluginmanager") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1108,157 +1136,21 @@ $(function() {
|
||||
|
||||
var messageType = data.type;
|
||||
|
||||
if (messageType == "loglines" && self.working()) {
|
||||
if (messageType === "loglines" && self.working()) {
|
||||
_.each(data.loglines, function(line) {
|
||||
self.loglines.push(self._preprocessLine(line));
|
||||
});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
} else if (messageType == "result") {
|
||||
var titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError;
|
||||
} else if (messageType === "result") {
|
||||
var action = data.action;
|
||||
|
||||
var name = "Unknown";
|
||||
if (action == "install") {
|
||||
var unknown = false;
|
||||
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
if (data.plugin == "unknown") {
|
||||
unknown = true;
|
||||
} else {
|
||||
name = data.plugin.name;
|
||||
}
|
||||
}
|
||||
|
||||
if (unknown) {
|
||||
titleSuccess = _.sprintf(gettext("Plugin installed"));
|
||||
textSuccess = gettext("A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly");
|
||||
textRestart = textSuccess;
|
||||
textReload = textSuccess;
|
||||
textReconnect = textSuccess;
|
||||
} else if (data.plugin && data.plugin.blacklisted) {
|
||||
if (data.was_reinstalled) {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name});
|
||||
textSuccess = gettext("The plugin was reinstalled successfully, however it is blacklisted and therefore won't be loaded.");
|
||||
} else {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name});
|
||||
textSuccess = gettext("The plugin was installed successfully, however it is blacklisted and therefore won't be loaded.");
|
||||
}
|
||||
textRestart = textSuccess;
|
||||
textReload = textSuccess;
|
||||
textReconnect = textSuccess;
|
||||
} else if (data.was_reinstalled) {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name});
|
||||
textSuccess = gettext("The plugin was reinstalled successfully");
|
||||
textRestart = gettext("The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was reinstalled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
} else {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name});
|
||||
textSuccess = gettext("The plugin was installed successfully");
|
||||
textRestart = gettext("The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was installed successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was installed successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
}
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
var source = "unknown";
|
||||
if (data.hasOwnProperty("source")) {
|
||||
source = data.source;
|
||||
}
|
||||
var sourceType = "unknown";
|
||||
if (data.hasOwnProperty("source_type")) {
|
||||
sourceType = data.source_type;
|
||||
}
|
||||
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
if (data.was_reinstalled) {
|
||||
if (sourceType == "path") {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from file failed: %(reason)s"), {reason: data.reason});
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
|
||||
}
|
||||
} else {
|
||||
if (sourceType == "path") {
|
||||
textError = _.sprintf(gettext("Installing the plugin from file failed: %(reason)s"), {reason: data.reason});
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (data.was_reinstalled) {
|
||||
if (sourceType == "path") {
|
||||
textError = gettext("Reinstalling the plugin from file failed, please see the log for details.");
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
|
||||
}
|
||||
} else {
|
||||
if (sourceType == "path") {
|
||||
textError = gettext("Installing the plugin from file failed, please see the log for details.");
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else if (action == "uninstall") {
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
if (data.plugin !== "unknown") {
|
||||
name = data.plugin.name;
|
||||
}
|
||||
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" uninstalled"), {name: name});
|
||||
textSuccess = gettext("The plugin was uninstalled successfully");
|
||||
textRestart = gettext("The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was uninstalled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
textError = _.sprintf(gettext("Uninstalling the plugin failed: %(reason)s"), {reason: data.reason});
|
||||
} else {
|
||||
textError = gettext("Uninstalling the plugin failed, please see the log for details.");
|
||||
}
|
||||
|
||||
} else if (action == "enable") {
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
name = data.plugin.name;
|
||||
}
|
||||
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" enabled"), {name: name});
|
||||
textSuccess = gettext("The plugin was enabled successfully.");
|
||||
textRestart = gettext("The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was enabled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was enabled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
textError = _.sprintf(gettext("Toggling the plugin failed: %(reason)s"), {reason: data.reason});
|
||||
} else {
|
||||
textError = gettext("Toggling the plugin failed, please see the log for details.");
|
||||
}
|
||||
|
||||
} else if (action == "disable") {
|
||||
if (data.hasOwnProperty("plugin")) {
|
||||
name = data.plugin.name;
|
||||
}
|
||||
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" disabled"), {name: name});
|
||||
textSuccess = gettext("The plugin was disabled successfully.");
|
||||
textRestart = gettext("The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was disabled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was disabled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
textError = _.sprintf(gettext("Toggling the plugin failed: %(reason)s"), {reason: data.reason});
|
||||
} else {
|
||||
textError = gettext("Toggling the plugin failed, please see the log for details.");
|
||||
}
|
||||
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
self._displayNotification(data, action, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError);
|
||||
self._displayPluginManagementNotification(data, action, name);
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.events import Events
|
||||
from octoprint.server import user_permission
|
||||
|
||||
import flask
|
||||
from flask_babel import gettext
|
||||
|
||||
import textwrap
|
||||
|
||||
TERMINAL_SAFETY_WARNING = """
|
||||
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
{message}
|
||||
|
||||
Learn more at https://faq.octoprint.org/warning-{warning_type}
|
||||
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
|
||||
"""
|
||||
|
||||
SAFETY_CHECKS = {
|
||||
"firmware-unsafe": (lambda name, data: name and name.lower().startswith("anet_a8_"),)
|
||||
}
|
||||
|
||||
class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.EventHandlerPlugin,
|
||||
octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
self._warnings = dict()
|
||||
|
||||
##~~ TemplatePlugin API
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="sidebar",
|
||||
name=gettext("Printer Safety Warning"),
|
||||
data_bind="visible: printerState.isOperational() && loginState.isAdmin() && warnings().length > 0",
|
||||
icon="exclamation-triangle",
|
||||
styles_wrapper=["display: none"])
|
||||
]
|
||||
|
||||
##~~ AssetPlugin API
|
||||
|
||||
def get_assets(self):
|
||||
return dict(js=("js/printer_safety_check.js",),
|
||||
css=("css/printer_safety_check.css",),
|
||||
less=("less/printer_safety_check.less",))
|
||||
|
||||
##~~ EventHandlerPlugin API
|
||||
|
||||
def on_event(self, event, payload):
|
||||
if event == Events.FIRMWARE_DATA:
|
||||
self._analyze_firmware_data(payload.get("name"), payload.get("data"))
|
||||
elif event == Events.DISCONNECTED:
|
||||
self._reset_warnings()
|
||||
|
||||
##~~ SimpleApiPlugin API
|
||||
|
||||
def on_api_get(self, request):
|
||||
if not user_permission.can():
|
||||
return flask.make_response("Insufficient rights", 403)
|
||||
return flask.jsonify(self._warnings)
|
||||
|
||||
##~~ Helpers
|
||||
|
||||
def _analyze_firmware_data(self, name, data):
|
||||
changes = False
|
||||
|
||||
for warning_type, checks in SAFETY_CHECKS.items():
|
||||
if any(x(name, data) for x in checks):
|
||||
message = u"Your printer's firmware is known to lack mandatory safety features (e.g. " \
|
||||
u"thermal runaway protection). This is a fire risk."
|
||||
self._log_to_terminal(TERMINAL_SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)),
|
||||
warning_type=warning_type))
|
||||
self._warnings[warning_type] = message
|
||||
changes = True
|
||||
|
||||
if changes:
|
||||
self._ping_clients()
|
||||
|
||||
def _reset_warnings(self):
|
||||
self._warnings.clear()
|
||||
self._ping_clients()
|
||||
|
||||
def _log_to_terminal(self, message):
|
||||
if self._printer:
|
||||
lines = message.split("\n")
|
||||
self._printer.log_lines(*lines)
|
||||
|
||||
def _ping_clients(self):
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type="update"))
|
||||
|
||||
__plugin_name__ = "Printer Safety Check"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/printer_safety_check.html"
|
||||
__plugin_description__ = "Checks for unsafe printers/printer firmwares"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
|
||||
"check if the printer it is connected to has a known safety"
|
||||
"issue and inform you about that fact.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = PrinterSafetyCheckPlugin()
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
#sidebar_plugin_printer_safety_check_wrapper{border:1px solid #b94a48}#sidebar_plugin_printer_safety_check_wrapper .accordion-heading{background-color:#b94a48;font-weight:700;color:#fff}#sidebar_plugin_printer_safety_check_wrapper .accordion-heading .icon-black,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a:active,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a:hover,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a:visited{color:#fff}
|
||||
@@ -0,0 +1,78 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintPrinterSafetyCheckClient = function(base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPrinterSafetyCheckClient.prototype.get = function(opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("printer_safety_check"), opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("printer_safety_check", OctoPrintPrinterSafetyCheckClient);
|
||||
return OctoPrintPrinterSafetyCheckClient;
|
||||
});
|
||||
|
||||
$(function() {
|
||||
function PrinterSafetyCheckViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.printerState = parameters[1];
|
||||
|
||||
self.warnings = ko.observableArray([]);
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.isUser()) {
|
||||
self.warnings([]);
|
||||
return;
|
||||
}
|
||||
|
||||
OctoPrint.plugins.printer_safety_check.get()
|
||||
.done(self.fromResponse)
|
||||
.fail(function() {
|
||||
self.warnings([]);
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
var warnings = [];
|
||||
_.each(data, function(message, warning_type) {
|
||||
warnings.push({type: warning_type, message: message});
|
||||
});
|
||||
self.warnings(warnings);
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (plugin !== "printer_safety_check") return;
|
||||
if (!data.hasOwnProperty("type")) return;
|
||||
|
||||
if (data.type === "update") {
|
||||
self.requestData();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: PrinterSafetyCheckViewModel,
|
||||
dependencies: ["loginStateViewModel", "printerStateViewModel"],
|
||||
elements: ["#sidebar_plugin_printer_safety_check_wrapper"]
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
#sidebar_plugin_printer_safety_check_wrapper {
|
||||
border: 1px solid #b94a48;
|
||||
|
||||
.accordion-heading {
|
||||
background-color: #b94a48;
|
||||
font-weight: bold;
|
||||
color: #fff;
|
||||
a, a:hover, a:visited, a:active {
|
||||
color: #fff;
|
||||
}
|
||||
.icon-black {
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
<p><strong>{{ _('Warning!') }}</strong></p>
|
||||
<!-- ko foreach: warnings -->
|
||||
<p class="printer_safety_warning">
|
||||
<span data-bind="text: message"></span><br>
|
||||
<a target="_blank" rel="noreferrer noopener" data-bind="attr: {href: 'https://faq.octoprint.org/warning-' + type}">{{ _('Learn more...') }}</a>
|
||||
</p>
|
||||
<!-- /ko -->
|
||||
@@ -21,7 +21,7 @@ from concurrent import futures
|
||||
|
||||
from . import version_checks, updaters, exceptions, util, cli
|
||||
|
||||
from flask.ext.babel import gettext
|
||||
from flask_babel import gettext
|
||||
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
|
||||
@@ -42,7 +42,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
|
||||
|
||||
DATA_FORMAT_VERSION = "v2"
|
||||
DATA_FORMAT_VERSION = "v3"
|
||||
|
||||
# noinspection PyMissingConstructor
|
||||
def __init__(self):
|
||||
@@ -484,7 +484,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
def view():
|
||||
try:
|
||||
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
|
||||
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
|
||||
return flask.jsonify(dict(status="inProgress" if self._update_in_progress else "updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
|
||||
information=information,
|
||||
timestamp=self._version_cache_timestamp))
|
||||
except exceptions.ConfigurationInvalid as e:
|
||||
@@ -515,6 +515,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash.update(",".join(targets))
|
||||
hash.update(str(self._version_cache_timestamp))
|
||||
hash.update(str(self._connectivity_checker.online))
|
||||
hash.update(str(self._update_in_progress))
|
||||
hash.update(self.DATA_FORMAT_VERSION)
|
||||
return hash.hexdigest()
|
||||
|
||||
@@ -564,7 +565,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
##~~ TemplatePlugin API
|
||||
|
||||
def get_template_configs(self):
|
||||
from flask.ext.babel import gettext
|
||||
from flask_babel import gettext
|
||||
return [
|
||||
dict(type="settings", name=gettext("Software Update"))
|
||||
]
|
||||
@@ -919,7 +920,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="No internet connection"))
|
||||
|
||||
except Exception as e:
|
||||
self._logger.exception("Update of %s can not be performed" % target)
|
||||
self._logger.exception("Update of %s can not be performed, please also check plugin_softwareupdate_console.log for possible causes of this" % target)
|
||||
if not "ignorable" in populated_check or not populated_check["ignorable"]:
|
||||
target_error = True
|
||||
|
||||
@@ -971,7 +972,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
result = dict(check)
|
||||
|
||||
if target == "octoprint":
|
||||
from flask.ext.babel import gettext
|
||||
from flask_babel import gettext
|
||||
|
||||
from octoprint.util.version import is_released_octoprint_version, is_stable_octoprint_version
|
||||
|
||||
@@ -1113,7 +1114,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
mapping = dict(update_script=updaters.update_script,
|
||||
pip=updaters.pip,
|
||||
python_updater=updaters.python_updater)
|
||||
python_updater=updaters.python_updater,
|
||||
sleep_a_bit=updaters.sleep_a_bit)
|
||||
|
||||
method = self._get_update_method(target, check, valid_methods=mapping.keys())
|
||||
return mapping[method]
|
||||
|
||||
@@ -303,6 +303,11 @@ $(function() {
|
||||
var octoprint = data.information["octoprint"];
|
||||
self.octoprintReleasedVersion(!octoprint || octoprint.released_version);
|
||||
|
||||
if (data.status === "inProgress") {
|
||||
self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.loginState.isAdmin() && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
|
||||
|
||||
if (data.status === "updateAvailable" || data.status === "updatePossible") {
|
||||
@@ -523,7 +528,7 @@ $(function() {
|
||||
self.updateInProgress = false;
|
||||
self._showPopup({
|
||||
title: gettext("Update not started!"),
|
||||
text: gettext("The update could not be started. Is it already active? Please consult the log for details."),
|
||||
text: gettext("The update could not be started. Is it already active? Please consult octoprint.log for details."),
|
||||
type: "error",
|
||||
hide: false,
|
||||
buttons: {
|
||||
@@ -664,23 +669,33 @@ $(function() {
|
||||
var title = undefined;
|
||||
var text = undefined;
|
||||
|
||||
switch(messageType) {
|
||||
// make sure we are marked as working if we get any of the in-progress messages
|
||||
case "loglines":
|
||||
case "updating":
|
||||
case "restarting":
|
||||
case "restart_manually":
|
||||
case "restart_failed":
|
||||
case "success":
|
||||
case "error": {
|
||||
if (!self.working()) {
|
||||
self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
switch (messageType) {
|
||||
case "loglines": {
|
||||
if (self.working()) {
|
||||
_.each(messageData.loglines, function(line) {
|
||||
self.loglines.push(self._preprocessLine(line));
|
||||
});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
}
|
||||
_.each(messageData.loglines, function(line) {
|
||||
self.loglines.push(self._preprocessLine(line));
|
||||
});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
break;
|
||||
}
|
||||
case "updating": {
|
||||
console.log(JSON.stringify(messageData));
|
||||
|
||||
if (!self.working()) {
|
||||
self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
|
||||
}
|
||||
|
||||
text = _.sprintf(gettext("Now updating %(name)s to %(version)s"), {name: messageData.name, version: messageData.version});
|
||||
self.loglines.push({line: "", stream: "separator"});
|
||||
self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
|
||||
@@ -719,7 +734,7 @@ $(function() {
|
||||
self.waitingForRestart = true;
|
||||
self.restartTimeout = setTimeout(function() {
|
||||
title = gettext("Restart failed");
|
||||
text = gettext("The server apparently did not restart by itself, you'll have to do it manually. Please consult the log file on what went wrong.");
|
||||
text = gettext("The server apparently did not restart by itself, you'll have to do it manually. Please consult octoprint.log on what went wrong.");
|
||||
|
||||
self._showPopup({
|
||||
title: title,
|
||||
@@ -762,9 +777,9 @@ $(function() {
|
||||
}
|
||||
case "restart_failed": {
|
||||
restartType = messageData.restart_type;
|
||||
text = gettext("Restarting OctoPrint failed, please restart it manually. You might also want to consult the log file on what went wrong here.");
|
||||
text = gettext("Restarting OctoPrint failed, please restart it manually. You might also want to consult octoprint.log on what went wrong here.");
|
||||
if (restartType === "environment") {
|
||||
text = gettext("Rebooting the server failed, please reboot it manually. You might also want to consult the log file on what went wrong here.");
|
||||
text = gettext("Rebooting the server failed, please reboot it manually. You might also want to consult octoprint.log on what went wrong here.");
|
||||
}
|
||||
|
||||
title = gettext("Restart failed");
|
||||
@@ -800,7 +815,7 @@ $(function() {
|
||||
}
|
||||
case "error": {
|
||||
title = gettext("Update failed!");
|
||||
text = gettext("The update did not finish successfully. Please consult the log for details.");
|
||||
text = gettext("The update did not finish successfully. Please consult <code>octoprint.log</code> and <code>plugin_softwareupdate_console.log</code> for details.");
|
||||
self._showPopup({
|
||||
title: title,
|
||||
text: text,
|
||||
|
||||
+1
-1
@@ -2,6 +2,6 @@
|
||||
<label class="control-label">{{ _('OctoPrint Release Channel') }}</label>
|
||||
<div class="controls">
|
||||
<select data-bind="value: config_releaseChannel, options: config_availableReleaseChannels, optionsText: 'name', optionsValue: 'key'"></select>
|
||||
<span class="help-inline">{{ _('Make sure you have read <a href="%(url)s" target="_blank" rel="noreferrer noopener">"Using Release Channels"</a> before switching to a release channel other than "Stable"', url="https://github.com/foosel/OctoPrint/wiki/Using-Release-Channels") }}</span>
|
||||
<span class="help-inline">{{ _('Make sure you have read <a href="%(url)s" target="_blank" rel="noreferrer noopener">"How to use the release channels to help test release candidates"</a> before switching to a release channel other than "Stable"', url="https://faq.octoprint.org/using-release-channels") }}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -5,4 +5,4 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from . import pip, python_updater, update_script
|
||||
from . import pip, python_updater, update_script, sleep_a_bit
|
||||
@@ -16,6 +16,8 @@ logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
|
||||
console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console")
|
||||
|
||||
_ALREADY_INSTALLED = "Requirement already satisfied (use --upgrade to upgrade)"
|
||||
_POTENTIAL_EGG_PROBLEM_POSIX = "No such file or directory"
|
||||
_POTENTIAL_EGG_PROBLEM_WINDOWS = "The system cannot find the file specified"
|
||||
|
||||
_pip_callers = dict()
|
||||
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
@@ -42,6 +44,10 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
if "pip_command" in check:
|
||||
pip_command = check["pip_command"]
|
||||
|
||||
pip_working_directory = None
|
||||
if "pip_cwd" in check:
|
||||
pip_working_directory = check["pip_cwd"]
|
||||
|
||||
if not online and not check.get("offline", False):
|
||||
raise exceptions.CannotUpdateOffline()
|
||||
|
||||
@@ -58,6 +64,9 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
def _log_stderr(*lines):
|
||||
_log(lines, prefix="!", stream="stderr")
|
||||
|
||||
def _log_message(*lines):
|
||||
_log(lines, prefix="#", stream="message")
|
||||
|
||||
def _log(lines, prefix=None, stream=None):
|
||||
if log_cb is None:
|
||||
return
|
||||
@@ -72,23 +81,43 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
|
||||
logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg))
|
||||
pip_args = ["install", install_arg]
|
||||
pip_kwargs = dict()
|
||||
if pip_working_directory is not None:
|
||||
pip_kwargs.update(cwd=pip_working_directory)
|
||||
|
||||
if "dependency_links" in check and check["dependency_links"]:
|
||||
pip_args += ["--process-dependency-links"]
|
||||
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
|
||||
|
||||
# This could be caused by an issue with pip/setuptools: If something (target or dependency of target) was
|
||||
# installed as an egg at an earlier date (e.g. thanks to just running python setup.py install), pip install
|
||||
# will throw an error after updating that something to a newer (non-egg) version since it will still have
|
||||
# the egg on its sys.path and expect to read data from it. Running the exact same command a second time
|
||||
# solved this during hunt for a workaround, so this is what we'll now do if it indeed looks like this
|
||||
# specific problem
|
||||
def is_egg_problem(line):
|
||||
return (_POTENTIAL_EGG_PROBLEM_POSIX in line or _POTENTIAL_EGG_PROBLEM_WINDOWS in line) and ".egg" in line
|
||||
|
||||
if any(map(lambda x: is_egg_problem(x), stderr)) or any(map(lambda x: is_egg_problem(x), stdout)):
|
||||
_log_message(u"This looks like an error caused by a specific issue in upgrading Python \"eggs\"",
|
||||
u"via current versions of pip.",
|
||||
u"Performing a second install attempt as a work around.")
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
|
||||
else:
|
||||
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
|
||||
|
||||
if not force and any(map(lambda x: x.strip().startswith(_ALREADY_INSTALLED) and (install_arg in x or install_arg in x.lower()), stdout)):
|
||||
logger.debug(u"Looks like we were already installed in this version. Forcing a reinstall.")
|
||||
_log_message(u"Looks like we were already installed in this version. Forcing a reinstall.")
|
||||
force = True
|
||||
|
||||
if force:
|
||||
logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import time
|
||||
|
||||
from octoprint.util import monotonic_time
|
||||
|
||||
def can_perform_update(target, check, online=True):
|
||||
return True
|
||||
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
duration = check.get("duration", 30)
|
||||
|
||||
now = monotonic_time()
|
||||
end = now + duration
|
||||
while now < end:
|
||||
log_cb(["{}s left...".format(end - now)], prefix=">", stream="output")
|
||||
time.sleep(5)
|
||||
now = monotonic_time()
|
||||
@@ -5,7 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from . import commandline, git_commit, github_commit, github_release, bitbucket_commit, python_checker
|
||||
from . import commandline, git_commit, github_commit, github_release, bitbucket_commit, python_checker, never_current, always_current
|
||||
|
||||
def log_github_ratelimit(logger, r):
|
||||
ratelimit = r.headers["X-RateLimit-Limit"] if "X-RateLimit-Limit" in r.headers else "?"
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
def get_latest(target, check, online=True):
|
||||
current_version = check.get("current_version", "1.0.0")
|
||||
|
||||
information = dict(local=dict(name=current_version, value=current_version),
|
||||
remote=dict(name=current_version, value=current_version))
|
||||
|
||||
return information, True
|
||||
@@ -0,0 +1,14 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
def get_latest(target, check, online=True):
|
||||
local_version = check.get("local_version", "1.0.0")
|
||||
remote_version = check.get("remote_version", "1.0.1")
|
||||
|
||||
information = dict(local=dict(name=local_version, value=local_version),
|
||||
remote=dict(name=remote_version, value=remote_version))
|
||||
|
||||
return information, False
|
||||
@@ -29,6 +29,7 @@ class VirtualPrinter(object):
|
||||
prepare_ok_regex = re.compile("prepare_ok (.*)")
|
||||
send_regex = re.compile("send (.*)")
|
||||
set_ambient_regex = re.compile("set_ambient ([-+]?[0-9]*\.?[0-9]+)")
|
||||
start_sd_regex = re.compile("start_sd (.*)")
|
||||
|
||||
def __init__(self, seriallog_handler=None, read_timeout=5.0, write_timeout=10.0):
|
||||
import logging
|
||||
@@ -88,7 +89,7 @@ class VirtualPrinter(object):
|
||||
self._lastX = 0.0
|
||||
self._lastY = 0.0
|
||||
self._lastZ = 0.0
|
||||
self._lastE = 0.0
|
||||
self._lastE = [0.0] * self.extruderCount
|
||||
self._lastF = 200
|
||||
|
||||
self._unitModifier = 1
|
||||
@@ -102,10 +103,12 @@ class VirtualPrinter(object):
|
||||
self._selectedSdFile = None
|
||||
self._selectedSdFileSize = None
|
||||
self._selectedSdFilePos = None
|
||||
|
||||
self._writingToSd = False
|
||||
self._writingToSdHandle = None
|
||||
self._newSdFilePos = None
|
||||
self._heatupThread = None
|
||||
|
||||
self._heatingUp = False
|
||||
|
||||
self._okBeforeCommandOutput = settings().getBoolean(["devel", "virtualPrinter", "okBeforeCommandOutput"])
|
||||
self._supportM112 = settings().getBoolean(["devel", "virtualPrinter", "supportM112"])
|
||||
@@ -114,19 +117,22 @@ class VirtualPrinter(object):
|
||||
self._sendWait = settings().getBoolean(["devel", "virtualPrinter", "sendWait"])
|
||||
self._sendBusy = settings().getBoolean(["devel", "virtualPrinter", "sendBusy"])
|
||||
self._waitInterval = settings().getFloat(["devel", "virtualPrinter", "waitInterval"])
|
||||
self._busyInterval = settings().getFloat(["devel", "virtualPrinter", "busyInterval"])
|
||||
|
||||
self._echoOnM117 = settings().getBoolean(["devel", "virtualPrinter", "echoOnM117"])
|
||||
|
||||
self._brokenM29 = settings().getBoolean(["devel", "virtualPrinter", "brokenM29"])
|
||||
self._brokenResend = settings().getBoolean(["devel", "virtualPrinter", "brokenResend"])
|
||||
|
||||
self._m115FormatString = settings().get(["devel", "virtualPrinter", "m115FormatString"])
|
||||
self._firmwareName = settings().get(["devel", "virtualPrinter", "firmwareName"])
|
||||
|
||||
self._okFormatString = settings().get(["devel", "virtualPrinter", "okFormatString"])
|
||||
|
||||
self._capabilities = settings().get(["devel", "virtualPrinter", "capabilities"])
|
||||
self._capabilities = settings().get(["devel", "virtualPrinter", "capabilities"], merged=True)
|
||||
|
||||
self._temperature_reporter = None
|
||||
self._sdstatus_reporter = None
|
||||
|
||||
self.currentLine = 0
|
||||
self.lastN = 0
|
||||
@@ -161,6 +167,74 @@ class VirtualPrinter(object):
|
||||
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"]))
|
||||
|
||||
def _reset(self):
|
||||
self._clearQueue(self.incoming)
|
||||
self._clearQueue(self.outgoing)
|
||||
self._clearQueue(self.buffered)
|
||||
|
||||
self._relative = True
|
||||
self._lastX = 0.0
|
||||
self._lastY = 0.0
|
||||
self._lastZ = 0.0
|
||||
self._lastE = [0.0] * self.extruderCount
|
||||
self._lastF = 200
|
||||
|
||||
self._unitModifier = 1
|
||||
self._feedrate_multiplier = 100
|
||||
self._flowrate_multiplier = 100
|
||||
|
||||
self._sdCardReady = True
|
||||
self._sdPrinting = False
|
||||
if self._sdPrinter:
|
||||
self._sdPrinting = False
|
||||
self._sdPrintingSemaphore.set()
|
||||
self._sdPrinter = None
|
||||
self._selectedSdFile = None
|
||||
self._selectedSdFileSize = None
|
||||
self._selectedSdFilePos = None
|
||||
|
||||
if self._writingToSdHandle:
|
||||
try:
|
||||
self._writingToSdHandle.close()
|
||||
except:
|
||||
pass
|
||||
self._writingToSd = False
|
||||
self._writingToSdHandle = None
|
||||
self._newSdFilePos = None
|
||||
|
||||
self._heatingUp = False
|
||||
|
||||
self.currentLine = 0
|
||||
self.lastN = 0
|
||||
|
||||
self._debug_awol = False
|
||||
self._debug_sleep = None
|
||||
self._sleepAfterNext.clear()
|
||||
self._sleepAfter.clear()
|
||||
|
||||
self._dont_answer = False
|
||||
|
||||
self._debug_drop_connection = False
|
||||
|
||||
self._killed = False
|
||||
|
||||
self._triggerResendAt100 = True
|
||||
self._triggerResendWithTimeoutAt105 = True
|
||||
self._triggerResendWithMissingLinenoAt110 = True
|
||||
self._triggerResendWithChecksumMismatchAt115 = True
|
||||
|
||||
if self._temperature_reporter is not None:
|
||||
self._temperature_reporter.cancel()
|
||||
self._temperature_reporter = None
|
||||
|
||||
if self._sdstatus_reporter is not None:
|
||||
self._sdstatus_reporter.cancel()
|
||||
self._sdstatus_reporter = None
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "simulateReset"]):
|
||||
for item in settings().get(["devel", "virtualPrinter", "resetLines"]):
|
||||
self._send(item + "\n")
|
||||
|
||||
@property
|
||||
def timeout(self):
|
||||
return self._read_timeout
|
||||
@@ -179,9 +253,10 @@ class VirtualPrinter(object):
|
||||
self._logger.debug("Setting write timeout to {}s".format(value))
|
||||
self._write_timeout = value
|
||||
|
||||
def _clearQueue(self, queue):
|
||||
def _clearQueue(self, q):
|
||||
try:
|
||||
while queue.get(block=False):
|
||||
while q.get(block=False):
|
||||
q.task_done()
|
||||
continue
|
||||
except queue.Empty:
|
||||
pass
|
||||
@@ -192,6 +267,10 @@ class VirtualPrinter(object):
|
||||
while self.incoming is not None and not self._killed:
|
||||
self._simulateTemps()
|
||||
|
||||
if self._heatingUp:
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
try:
|
||||
data = self.incoming.get(timeout=0.01)
|
||||
self.incoming.task_done()
|
||||
@@ -291,7 +370,7 @@ class VirtualPrinter(object):
|
||||
continue
|
||||
|
||||
# shortcut for writing to SD
|
||||
if self._writingToSdHandle is not None and not "M29" in data:
|
||||
if self._writingToSd and self._writingToSdHandle is not None and not "M29" in data:
|
||||
self._writingToSdHandle.write(data)
|
||||
self._sendOk()
|
||||
continue
|
||||
@@ -352,9 +431,11 @@ class VirtualPrinter(object):
|
||||
|
||||
def _gcode_T(self, code, data):
|
||||
t = int(code)
|
||||
if 0 <= t <= self.extruderCount:
|
||||
if 0 <= t < self.extruderCount:
|
||||
self.currentExtruder = t
|
||||
self._send("Active Extruder: %d" % self.currentExtruder)
|
||||
else:
|
||||
self._send("echo:T{} Invalid extruder ".format(t))
|
||||
|
||||
def _gcode_F(self, code, data):
|
||||
if self._supportF:
|
||||
@@ -410,8 +491,23 @@ class VirtualPrinter(object):
|
||||
self._setSdPos(pos)
|
||||
|
||||
def _gcode_M27(self, data):
|
||||
if self._sdCardReady:
|
||||
self._reportSdStatus()
|
||||
def report():
|
||||
if self._sdCardReady:
|
||||
self._reportSdStatus()
|
||||
|
||||
match = re.search("S([0-9]+)", data)
|
||||
if match:
|
||||
interval = int(match.group(1))
|
||||
if self._sdstatus_reporter is not None:
|
||||
self._sdstatus_reporter.cancel()
|
||||
|
||||
if interval > 0:
|
||||
self._sdstatus_reporter = RepeatedTimer(interval, report)
|
||||
self._sdstatus_reporter.start()
|
||||
else:
|
||||
self._sdstatus_reporter = None
|
||||
|
||||
report()
|
||||
|
||||
def _gcode_M28(self, data):
|
||||
if self._sdCardReady:
|
||||
@@ -427,8 +523,25 @@ class VirtualPrinter(object):
|
||||
filename = data.split(None, 1)[1].strip()
|
||||
self._deleteSdFile(filename)
|
||||
|
||||
def _gcode_M113(self, data):
|
||||
interval = int(re.search("S([0-9]+)", data).group(1))
|
||||
if 0 <= interval <= 60:
|
||||
self._busyInterval = interval
|
||||
|
||||
def _gcode_M114(self, data):
|
||||
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE, int(self._lastX*100), int(self._lastY*100), int(self._lastZ*100))
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "reprapfwM114"]):
|
||||
output = "X:{} Y:{} Z:{} {}".format(self._lastX,
|
||||
self._lastY,
|
||||
self._lastZ,
|
||||
" ".join(["E{}:{}".format(num, self._lastE[self.currentExtruder]) for num in range(self.extruderCount)]))
|
||||
else:
|
||||
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX,
|
||||
self._lastY,
|
||||
self._lastZ,
|
||||
self._lastE[self.currentExtruder],
|
||||
int(self._lastX*100),
|
||||
int(self._lastY*100),
|
||||
int(self._lastZ*100))
|
||||
if not self._okBeforeCommandOutput:
|
||||
ok = self._ok()
|
||||
if ok:
|
||||
@@ -482,7 +595,7 @@ class VirtualPrinter(object):
|
||||
if self._lastZ is not None:
|
||||
self._lastZ *= 2.54
|
||||
if self._lastE is not None:
|
||||
self._lastE *= 2.54
|
||||
self._lastE = [e * 2.54 if e is not None else None for e in self._lastE]
|
||||
|
||||
def _gcode_G21(self, data):
|
||||
self._unitModifier = 1.0
|
||||
@@ -493,7 +606,7 @@ class VirtualPrinter(object):
|
||||
if self._lastZ is not None:
|
||||
self._lastZ /= 2.54
|
||||
if self._lastE is not None:
|
||||
self._lastE /= 2.54
|
||||
self._lastE = [e / 2.54 if e is not None else None for e in self._lastE]
|
||||
|
||||
def _gcode_G90(self, data):
|
||||
self._relative = False
|
||||
@@ -524,10 +637,10 @@ class VirtualPrinter(object):
|
||||
elif matchS:
|
||||
_timeout = float(matchS.group(1))
|
||||
|
||||
if self._sendBusy:
|
||||
if self._sendBusy and self._busyInterval > 0:
|
||||
until = time.time() + _timeout
|
||||
while time.time() < until:
|
||||
time.sleep(1.0)
|
||||
time.sleep(self._busyInterval)
|
||||
self._send("busy:processing")
|
||||
else:
|
||||
time.sleep(_timeout)
|
||||
@@ -563,7 +676,8 @@ class VirtualPrinter(object):
|
||||
|
||||
def request_resend():
|
||||
self._send("Resend:%d" % expected)
|
||||
self._sendOk()
|
||||
if not self._brokenResend:
|
||||
self._sendOk()
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
|
||||
request_resend()
|
||||
@@ -620,10 +734,19 @@ class VirtualPrinter(object):
|
||||
sleep_after_next <str:command> <int:seconds>
|
||||
| Sleeps <seconds> s after execution of next <command>
|
||||
|
||||
# SD printing
|
||||
|
||||
start_sd <str:file>
|
||||
| Start printing file <file> from SD
|
||||
cancel_sd
|
||||
| Cancels an ongoing SD print
|
||||
|
||||
# Misc
|
||||
|
||||
send <str:message>
|
||||
| Sends back <message>
|
||||
reset
|
||||
| Simulates a reset. Internal state will be lost.
|
||||
"""
|
||||
for line in usage.split("\n"):
|
||||
self._send("echo: {}".format(line.strip()))
|
||||
@@ -645,6 +768,8 @@ class VirtualPrinter(object):
|
||||
self._prepared_errors.append(lambda cur, last, line: self._send(self._error("lineno_missing", last)))
|
||||
elif data == "drop_connection":
|
||||
self._debug_drop_connection = True
|
||||
elif data == "reset":
|
||||
self._reset()
|
||||
elif data == "mintemp_error":
|
||||
self._send(self._error("mintemp"))
|
||||
elif data == "maxtemp_error":
|
||||
@@ -652,6 +777,13 @@ class VirtualPrinter(object):
|
||||
elif data == "go_awol":
|
||||
self._send("// Going AWOL")
|
||||
self._debug_awol = True
|
||||
elif data == "cancel_sd":
|
||||
if self._sdPrinting and self._sdPrinter:
|
||||
self._pauseSdPrint()
|
||||
self._sdPrinting = False
|
||||
self._sdPrintingSemaphore.set()
|
||||
self._sdPrinter.join()
|
||||
self._finishSdPrint()
|
||||
else:
|
||||
try:
|
||||
sleep_match = VirtualPrinter.sleep_regex.match(data)
|
||||
@@ -661,6 +793,7 @@ class VirtualPrinter(object):
|
||||
prepare_ok_match = VirtualPrinter.prepare_ok_regex.match(data)
|
||||
send_match = VirtualPrinter.send_regex.match(data)
|
||||
set_ambient_match = VirtualPrinter.set_ambient_regex.match(data)
|
||||
start_sd_match = VirtualPrinter.start_sd_regex.match(data)
|
||||
|
||||
if sleep_match is not None:
|
||||
interval = int(sleep_match.group(1))
|
||||
@@ -689,6 +822,9 @@ class VirtualPrinter(object):
|
||||
elif set_ambient_match is not None:
|
||||
self._ambient_temperature = float(set_ambient_match.group(1))
|
||||
self._send("// set ambient temperature to {}".format(self._ambient_temperature))
|
||||
elif start_sd_match is not None:
|
||||
self._selectSdFile(start_sd_match.group(1))
|
||||
self._startSdPrint()
|
||||
except:
|
||||
pass
|
||||
|
||||
@@ -726,6 +862,7 @@ class VirtualPrinter(object):
|
||||
def _startSdPrint(self):
|
||||
if self._selectedSdFile is not None:
|
||||
if self._sdPrinter is None:
|
||||
self._sdPrinting = True
|
||||
self._sdPrinter = threading.Thread(target=self._sdPrintingWorker)
|
||||
self._sdPrinter.start()
|
||||
self._sdPrintingSemaphore.set()
|
||||
@@ -839,7 +976,7 @@ class VirtualPrinter(object):
|
||||
matchE = re.search("E([0-9.]+)", line)
|
||||
matchF = re.search("F([0-9.]+)", line)
|
||||
|
||||
duration = 0
|
||||
duration = 0.0
|
||||
if matchF is not None:
|
||||
try:
|
||||
self._lastF = float(matchF.group(1))
|
||||
@@ -894,19 +1031,21 @@ class VirtualPrinter(object):
|
||||
if matchE is not None:
|
||||
try:
|
||||
e = float(matchE.group(1))
|
||||
if self._relative or self._lastE is None:
|
||||
lastE = self._lastE[self.currentExtruder]
|
||||
if self._relative or lastE is None:
|
||||
duration = max(duration, e * self._unitModifier / speedE * 60.0)
|
||||
else:
|
||||
duration = max(duration, (e - self._lastE) * self._unitModifier / speedE * 60.0)
|
||||
duration = max(duration, (e - lastE) * self._unitModifier / speedE * 60.0)
|
||||
|
||||
if self._relative and self._lastE is not None:
|
||||
self._lastE += e
|
||||
if self._relative and lastE is not None:
|
||||
self._lastE[self.currentExtruder] += e
|
||||
else:
|
||||
self._lastE = e
|
||||
self._lastE[self.currentExtruder] = e
|
||||
except:
|
||||
pass
|
||||
|
||||
if duration:
|
||||
duration *= 0.1
|
||||
if duration > self._read_timeout:
|
||||
slept = 0
|
||||
while duration - slept > self._read_timeout and not self._killed:
|
||||
@@ -922,7 +1061,7 @@ class VirtualPrinter(object):
|
||||
matchE = re.search("E([0-9.]+)", line)
|
||||
|
||||
if matchX is None and matchY is None and matchZ is None and matchE is None:
|
||||
self._lastX = self._lastY = self._lastZ = self._lastE = 0
|
||||
self._lastX = self._lastY = self._lastZ = self._lastE[self.currentExtruder] = 0
|
||||
else:
|
||||
if matchX is not None:
|
||||
try:
|
||||
@@ -941,7 +1080,7 @@ class VirtualPrinter(object):
|
||||
pass
|
||||
if matchE is not None:
|
||||
try:
|
||||
self._lastE = float(matchE.group(1))
|
||||
self._lastE[self.currentExtruder] = float(matchE.group(1))
|
||||
except:
|
||||
pass
|
||||
|
||||
@@ -986,7 +1125,7 @@ class VirtualPrinter(object):
|
||||
try:
|
||||
with open(self._selectedSdFile, "r") as f:
|
||||
for line in iter(f.readline, ""):
|
||||
if self._killed:
|
||||
if self._killed or not self._sdPrinting:
|
||||
break
|
||||
|
||||
# reset position if requested by client
|
||||
@@ -999,12 +1138,14 @@ class VirtualPrinter(object):
|
||||
|
||||
# if we are paused, wait for unpausing
|
||||
self._sdPrintingSemaphore.wait()
|
||||
if self._killed or not self._sdPrinting:
|
||||
break
|
||||
|
||||
# set target temps
|
||||
if 'M104' in line or 'M109' in line:
|
||||
self._parseHotendCommand(line)
|
||||
self._parseHotendCommand(line, wait='M109' in line)
|
||||
elif 'M140' in line or 'M190' in line:
|
||||
self._parseBedCommand(line)
|
||||
self._parseBedCommand(line, wait='M190' in line)
|
||||
elif line.startswith("G0") or line.startswith("G1") or line.startswith("G2") or line.startswith("G3"):
|
||||
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
|
||||
self.buffered.put(line)
|
||||
@@ -1013,31 +1154,45 @@ class VirtualPrinter(object):
|
||||
if self.outgoing is not None:
|
||||
raise
|
||||
|
||||
self._finishSdPrint()
|
||||
|
||||
def _finishSdPrint(self):
|
||||
if not self._killed:
|
||||
self._sdPrintingSemaphore.clear()
|
||||
self._selectedSdFilePos = 0
|
||||
self._sdPrinting = False
|
||||
self._sdPrinter = None
|
||||
self._output("Done printing file")
|
||||
|
||||
def _waitForHeatup(self, heater, only_wait_if_higher):
|
||||
delta = 1
|
||||
delay = 1
|
||||
last_busy = time.time()
|
||||
|
||||
self._heatingUp = True
|
||||
try:
|
||||
if heater.startswith("tool"):
|
||||
toolNum = int(heater[len("tool"):])
|
||||
while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or (not only_wait_if_higher and self.temp[toolNum] > self.targetTemp[toolNum] + delta)):
|
||||
self._simulateTemps(delta=delta)
|
||||
self._output("T:%0.2f" % self.temp[toolNum])
|
||||
time.sleep(delay)
|
||||
test = lambda: self.temp[toolNum] < self.targetTemp[toolNum] - delta or (not only_wait_if_higher and self.temp[toolNum] > self.targetTemp[toolNum] + delta)
|
||||
output = lambda: "T:%0.2f" % self.temp[toolNum]
|
||||
elif heater == "bed":
|
||||
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or (not only_wait_if_higher and self.bedTemp > self.bedTargetTemp + delta)):
|
||||
self._simulateTemps(delta=delta)
|
||||
self._output("B:%0.2f" % self.bedTemp)
|
||||
time.sleep(delay)
|
||||
test = lambda: self.bedTemp < self.bedTargetTemp - delta or (not only_wait_if_higher and self.bedTemp > self.bedTargetTemp + delta)
|
||||
output = lambda: "B:%0.2f" % self.bedTemp
|
||||
else:
|
||||
return
|
||||
|
||||
while not self._killed and self._heatingUp and test():
|
||||
self._simulateTemps(delta=delta)
|
||||
self._output(output())
|
||||
if self._sendBusy and time.time() - last_busy >= self._busyInterval:
|
||||
self._output("echo:busy: processing")
|
||||
last_busy = time.time()
|
||||
time.sleep(delay)
|
||||
except AttributeError:
|
||||
if self.outgoing is not None:
|
||||
raise
|
||||
finally:
|
||||
self._heatingUp = False
|
||||
|
||||
def _deleteSdFile(self, filename):
|
||||
if filename.startswith("/"):
|
||||
@@ -1200,6 +1355,10 @@ class CharCountingQueue(queue.Queue):
|
||||
self._size = 0
|
||||
self._name = name
|
||||
|
||||
def clear(self):
|
||||
with self.mutex:
|
||||
self.queue.clear()
|
||||
|
||||
def put(self, item, block=True, timeout=None, partial=False):
|
||||
self.not_full.acquire()
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ class PrinterInterface(object):
|
||||
"""Regex for valid heater identifiers."""
|
||||
|
||||
@classmethod
|
||||
def get_connection_options(cls):
|
||||
def get_connection_options(cls, *args, **kwargs):
|
||||
"""
|
||||
Retrieves the available ports, baudrates, preferred port and baudrate for connecting to the printer.
|
||||
|
||||
@@ -75,7 +75,7 @@ class PrinterInterface(object):
|
||||
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
|
||||
}
|
||||
|
||||
def connect(self, port=None, baudrate=None, profile=None):
|
||||
def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs):
|
||||
"""
|
||||
Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a
|
||||
connection is already established, that connection will be closed prior to connecting anew with the provided
|
||||
@@ -89,13 +89,13 @@ class PrinterInterface(object):
|
||||
"""
|
||||
pass
|
||||
|
||||
def disconnect(self):
|
||||
def disconnect(self, *args, **kwargs):
|
||||
"""
|
||||
Disconnects from the printer. Does nothing if no connection is currently established.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_transport(self):
|
||||
def get_transport(self, *args, **kwargs):
|
||||
"""
|
||||
Returns the communication layer's transport object, if a connection is currently established.
|
||||
|
||||
@@ -107,7 +107,67 @@ class PrinterInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def fake_ack(self):
|
||||
def job_on_hold(self, blocking=True, *args, **kwargs):
|
||||
"""
|
||||
Contextmanager that allows executing code while printing while making sure that no commands from the file
|
||||
being printed are continued to be sent to the printer. Note that this will only work for local files,
|
||||
NOT SD files.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
with printer.job_on_hold():
|
||||
park_printhead()
|
||||
take_snapshot()
|
||||
send_printhead_back()
|
||||
|
||||
It should be used sparingly and only for very specific situations (such as parking the print head somewhere,
|
||||
taking a snapshot from the webcam, then continuing). If you abuse this, you WILL cause print quality issues!
|
||||
|
||||
A lock is in place that ensures that the context can only actually be held by one thread at a time. If you
|
||||
don't want to block on acquire, be sure to set ``blocking`` to ``False`` and catch the ``RuntimeException`` thrown
|
||||
if the lock can't be acquired.
|
||||
|
||||
Args:
|
||||
blocking (bool): Whether to block while attempting to acquire the lock (default) or not
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_job_on_hold(self, value, blocking=True, *args, **kwargs):
|
||||
"""
|
||||
Setter for finer control over putting jobs on hold. Set to ``True`` to ensure that no commands from the file
|
||||
being printed are continued to be sent to the printer. Set to ``False`` to resume. Note that this will only
|
||||
work for local files, NOT SD files.
|
||||
|
||||
Make absolutely sure that if you set this flag, you will always also unset it again. If you don't, the job will
|
||||
be stuck forever.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
if printer.set_job_on_hold(True):
|
||||
try:
|
||||
park_printhead()
|
||||
take_snapshot()
|
||||
send_printhead_back()
|
||||
finally:
|
||||
printer.set_job_on_hold(False)
|
||||
|
||||
Just like :func:`~octoprint.printer.PrinterInterface.job_on_hold` this should be used sparingly and only for
|
||||
very specific situations. If you abuse this, you WILL cause print quality issues!
|
||||
|
||||
Args:
|
||||
value (bool): The value to set
|
||||
blocking (bool): Whether to block while attempting to set the value (default) or not
|
||||
|
||||
Returns:
|
||||
(bool) Whether the value could be set successfully (True) or a timeout was encountered (False)
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def fake_ack(self, *args, **kwargs):
|
||||
"""
|
||||
Fakes an acknowledgment for the communication layer. If the communication between OctoPrint and the printer
|
||||
gets stuck due to lost "ok" responses from the server due to communication issues, this can be used to get
|
||||
@@ -115,17 +175,18 @@ class PrinterInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def commands(self, commands):
|
||||
def commands(self, commands, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Sends the provided ``commands`` to the printer.
|
||||
|
||||
Arguments:
|
||||
commands (str, list): The commands to send. Might be a single command provided just as a string or a list
|
||||
of multiple commands to send in order.
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def script(self, name, context=None):
|
||||
def script(self, name, context=None, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Sends the GCODE script ``name`` to the printer.
|
||||
|
||||
@@ -137,13 +198,14 @@ class PrinterInterface(object):
|
||||
Arguments:
|
||||
name (str): The name of the GCODE script to render.
|
||||
context (dict): An optional context of additional template variables to provide to the renderer.
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
|
||||
Raises:
|
||||
UnknownScriptException: There is no GCODE script with name ``name``
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def jog(self, axes, relative=True, speed=None, *args, **kwargs):
|
||||
def jog(self, axes, relative=True, speed=None, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Jogs the specified printer ``axis`` by the specified ``amount`` in mm.
|
||||
|
||||
@@ -154,38 +216,42 @@ class PrinterInterface(object):
|
||||
speed (int, bool or None): Speed at which to jog (F parameter). If set to ``False`` no speed will be set
|
||||
specifically. If set to ``None`` (or left out) the minimum of all involved axes speeds from the printer
|
||||
profile will be used.
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def home(self, axes):
|
||||
def home(self, axes, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Homes the specified printer ``axes``.
|
||||
|
||||
Arguments:
|
||||
axes (str, list): The axis or axes to home, each of which must converted to lower case must match one of
|
||||
"x", "y", "z" and "e"
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def extrude(self, amount):
|
||||
def extrude(self, amount, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Extrude ``amount`` millimeters of material from the tool.
|
||||
|
||||
Arguments:
|
||||
amount (int, float): The amount of material to extrude in mm
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def change_tool(self, tool):
|
||||
def change_tool(self, tool, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Switch the currently active ``tool`` (for which extrude commands will apply).
|
||||
|
||||
Arguments:
|
||||
tool (str): The tool to switch to, matching the regex "tool[0-9]+" (e.g. "tool0", "tool1", ...)
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_temperature(self, heater, value):
|
||||
def set_temperature(self, heater, value, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Sets the target temperature on the specified ``heater`` to the given ``value`` in celsius.
|
||||
|
||||
@@ -194,10 +260,11 @@ class PrinterInterface(object):
|
||||
temperature or something matching the regular expression "tool[0-9]+" (e.g. "tool0", "tool1", ...) for
|
||||
the hotends of the printer
|
||||
value (int, float): The temperature in celsius to set the target temperature to.
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_temperature_offset(self, offsets=None):
|
||||
def set_temperature_offset(self, offsets=None, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Sets the temperature ``offsets`` to apply to target temperatures read from a GCODE file while printing.
|
||||
|
||||
@@ -205,30 +272,33 @@ class PrinterInterface(object):
|
||||
offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater``
|
||||
parameter to :func:`set_temperature`, so "bed" for the offset for the bed target temperature and
|
||||
"tool[0-9]+" for the offsets to the hotend target temperatures.
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def feed_rate(self, factor):
|
||||
def feed_rate(self, factor, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Sets the ``factor`` for the printer's feed rate.
|
||||
|
||||
Arguments:
|
||||
factor (int, float): The factor for the feed rate to send to the firmware. Percentage expressed as either an
|
||||
int between 0 and 100 or a float between 0 and 1.
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def flow_rate(self, factor):
|
||||
def flow_rate(self, factor, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Sets the ``factor`` for the printer's flow rate.
|
||||
|
||||
Arguments:
|
||||
factor (int, float): The factor for the flow rate to send to the firmware. Percentage expressed as either an
|
||||
int between 0 and 100 or a float between 0 and 1.
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def can_modify_file(self, path, sd):
|
||||
def can_modify_file(self, path, sd, *args, **kwargs):
|
||||
"""
|
||||
Determines whether the ``path`` (on the printer's SD if ``sd`` is True) may be modified (updated or deleted)
|
||||
or not.
|
||||
@@ -254,7 +324,7 @@ class PrinterInterface(object):
|
||||
"""
|
||||
return not (self.is_current_file(path, sd) and (self.is_printing() or self.is_paused()))
|
||||
|
||||
def is_current_file(self, path, sd):
|
||||
def is_current_file(self, path, sd, *args, **kwargs):
|
||||
"""
|
||||
Returns whether the provided ``path`` (on the printer's SD if ``sd`` is True) is the currently selected
|
||||
file for printing.
|
||||
@@ -286,7 +356,7 @@ class PrinterInterface(object):
|
||||
|
||||
return False
|
||||
|
||||
def select_file(self, path, sd, printAfterSelect=False, pos=None):
|
||||
def select_file(self, path, sd, printAfterSelect=False, pos=None, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
|
||||
Optionally can also directly start the print after selecting the file.
|
||||
@@ -297,6 +367,7 @@ class PrinterInterface(object):
|
||||
sd (boolean): Indicates whether the file is on the printer's SD card or not.
|
||||
printAfterSelect (boolean): Indicates whether a print should be started
|
||||
after the file is selected.
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
|
||||
Raises:
|
||||
InvalidFileType: if the file is not a machinecode file and hence cannot be printed
|
||||
@@ -305,53 +376,76 @@ class PrinterInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def unselect_file(self):
|
||||
def unselect_file(self, *args, **kwargs):
|
||||
"""
|
||||
Unselects and currently selected file.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def start_print(self):
|
||||
def start_print(self, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Starts printing the currently selected file. If no file is currently selected, does nothing.
|
||||
|
||||
Arguments:
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def pause_print(self):
|
||||
def pause_print(self, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Pauses the current print job if it is currently running, does nothing otherwise.
|
||||
|
||||
Arguments:
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def resume_print(self):
|
||||
def resume_print(self, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Resumes the current print job if it is currently paused, does nothing otherwise.
|
||||
|
||||
Arguments:
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def toggle_pause_print(self):
|
||||
def toggle_pause_print(self, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Pauses the current print job if it is currently running or resumes it if it is currently paused.
|
||||
|
||||
Arguments:
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
if self.is_printing():
|
||||
self.pause_print()
|
||||
self.pause_print(tags=tags)
|
||||
elif self.is_paused():
|
||||
self.resume_print()
|
||||
self.resume_print(tags=tags)
|
||||
|
||||
def cancel_print(self):
|
||||
def cancel_print(self, tags=None, *args, **kwargs):
|
||||
"""
|
||||
Cancels the current print job.
|
||||
|
||||
Arguments:
|
||||
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_state_string(self):
|
||||
def log_lines(self, *lines):
|
||||
"""
|
||||
Logs the provided lines to the printer log and serial.log
|
||||
Args:
|
||||
*lines: the lines to log
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_state_string(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(str) A human readable string corresponding to the current communication state.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_state_id(self):
|
||||
def get_state_id(self, *args, **kwargs):
|
||||
"""
|
||||
Identifier of the current communication state.
|
||||
|
||||
@@ -376,35 +470,35 @@ class PrinterInterface(object):
|
||||
(str) A unique identifier corresponding to the current communication state.
|
||||
"""
|
||||
|
||||
def get_current_data(self):
|
||||
def get_current_data(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(dict) The current state data.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_current_job(self):
|
||||
def get_current_job(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(dict) The data of the current job.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_current_temperatures(self):
|
||||
def get_current_temperatures(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(dict) The current temperatures.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_temperature_history(self):
|
||||
def get_temperature_history(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(list) The temperature history.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_current_connection(self):
|
||||
def get_current_connection(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(tuple) The current connection information as a 4-tuple ``(connection_string, port, baudrate, printer_profile)``.
|
||||
@@ -412,49 +506,63 @@ class PrinterInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_closed_or_error(self):
|
||||
def is_closed_or_error(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently disconnected and/or in an error state.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_operational(self):
|
||||
def is_operational(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently connected and available.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_printing(self):
|
||||
def is_printing(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently printing.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_paused(self):
|
||||
def is_cancelling(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently cancelling a print.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_pausing(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently pausing a print.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_paused(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently paused.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_error(self):
|
||||
def is_error(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently in an error state.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_ready(self):
|
||||
def is_ready(self, *args, **kwargs):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently operational and ready for new print jobs (not printing).
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def register_callback(self, callback):
|
||||
def register_callback(self, callback, *args, **kwargs):
|
||||
"""
|
||||
Registers a :class:`PrinterCallback` with the instance.
|
||||
|
||||
@@ -463,7 +571,7 @@ class PrinterInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def unregister_callback(self, callback):
|
||||
def unregister_callback(self, callback, *args, **kwargs):
|
||||
"""
|
||||
Unregisters a :class:`PrinterCallback` from the instance.
|
||||
|
||||
|
||||
+160
-125
@@ -1,4 +1,142 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
This module contains printer profile related code.
|
||||
|
||||
A printer profile is a ``dict`` of the following structure:
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Type
|
||||
- Description
|
||||
* - ``id``
|
||||
- ``string``
|
||||
- Internal id of the printer profile
|
||||
* - ``name``
|
||||
- ``string``
|
||||
- Human readable name of the printer profile
|
||||
* - ``model``
|
||||
- ``string``
|
||||
- Printer model
|
||||
* - ``color``
|
||||
- ``string``
|
||||
- Color to associate with the printer profile
|
||||
* - ``volume``
|
||||
- ``dict``
|
||||
- Information about the print volume
|
||||
* - ``volume.width``
|
||||
- ``float``
|
||||
- Width of the print volume (X axis)
|
||||
* - ``volume.depth``
|
||||
- ``float``
|
||||
- Depth of the print volume (Y axis)
|
||||
* - ``volume.height``
|
||||
- ``float``
|
||||
- Height of the print volume (Z axis)
|
||||
* - ``volume.formFactor``
|
||||
- ``string``
|
||||
- Form factor of the print bed, either ``rectangular`` or ``circular``
|
||||
* - ``volume.origin``
|
||||
- ``string``
|
||||
- Location of gcode origin in the print volume, either ``lowerleft`` or ``center``
|
||||
* - ``volume.custom_box``
|
||||
- ``dict`` or ``False``
|
||||
- Custom boundary box overriding the default bounding box based on the provided width, depth, height and origin.
|
||||
If ``False``, the default boundary box will be used.
|
||||
* - ``volume.custom_box.x_min``
|
||||
- ``float``
|
||||
- Minimum valid X coordinate
|
||||
* - ``volume.custom_box.y_min``
|
||||
- ``float``
|
||||
- Minimum valid Y coordinate
|
||||
* - ``volume.custom_box.z_min``
|
||||
- ``float``
|
||||
- Minimum valid Z coordinate
|
||||
* - ``volume.custom_box.x_max``
|
||||
- ``float``
|
||||
- Maximum valid X coordinate
|
||||
* - ``volume.custom_box.y_max``
|
||||
- ``float``
|
||||
- Maximum valid Y coordinate
|
||||
* - ``volume.custom_box.z_max``
|
||||
- ``float``
|
||||
- Maximum valid Z coordinate
|
||||
* - ``heatedBed``
|
||||
- ``bool``
|
||||
- Whether the printer has a heated bed (``True``) or not (``False``)
|
||||
* - ``extruder``
|
||||
- ``dict``
|
||||
- Information about the printer's extruders
|
||||
* - ``extruder.count``
|
||||
- ``int``
|
||||
- How many extruders the printer has (default 1)
|
||||
* - ``extruder.offsets``
|
||||
- ``list`` of ``tuple``
|
||||
- Extruder offsets relative to first extruder, list of (x, y) tuples, first is always (0,0)
|
||||
* - ``extruder.nozzleDiameter``
|
||||
- ``float``
|
||||
- Diameter of the printer nozzle(s)
|
||||
* - ``extruder.sharedNozzle``
|
||||
- ``boolean``
|
||||
- Whether there's only one nozzle shared among all extruders (true) or one nozzle per extruder (false).
|
||||
* - ``axes``
|
||||
- ``dict``
|
||||
- Information about the printer axes
|
||||
* - ``axes.x``
|
||||
- ``dict``
|
||||
- Information about the printer's X axis
|
||||
* - ``axes.x.speed``
|
||||
- ``float``
|
||||
- Speed of the X axis in mm/s
|
||||
* - ``axes.x.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
|
||||
* - ``axes.y``
|
||||
- ``dict``
|
||||
- Information about the printer's Y axis
|
||||
* - ``axes.y.speed``
|
||||
- ``float``
|
||||
- Speed of the Y axis in mm/s
|
||||
* - ``axes.y.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
|
||||
* - ``axes.z``
|
||||
- ``dict``
|
||||
- Information about the printer's Z axis
|
||||
* - ``axes.z.speed``
|
||||
- ``float``
|
||||
- Speed of the Z axis in mm/s
|
||||
* - ``axes.z.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed (False, default) or towards it (True)
|
||||
* - ``axes.e``
|
||||
- ``dict``
|
||||
- Information about the printer's E axis
|
||||
* - ``axes.e.speed``
|
||||
- ``float``
|
||||
- Speed of the E axis in mm/s
|
||||
* - ``axes.e.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change extrudes (False, default) or retracts (True) filament
|
||||
|
||||
.. autoclass:: PrinterProfileManager
|
||||
:members:
|
||||
|
||||
.. autoclass:: BedFormFactor
|
||||
:members:
|
||||
|
||||
.. autoclass:: BedOrigin
|
||||
:members:
|
||||
|
||||
.. autoclass:: SaveError
|
||||
|
||||
.. autoclass:: CouldNotOverwriteError
|
||||
|
||||
.. autoclass:: InvalidProfileError
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
@@ -20,25 +158,41 @@ from octoprint.settings import settings
|
||||
from octoprint.util import dict_merge, dict_sanitize, dict_contains_keys, is_hidden_path
|
||||
|
||||
class SaveError(Exception):
|
||||
"""Saving a profile failed"""
|
||||
pass
|
||||
|
||||
class CouldNotOverwriteError(SaveError):
|
||||
"""Overwriting of a profile not allowed"""
|
||||
pass
|
||||
|
||||
class InvalidProfileError(Exception):
|
||||
"""Profile invalid"""
|
||||
pass
|
||||
|
||||
class BedTypes(object):
|
||||
class BedFormFactor(object):
|
||||
"""Valid values for bed form factor"""
|
||||
|
||||
RECTANGULAR = "rectangular"
|
||||
"""Rectangular bed"""
|
||||
|
||||
CIRCULAR = "circular"
|
||||
"""Circular bed"""
|
||||
|
||||
@classmethod
|
||||
def values(cls):
|
||||
return [getattr(cls, name) for name in cls.__dict__ if not (name.startswith("__") or name == "values")]
|
||||
|
||||
BedTypes = BedFormFactor
|
||||
"""Deprecated name of :class:`BedFormFactors`"""
|
||||
|
||||
class BedOrigin(object):
|
||||
"""Valid values for bed origin"""
|
||||
|
||||
LOWERLEFT = "lowerleft"
|
||||
"""Origin at lower left corner of the bed when looking from the top"""
|
||||
|
||||
CENTER = "center"
|
||||
"""Origin at the center of the bed when looking from top"""
|
||||
|
||||
@classmethod
|
||||
def values(cls):
|
||||
@@ -48,125 +202,6 @@ class PrinterProfileManager(object):
|
||||
"""
|
||||
Manager for printer profiles. Offers methods to select the globally used printer profile and to list, add, remove,
|
||||
load and save printer profiles.
|
||||
|
||||
A printer profile is a ``dict`` of the following structure:
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Type
|
||||
- Description
|
||||
* - ``id``
|
||||
- ``string``
|
||||
- Internal id of the printer profile
|
||||
* - ``name``
|
||||
- ``string``
|
||||
- Human readable name of the printer profile
|
||||
* - ``model``
|
||||
- ``string``
|
||||
- Printer model
|
||||
* - ``color``
|
||||
- ``string``
|
||||
- Color to associate with the printer profile
|
||||
* - ``volume``
|
||||
- ``dict``
|
||||
- Information about the print volume
|
||||
* - ``volume.width``
|
||||
- ``float``
|
||||
- Width of the print volume (X axis)
|
||||
* - ``volume.depth``
|
||||
- ``float``
|
||||
- Depth of the print volume (Y axis)
|
||||
* - ``volume.height``
|
||||
- ``float``
|
||||
- Height of the print volume (Z axis)
|
||||
* - ``volume.formFactor``
|
||||
- ``string``
|
||||
- Form factor of the print bed, either ``rectangular`` or ``circular``
|
||||
* - ``volume.origin``
|
||||
- ``string``
|
||||
- Location of gcode origin in the print volume, either ``lowerleft`` or ``center``
|
||||
* - ``volume.custom_box``
|
||||
- ``dict`` or ``False``
|
||||
- Custom boundary box overriding the default bounding box based on the provided width, depth, height and origin.
|
||||
If ``False``, the default boundary box will be used.
|
||||
* - ``volume.custom_box.x_min``
|
||||
- ``float``
|
||||
- Minimum valid X coordinate
|
||||
* - ``volume.custom_box.y_min``
|
||||
- ``float``
|
||||
- Minimum valid Y coordinate
|
||||
* - ``volume.custom_box.z_min``
|
||||
- ``float``
|
||||
- Minimum valid Z coordinate
|
||||
* - ``volume.custom_box.x_max``
|
||||
- ``float``
|
||||
- Maximum valid X coordinate
|
||||
* - ``volume.custom_box.y_max``
|
||||
- ``float``
|
||||
- Maximum valid Y coordinate
|
||||
* - ``volume.custom_box.z_max``
|
||||
- ``float``
|
||||
- Maximum valid Z coordinate
|
||||
* - ``heatedBed``
|
||||
- ``bool``
|
||||
- Whether the printer has a heated bed (``True``) or not (``False``)
|
||||
* - ``extruder``
|
||||
- ``dict``
|
||||
- Information about the printer's extruders
|
||||
* - ``extruder.count``
|
||||
- ``int``
|
||||
- How many extruders the printer has (default 1)
|
||||
* - ``extruder.offsets``
|
||||
- ``list`` of ``tuple``s
|
||||
- Extruder offsets relative to first extruder, list of (x, y) tuples, first is always (0,0)
|
||||
* - ``extruder.nozzleDiameter``
|
||||
- ``float``
|
||||
- Diameter of the printer nozzle(s)
|
||||
* - ``extruder.sharedNozzle``
|
||||
- ``boolean``
|
||||
- Whether there's only one nozzle shared among all extruders (true) or one nozzle per extruder (false).
|
||||
* - ``axes``
|
||||
- ``dict``
|
||||
- Information about the printer axes
|
||||
* - ``axes.x``
|
||||
- ``dict``
|
||||
- Information about the printer's X axis
|
||||
* - ``axes.x.speed``
|
||||
- ``float``
|
||||
- Speed of the X axis in mm/s
|
||||
* - ``axes.x.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
|
||||
* - ``axes.y``
|
||||
- ``dict``
|
||||
- Information about the printer's Y axis
|
||||
* - ``axes.y.speed``
|
||||
- ``float``
|
||||
- Speed of the Y axis in mm/s
|
||||
* - ``axes.y.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
|
||||
* - ``axes.z``
|
||||
- ``dict``
|
||||
- Information about the printer's Z axis
|
||||
* - ``axes.z.speed``
|
||||
- ``float``
|
||||
- Speed of the Z axis in mm/s
|
||||
* - ``axes.z.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed (False, default) or towards it (True)
|
||||
* - ``axes.e``
|
||||
- ``dict``
|
||||
- Information about the printer's E axis
|
||||
* - ``axes.e.speed``
|
||||
- ``float``
|
||||
- Speed of the E axis in mm/s
|
||||
* - ``axes.e.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change extrudes (False, default) or retracts (True) filament
|
||||
"""
|
||||
|
||||
default = dict(
|
||||
@@ -178,7 +213,7 @@ class PrinterProfileManager(object):
|
||||
width = 200,
|
||||
depth = 200,
|
||||
height = 200,
|
||||
formFactor = BedTypes.RECTANGULAR,
|
||||
formFactor = BedFormFactor.RECTANGULAR,
|
||||
origin = BedOrigin.LOWERLEFT,
|
||||
custom_box = False
|
||||
),
|
||||
@@ -459,7 +494,7 @@ class PrinterProfileManager(object):
|
||||
modified = False
|
||||
|
||||
if "volume" in profile and "formFactor" in profile["volume"] and not "origin" in profile["volume"]:
|
||||
profile["volume"]["origin"] = BedOrigin.CENTER if profile["volume"]["formFactor"] == BedTypes.CIRCULAR else BedOrigin.LOWERLEFT
|
||||
profile["volume"]["origin"] = BedOrigin.CENTER if profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR else BedOrigin.LOWERLEFT
|
||||
modified = True
|
||||
|
||||
if "volume" in profile and not "custom_box" in profile["volume"]:
|
||||
@@ -520,7 +555,7 @@ class PrinterProfileManager(object):
|
||||
return False
|
||||
|
||||
# validate form factor
|
||||
if not profile["volume"]["formFactor"] in BedTypes.values():
|
||||
if not profile["volume"]["formFactor"] in BedFormFactor.values():
|
||||
self._logger.warn("Profile has invalid value volume.formFactor: {formFactor}".format(formFactor=profile["volume"]["formFactor"]))
|
||||
return False
|
||||
|
||||
@@ -530,11 +565,11 @@ class PrinterProfileManager(object):
|
||||
return False
|
||||
|
||||
# ensure origin and form factor combination is legal
|
||||
if profile["volume"]["formFactor"] == BedTypes.CIRCULAR and not profile["volume"]["origin"] == BedOrigin.CENTER:
|
||||
if profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR and not profile["volume"]["origin"] == BedOrigin.CENTER:
|
||||
profile["volume"]["origin"] = BedOrigin.CENTER
|
||||
|
||||
# force width and depth of volume to be identical for circular beds, with width being the reference
|
||||
if profile["volume"]["formFactor"] == BedTypes.CIRCULAR:
|
||||
if profile["volume"]["formFactor"] == BedFormFactor.CIRCULAR:
|
||||
profile["volume"]["depth"] = profile["volume"]["width"]
|
||||
|
||||
# if we have a custom bounding box, validate it
|
||||
|
||||
+211
-170
@@ -17,6 +17,8 @@ import time
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from frozendict import frozendict
|
||||
|
||||
from octoprint import util as util
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import FileDestinations, NoSuchStorage, valid_file_type
|
||||
@@ -40,6 +42,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._dict = frozendict if settings().getBoolean(["devel", "useFrozenDictForPrinterState"]) else dict
|
||||
|
||||
self._analysisQueue = analysisQueue
|
||||
self._fileManager = fileManager
|
||||
self._printerProfileManager = printerProfileManager
|
||||
@@ -100,25 +104,23 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
on_get_progress=self._updateProgressDataCallback
|
||||
)
|
||||
self._stateMonitor.reset(
|
||||
state={"text": self.get_state_string(), "flags": self._getStateFlags()},
|
||||
job_data={
|
||||
"file": {
|
||||
"name": None,
|
||||
"path": None,
|
||||
"size": None,
|
||||
"origin": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"lastPrintTime": None,
|
||||
"filament": {
|
||||
"length": None,
|
||||
"volume": None
|
||||
}
|
||||
},
|
||||
progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
|
||||
state=self._dict(text=self.get_state_string(), flags=self._getStateFlags()),
|
||||
job_data=self._dict(file=self._dict(name=None,
|
||||
path=None,
|
||||
size=None,
|
||||
origin=None,
|
||||
date=None),
|
||||
estimatedPrintTime=None,
|
||||
lastPrintTime=None,
|
||||
filament=self._dict(length=None,
|
||||
volume=None)),
|
||||
progress=self._dict(completion=None,
|
||||
filepos=None,
|
||||
printTime=None,
|
||||
printTimeLeft=None,
|
||||
printTimeOrigin=None),
|
||||
current_z=None,
|
||||
offsets=dict()
|
||||
offsets=self._dict()
|
||||
)
|
||||
|
||||
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self._on_event_MetadataAnalysisFinished)
|
||||
@@ -126,36 +128,44 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
#~~ handling of PrinterCallbacks
|
||||
|
||||
def register_callback(self, callback):
|
||||
def register_callback(self, callback, *args, **kwargs):
|
||||
if not isinstance(callback, PrinterCallback):
|
||||
self._logger.warn("Registering an object as printer callback which doesn't implement the PrinterCallback interface")
|
||||
|
||||
self._callbacks.append(callback)
|
||||
self._sendInitialStateUpdate(callback)
|
||||
|
||||
def unregister_callback(self, callback):
|
||||
def unregister_callback(self, callback, *args, **kwargs):
|
||||
if callback in self._callbacks:
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def _sendAddTemperatureCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_add_temperature(data)
|
||||
except: self._logger.exception("Exception while adding temperature data point")
|
||||
try:
|
||||
callback.on_printer_add_temperature(data)
|
||||
except:
|
||||
self._logger.exception(u"Exception while adding temperature data point to callback {}".format(callback))
|
||||
|
||||
def _sendAddLogCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_add_log(data)
|
||||
except: self._logger.exception("Exception while adding communication log entry")
|
||||
try:
|
||||
callback.on_printer_add_log(data)
|
||||
except:
|
||||
self._logger.exception(u"Exception while adding communication log entry to callback {}".format(callback))
|
||||
|
||||
def _sendAddMessageCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_add_message(data)
|
||||
except: self._logger.exception("Exception while adding printer message")
|
||||
try:
|
||||
callback.on_printer_add_message(data)
|
||||
except:
|
||||
self._logger.exception(u"Exception while adding printer message to callback {}".format(callback))
|
||||
|
||||
def _sendCurrentDataCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_send_current_data(copy.deepcopy(data))
|
||||
except: self._logger.exception("Exception while pushing current data")
|
||||
try:
|
||||
callback.on_printer_send_current_data(copy.deepcopy(data))
|
||||
except:
|
||||
self._logger.exception(u"Exception while pushing current data to callback {}".format(callback))
|
||||
|
||||
#~~ callback from metadata analysis event
|
||||
|
||||
@@ -196,7 +206,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
#~~ PrinterInterface implementation
|
||||
|
||||
def connect(self, port=None, baudrate=None, profile=None):
|
||||
def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs):
|
||||
"""
|
||||
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
|
||||
will be attempted.
|
||||
@@ -215,7 +225,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager)
|
||||
|
||||
def disconnect(self):
|
||||
def disconnect(self, *args, **kwargs):
|
||||
"""
|
||||
Closes the connection to the printer.
|
||||
"""
|
||||
@@ -225,7 +235,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
else:
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
def get_transport(self):
|
||||
def get_transport(self, *args, **kwargs):
|
||||
|
||||
if self._comm is None:
|
||||
return None
|
||||
@@ -233,13 +243,23 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
return self._comm.getTransport()
|
||||
getTransport = util.deprecated("getTransport has been renamed to get_transport", since="1.2.0-dev-590", includedoc="Replaced by :func:`get_transport`")
|
||||
|
||||
def fake_ack(self):
|
||||
def job_on_hold(self, blocking=True, *args, **kwargs):
|
||||
if self._comm is None:
|
||||
raise RuntimeError("No connection to the printer")
|
||||
return self._comm.job_put_on_hold(blocking=blocking)
|
||||
|
||||
def set_job_on_hold(self, value, blocking=True, *args, **kwargs):
|
||||
if self._comm is None:
|
||||
raise RuntimeError("No connection to the printer")
|
||||
return self._comm.set_job_on_hold(value, blocking=blocking)
|
||||
|
||||
def fake_ack(self, *args, **kwargs):
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.fakeOk()
|
||||
|
||||
def commands(self, commands):
|
||||
def commands(self, commands, *args, **kwargs):
|
||||
"""
|
||||
Sends one or more gcode commands to the printer.
|
||||
"""
|
||||
@@ -250,16 +270,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
commands = [commands]
|
||||
|
||||
for command in commands:
|
||||
self._comm.sendCommand(command)
|
||||
self._comm.sendCommand(command, tags=kwargs.get("tags", set()) | {"trigger:printer.commands"})
|
||||
|
||||
def script(self, name, context=None, must_be_set=True):
|
||||
def script(self, name, context=None, must_be_set=True, *args, **kwargs):
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
if name is None or not name:
|
||||
raise ValueError("name must be set")
|
||||
|
||||
result = self._comm.sendGcodeScript(name, replacements=context)
|
||||
result = self._comm.sendGcodeScript(name,
|
||||
replacements=context,
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.script"})
|
||||
if not result and must_be_set:
|
||||
raise UnknownScript(name)
|
||||
|
||||
@@ -298,9 +320,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
else:
|
||||
commands = ["G90", command]
|
||||
|
||||
self.commands(commands)
|
||||
self.commands(commands, tags=kwargs.get("tags", set()) | {"trigger:printer.jog"})
|
||||
|
||||
def home(self, axes):
|
||||
def home(self, axes, *args, **kwargs):
|
||||
if not isinstance(axes, (list, tuple)):
|
||||
if isinstance(axes, (str, unicode)):
|
||||
axes = [axes]
|
||||
@@ -311,24 +333,26 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if len(axes) != len(validated_axes):
|
||||
raise ValueError("axes contains invalid axes: {axes}".format(axes=axes))
|
||||
|
||||
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"])
|
||||
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"],
|
||||
tags=kwargs.get("tags", set) | {"trigger:printer.home"})
|
||||
|
||||
def extrude(self, amount):
|
||||
def extrude(self, amount, *args, **kwargs):
|
||||
if not isinstance(amount, (int, long, float)):
|
||||
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
|
||||
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
extrusion_speed = printer_profile["axes"]["e"]["speed"]
|
||||
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"])
|
||||
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"],
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.extrude"})
|
||||
|
||||
def change_tool(self, tool):
|
||||
def change_tool(self, tool, *args, **kwargs):
|
||||
if not PrinterInterface.valid_tool_regex.match(tool):
|
||||
raise ValueError("tool must match \"tool[0-9]+\": {tool}".format(tool=tool))
|
||||
|
||||
tool_num = int(tool[len("tool"):])
|
||||
self.commands("T%d" % tool_num)
|
||||
self.commands("T%d" % tool_num, tags=kwargs.get("tags", set()) | {"trigger:printer.change_tool"})
|
||||
|
||||
def set_temperature(self, heater, value):
|
||||
def set_temperature(self, heater, value, *args, **kwargs):
|
||||
if not PrinterInterface.valid_heater_regex.match(heater):
|
||||
raise ValueError("heater must match \"tool[0-9]+\" or \"bed\": {heater}".format(heater=heater))
|
||||
|
||||
@@ -341,14 +365,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
shared_nozzle = printer_profile["extruder"]["sharedNozzle"]
|
||||
if extruder_count > 1 and not shared_nozzle:
|
||||
toolNum = int(heater[len("tool"):])
|
||||
self.commands("M104 T{} S{}".format(toolNum, value))
|
||||
self.commands("M104 T{} S{}".format(toolNum, value),
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.set_temperature"})
|
||||
else:
|
||||
self.commands("M104 S{}".format(value))
|
||||
self.commands("M104 S{}".format(value),
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.set_temperature"})
|
||||
|
||||
elif heater == "bed":
|
||||
self.commands("M140 S{}".format(value))
|
||||
self.commands("M140 S{}".format(value),
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.set_temperature"})
|
||||
|
||||
def set_temperature_offset(self, offsets=None):
|
||||
def set_temperature_offset(self, offsets=None, *args, **kwargs):
|
||||
if offsets is None:
|
||||
offsets = dict()
|
||||
|
||||
@@ -381,15 +408,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
return factor
|
||||
|
||||
def feed_rate(self, factor):
|
||||
def feed_rate(self, factor, *args, **kwargs):
|
||||
factor = self._convert_rate_value(factor, min=50, max=200)
|
||||
self.commands("M220 S%d" % factor)
|
||||
self.commands("M220 S%d" % factor,
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.feed_rate"})
|
||||
|
||||
def flow_rate(self, factor):
|
||||
def flow_rate(self, factor, *args, **kwargs):
|
||||
factor = self._convert_rate_value(factor, min=75, max=125)
|
||||
self.commands("M221 S%d" % factor)
|
||||
self.commands("M221 S%d" % factor,
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.flow_rate"})
|
||||
|
||||
def select_file(self, path, sd, printAfterSelect=False, pos=None):
|
||||
def select_file(self, path, sd, printAfterSelect=False, pos=None, *args, **kwargs):
|
||||
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
self._logger.info("Cannot load file: printer not connected or currently busy")
|
||||
return
|
||||
@@ -408,11 +437,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
self._printAfterSelect = printAfterSelect
|
||||
self._posAfterSelect = pos
|
||||
self._comm.selectFile("/" + path if sd else path, sd)
|
||||
self._comm.selectFile("/" + path if sd else path, sd,
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.select_file"})
|
||||
self._updateProgressData()
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def unselect_file(self):
|
||||
def unselect_file(self, *args, **kwargs):
|
||||
if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
return
|
||||
|
||||
@@ -430,7 +460,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
return self._comm.getFilePosition()
|
||||
|
||||
def start_print(self, pos=None):
|
||||
def start_print(self, pos=None, *args, **kwargs):
|
||||
"""
|
||||
Starts the currently loaded print job.
|
||||
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
|
||||
@@ -463,9 +493,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._lastProgressReport = None
|
||||
self._updateProgressData()
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint(pos=pos)
|
||||
self._comm.startPrint(pos=pos,
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.start_print"})
|
||||
|
||||
def pause_print(self):
|
||||
def pause_print(self, *args, **kwargs):
|
||||
"""
|
||||
Pause the current printjob.
|
||||
"""
|
||||
@@ -475,9 +506,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if self._comm.isPaused():
|
||||
return
|
||||
|
||||
self._comm.setPause(True)
|
||||
self._comm.setPause(True, tags=kwargs.get("tags", set()) | {"trigger:printer.pause_print"})
|
||||
|
||||
def resume_print(self):
|
||||
def resume_print(self, *args, **kwargs):
|
||||
"""
|
||||
Resume the current printjob.
|
||||
"""
|
||||
@@ -487,9 +518,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if not self._comm.isPaused():
|
||||
return
|
||||
|
||||
self._comm.setPause(False)
|
||||
self._comm.setPause(False, tags=kwargs.get("tags", set()) | {"trigger:printer.resume_print"})
|
||||
|
||||
def cancel_print(self):
|
||||
def cancel_print(self, *args, **kwargs):
|
||||
"""
|
||||
Cancel the current printjob.
|
||||
"""
|
||||
@@ -498,28 +529,34 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
# tell comm layer to cancel - will also trigger our cancelled handler
|
||||
# for further processing
|
||||
self._comm.cancelPrint()
|
||||
self._comm.cancelPrint(tags=kwargs.get("tags", set()) | {"trigger:printer.cancel_print"})
|
||||
|
||||
def get_state_string(self, state=None):
|
||||
def log_lines(self, *lines):
|
||||
serial_logger = logging.getLogger("SERIAL")
|
||||
self.on_comm_log("\n".join(lines))
|
||||
for line in lines:
|
||||
serial_logger.debug(line)
|
||||
|
||||
def get_state_string(self, state=None, *args, **kwargs):
|
||||
if self._comm is None:
|
||||
return "Offline"
|
||||
else:
|
||||
return self._comm.getStateString(state=state)
|
||||
|
||||
def get_state_id(self, state=None):
|
||||
def get_state_id(self, state=None, *args, **kwargs):
|
||||
if self._comm is None:
|
||||
return "OFFLINE"
|
||||
else:
|
||||
return self._comm.getStateId(state=state)
|
||||
|
||||
def get_current_data(self):
|
||||
return self._stateMonitor.get_current_data()
|
||||
def get_current_data(self, *args, **kwargs):
|
||||
return util.thaw_frozendict(self._stateMonitor.get_current_data())
|
||||
|
||||
def get_current_job(self):
|
||||
def get_current_job(self, *args, **kwargs):
|
||||
currentData = self._stateMonitor.get_current_data()
|
||||
return currentData["job"]
|
||||
return util.thaw_frozendict(currentData["job"])
|
||||
|
||||
def get_current_temperatures(self):
|
||||
def get_current_temperatures(self, *args, **kwargs):
|
||||
if self._comm is not None:
|
||||
offsets = self._comm.getOffsets()
|
||||
else:
|
||||
@@ -542,10 +579,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
return result
|
||||
|
||||
def get_temperature_history(self):
|
||||
def get_temperature_history(self, *args, **kwargs):
|
||||
return self._temps
|
||||
|
||||
def get_current_connection(self):
|
||||
def get_current_connection(self, *args, **kwargs):
|
||||
if self._comm is None:
|
||||
return "Closed", None, None, None
|
||||
|
||||
@@ -553,25 +590,31 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
return self._comm.getStateString(), port, baudrate, printer_profile
|
||||
|
||||
def is_closed_or_error(self):
|
||||
def is_closed_or_error(self, *args, **kwargs):
|
||||
return self._comm is None or self._comm.isClosedOrError()
|
||||
|
||||
def is_operational(self):
|
||||
def is_operational(self, *args, **kwargs):
|
||||
return self._comm is not None and self._comm.isOperational()
|
||||
|
||||
def is_printing(self):
|
||||
def is_printing(self, *args, **kwargs):
|
||||
return self._comm is not None and self._comm.isPrinting()
|
||||
|
||||
def is_paused(self):
|
||||
def is_cancelling(self, *args, **kwargs):
|
||||
return self._comm is not None and self._comm.isCancelling()
|
||||
|
||||
def is_pausing(self, *args, **kwargs):
|
||||
return self._comm is not None and self._comm.isPausing()
|
||||
|
||||
def is_paused(self, *args, **kwargs):
|
||||
return self._comm is not None and self._comm.isPaused()
|
||||
|
||||
def is_error(self):
|
||||
def is_error(self, *args, **kwargs):
|
||||
return self._comm is not None and self._comm.isError()
|
||||
|
||||
def is_ready(self):
|
||||
def is_ready(self, *args, **kwargs):
|
||||
return self.is_operational() and not self.is_printing() and not self._comm.isStreaming()
|
||||
|
||||
def is_sd_ready(self):
|
||||
def is_sd_ready(self, *args, **kwargs):
|
||||
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
|
||||
return False
|
||||
else:
|
||||
@@ -579,12 +622,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
#~~ sd file handling
|
||||
|
||||
def get_sd_files(self):
|
||||
def get_sd_files(self, *args, **kwargs):
|
||||
if self._comm is None or not self._comm.isSdReady():
|
||||
return []
|
||||
return map(lambda x: (x[0][1:], x[1]), self._comm.getSdFiles())
|
||||
|
||||
def add_sd_file(self, filename, absolutePath, on_success=None, on_failure=None):
|
||||
def add_sd_file(self, filename, absolutePath, on_success=None, on_failure=None, *args, **kwargs):
|
||||
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
|
||||
self._logger.error("No connection to printer or printer is busy")
|
||||
return
|
||||
@@ -604,26 +647,28 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
# probably something else added through a plugin, use it's basename as-is
|
||||
remoteName = os.path.basename(filename)
|
||||
self._timeEstimationData = TimeEstimationHelper()
|
||||
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName, special=not valid_file_type(filename, "gcode"))
|
||||
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName,
|
||||
special=not valid_file_type(filename, "gcode"),
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.add_sd_file"})
|
||||
|
||||
return remoteName
|
||||
|
||||
def delete_sd_file(self, filename):
|
||||
def delete_sd_file(self, filename, *args, **kwargs):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.deleteSdFile("/" + filename)
|
||||
self._comm.deleteSdFile("/" + filename, tags=kwargs.get("tags", set()) | {"trigger:printer.delete_sd_file"})
|
||||
|
||||
def init_sd_card(self):
|
||||
def init_sd_card(self, *args, **kwargs):
|
||||
if not self._comm or self._comm.isSdReady():
|
||||
return
|
||||
self._comm.initSdCard()
|
||||
self._comm.initSdCard(tags=kwargs.get("tags", set()) | {"trigger:printer.init_sd_card"})
|
||||
|
||||
def release_sd_card(self):
|
||||
def release_sd_card(self, *args, **kwargs):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.releaseSdCard()
|
||||
self._comm.releaseSdCard(tags=kwargs.get("tags", set()) | {"trigger:printer.release_sd_card"})
|
||||
|
||||
def refresh_sd_files(self, blocking=False):
|
||||
def refresh_sd_files(self, blocking=False, *args, **kwargs):
|
||||
"""
|
||||
Refreshes the list of file stored on the SD card attached to printer (if available and printer communication
|
||||
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
|
||||
@@ -632,9 +677,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._sdFilelistAvailable.clear()
|
||||
self._comm.refreshSdFiles()
|
||||
self._comm.refreshSdFiles(tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"})
|
||||
if blocking:
|
||||
self._sdFilelistAvailable.wait(10000)
|
||||
self._sdFilelistAvailable.wait(kwargs.get("timeout", 10000))
|
||||
|
||||
#~~ state monitoring
|
||||
|
||||
@@ -650,7 +695,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
state_string = self.get_state_string()
|
||||
|
||||
self._state = state
|
||||
self._stateMonitor.set_state({"text": state_string, "flags": self._getStateFlags()})
|
||||
self._stateMonitor.set_state(self._dict(text=state_string, flags=self._getStateFlags()))
|
||||
|
||||
payload = dict(
|
||||
state_id=self.get_state_id(self._state),
|
||||
@@ -680,11 +725,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
return result
|
||||
|
||||
def _updateProgressData(self, completion=None, filepos=None, printTime=None, printTimeLeft=None):
|
||||
self._stateMonitor.set_progress(dict(completion=int(completion * 100) if completion 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))
|
||||
def _updateProgressData(self, completion=None, filepos=None, printTime=None, printTimeLeft=None, printTimeLeftOrigin=None):
|
||||
self._stateMonitor.set_progress(self._dict(completion=int(completion * 100) if completion 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 _updateProgressDataCallback(self):
|
||||
if self._comm is None:
|
||||
@@ -714,11 +760,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._lastProgressReport = progress_int
|
||||
self._reportPrintProgressToPlugins(progress_int)
|
||||
|
||||
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)
|
||||
return self._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):
|
||||
"""
|
||||
@@ -840,28 +886,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if tools is None:
|
||||
tools = dict()
|
||||
|
||||
currentTimeUtc = int(time.time())
|
||||
|
||||
data = {
|
||||
"time": currentTimeUtc
|
||||
}
|
||||
data = dict(time=int(time.time()))
|
||||
for tool in tools.keys():
|
||||
data["tool%d" % tool] = {
|
||||
"actual": tools[tool][0],
|
||||
"target": tools[tool][1]
|
||||
}
|
||||
data["tool%d" % tool] = self._dict(actual=tools[tool][0], target=tools[tool][1])
|
||||
if bed is not None and isinstance(bed, tuple):
|
||||
data["bed"] = {
|
||||
"actual": bed[0],
|
||||
"target": bed[1]
|
||||
}
|
||||
data["bed"] = self._dict(actual=bed[0], target=bed[1])
|
||||
|
||||
self._temps.append(data)
|
||||
|
||||
self._temp = tools
|
||||
self._bedTemp = bed
|
||||
|
||||
self._stateMonitor.add_temperature(data)
|
||||
self._stateMonitor.add_temperature(self._dict(**data))
|
||||
|
||||
def _validateJob(self, filename, sd):
|
||||
if not valid_file_type(filename, type="machinecode"):
|
||||
@@ -897,20 +933,16 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
}
|
||||
else:
|
||||
self._selectedFile = None
|
||||
self._stateMonitor.set_job_data({
|
||||
"file": {
|
||||
"name": None,
|
||||
"path": None,
|
||||
"display": None,
|
||||
"origin": None,
|
||||
"size": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"averagePrintTime": None,
|
||||
"lastPrintTime": None,
|
||||
"filament": None,
|
||||
})
|
||||
self._stateMonitor.set_job_data(self._dict(file=self._dict(name=None,
|
||||
path=None,
|
||||
display=None,
|
||||
origin=None,
|
||||
size=None,
|
||||
date=None),
|
||||
estimatedPrintTime=None,
|
||||
averagePrintTime=None,
|
||||
lastPrintTime=None,
|
||||
filament=None))
|
||||
return
|
||||
|
||||
estimatedPrintTime = None
|
||||
@@ -952,20 +984,16 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
|
||||
self._selectedFile["estimatedPrintTimeType"] = "analysis"
|
||||
|
||||
self._stateMonitor.set_job_data({
|
||||
"file": {
|
||||
"name": name_in_storage,
|
||||
"path": path_in_storage,
|
||||
"display": display_name,
|
||||
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
"size": filesize,
|
||||
"date": date
|
||||
},
|
||||
"estimatedPrintTime": estimatedPrintTime,
|
||||
"averagePrintTime": averagePrintTime,
|
||||
"lastPrintTime": lastPrintTime,
|
||||
"filament": filament,
|
||||
})
|
||||
self._stateMonitor.set_job_data(self._dict(file=self._dict(name=name_in_storage,
|
||||
path=path_in_storage,
|
||||
display=display_name,
|
||||
origin=FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
size=filesize,
|
||||
date=date),
|
||||
estimatedPrintTime=estimatedPrintTime,
|
||||
averagePrintTime=averagePrintTime,
|
||||
lastPrintTime=lastPrintTime,
|
||||
filament=filament))
|
||||
|
||||
def _sendInitialStateUpdate(self, callback):
|
||||
try:
|
||||
@@ -980,15 +1008,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._logger.exception("Error while trying to send initial state update")
|
||||
|
||||
def _getStateFlags(self):
|
||||
return {
|
||||
"operational": self.is_operational(),
|
||||
"printing": self.is_printing(),
|
||||
"closedOrError": self.is_closed_or_error(),
|
||||
"error": self.is_error(),
|
||||
"paused": self.is_paused(),
|
||||
"ready": self.is_ready(),
|
||||
"sdReady": self.is_sd_ready()
|
||||
}
|
||||
return self._dict(operational=self.is_operational(),
|
||||
printing=self.is_printing(),
|
||||
cancelling=self.is_cancelling(),
|
||||
pausing=self.is_pausing(),
|
||||
closedOrError=self.is_closed_or_error(),
|
||||
error=self.is_error(),
|
||||
paused=self.is_paused(),
|
||||
ready=self.is_ready(),
|
||||
sdReady=self.is_sd_ready())
|
||||
|
||||
#~~ comm.MachineComPrintCallback implementation
|
||||
|
||||
@@ -1021,17 +1049,22 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
with self._selectedFileMutex:
|
||||
if self._selectedFile is not None:
|
||||
if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_ERROR or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
|
||||
def log_print():
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL,
|
||||
self._selectedFile["filename"],
|
||||
time.time(),
|
||||
self._comm.getPrintTime(),
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
payload = self._payload_for_print_job_event()
|
||||
if payload:
|
||||
payload["time"] = self._comm.getPrintTime()
|
||||
|
||||
thread = threading.Thread(target=log_print)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
def finalize():
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
thread = threading.Thread(target=finalize)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
|
||||
elif state == comm.MachineCom.STATE_PRINTING:
|
||||
self._analysisQueue.pause() # do not analyse files while printing
|
||||
@@ -1078,7 +1111,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._setCurrentZ(newZ)
|
||||
|
||||
def on_comm_sd_state_change(self, sdReady):
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
|
||||
|
||||
def on_comm_sd_files(self, files):
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
|
||||
@@ -1093,7 +1126,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
eventManager().fire(Events.FILE_DESELECTED)
|
||||
|
||||
self._setJobData(full_path, size, sd)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
|
||||
|
||||
if self._printAfterSelect:
|
||||
self._printAfterSelect = False
|
||||
@@ -1117,7 +1150,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
filepos=payload["size"],
|
||||
printTime=payload["time"],
|
||||
printTimeLeft=0)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
|
||||
|
||||
eventManager().fire(Events.PRINT_DONE, payload)
|
||||
self.script("afterPrintDone",
|
||||
@@ -1138,12 +1171,20 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
else:
|
||||
self._updateProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
|
||||
|
||||
|
||||
def on_comm_print_job_failed(self):
|
||||
payload = self._payload_for_print_job_event()
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
if payload:
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
def on_comm_print_job_cancelling(self, firmware_error=None):
|
||||
payload = self._payload_for_print_job_event()
|
||||
if payload:
|
||||
if firmware_error:
|
||||
payload["firmwareError"] = firmware_error
|
||||
eventManager().fire(Events.PRINT_CANCELLING, payload)
|
||||
|
||||
def on_comm_print_job_cancelled(self):
|
||||
self._setCurrentZ(None)
|
||||
@@ -1192,7 +1233,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
self._setJobData(filename, filesize, True)
|
||||
self._updateProgressData(completion=0.0, filepos=0, printTime=0)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
|
||||
|
||||
def on_comm_file_transfer_done(self, filename, failed=False):
|
||||
self._sdStreaming = False
|
||||
@@ -1209,7 +1250,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._updateProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
|
||||
|
||||
def on_comm_file_transfer_failed(self, filename):
|
||||
self.on_comm_file_transfer_done(filename, failed=True)
|
||||
|
||||
@@ -8,10 +8,10 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import uuid
|
||||
from sockjs.tornado import SockJSRouter
|
||||
from flask import Flask, g, request, session, Blueprint, Request, Response, current_app
|
||||
from flask.ext.login import LoginManager, current_user, session_protected, user_logged_out
|
||||
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, AnonymousIdentity
|
||||
from flask.ext.babel import Babel, gettext, ngettext
|
||||
from flask.ext.assets import Environment, Bundle
|
||||
from flask_login import LoginManager, current_user, session_protected, user_logged_out
|
||||
from flask_principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, AnonymousIdentity
|
||||
from flask_babel import Babel, gettext, ngettext
|
||||
from flask_assets import Environment, Bundle
|
||||
from babel import Locale
|
||||
from watchdog.observers import Observer
|
||||
from watchdog.observers.polling import PollingObserver
|
||||
@@ -147,6 +147,13 @@ def load_user(id):
|
||||
|
||||
return None
|
||||
|
||||
def load_user_from_request(request):
|
||||
return util.get_user_for_authorization_header(request.headers.get('Authorization'))
|
||||
|
||||
def unauthorized_user():
|
||||
from flask import abort
|
||||
abort(403)
|
||||
|
||||
|
||||
#~~ startup code
|
||||
|
||||
@@ -211,10 +218,12 @@ class Server(object):
|
||||
safe_mode = self._safe_mode
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._setup_heartbeat_logging()
|
||||
pluginManager = self._plugin_manager
|
||||
|
||||
# monkey patch a bunch of stuff
|
||||
util.tornado.fix_ioloop_scheduling()
|
||||
util.tornado.fix_json_encode()
|
||||
util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")])
|
||||
|
||||
# setup app
|
||||
@@ -343,8 +352,37 @@ class Server(object):
|
||||
"""Factory for injections for all OctoPrintPlugins"""
|
||||
if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
|
||||
return None
|
||||
|
||||
components_copy = dict(components)
|
||||
if "printer" in components:
|
||||
import wrapt
|
||||
import functools
|
||||
|
||||
def tagwrap(f):
|
||||
@functools.wraps(f)
|
||||
def wrapper(*args, **kwargs):
|
||||
tags = kwargs.get("tags", set()) | {"source:plugin",
|
||||
"plugin:{}".format(name)}
|
||||
kwargs["tags"] = tags
|
||||
return f(*args, **kwargs)
|
||||
setattr(wrapper, "__tagwrapped__", True)
|
||||
return wrapper
|
||||
|
||||
class TaggedFuncsPrinter(wrapt.ObjectProxy):
|
||||
def __getattribute__(self, attr):
|
||||
__wrapped__ = super(TaggedFuncsPrinter, self).__getattribute__("__wrapped__")
|
||||
item = getattr(__wrapped__, attr)
|
||||
if callable(item) \
|
||||
and ("tags" in item.__code__.co_varnames or "kwargs" in item.__code__.co_varnames) \
|
||||
and not getattr(item, "__tagwrapped__", False):
|
||||
return tagwrap(item)
|
||||
else:
|
||||
return item
|
||||
|
||||
components_copy["printer"] = TaggedFuncsPrinter(components["printer"])
|
||||
|
||||
props = dict()
|
||||
props.update(components)
|
||||
props.update(components_copy)
|
||||
props.update(dict(
|
||||
data_folder=os.path.join(self._settings.getBaseFolder("data"), name)
|
||||
))
|
||||
@@ -414,18 +452,6 @@ class Server(object):
|
||||
# setup jinja2
|
||||
self._setup_jinja2()
|
||||
|
||||
# make sure plugin lifecycle events relevant for jinja2 are taken care of
|
||||
def template_enabled(name, plugin):
|
||||
if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
|
||||
return
|
||||
self._register_additional_template_plugin(plugin.implementation)
|
||||
def template_disabled(name, plugin):
|
||||
if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
|
||||
return
|
||||
self._unregister_additional_template_plugin(plugin.implementation)
|
||||
pluginLifecycleManager.add_callback("enabled", template_enabled)
|
||||
pluginLifecycleManager.add_callback("disabled", template_disabled)
|
||||
|
||||
# setup assets
|
||||
self._setup_assets()
|
||||
|
||||
@@ -437,13 +463,8 @@ class Server(object):
|
||||
if self._debug:
|
||||
events.DebugEventListener()
|
||||
|
||||
loginManager = LoginManager()
|
||||
loginManager.session_protection = "strong"
|
||||
loginManager.user_callback = load_user
|
||||
if not userManager.enabled:
|
||||
loginManager.anonymous_user = users.DummyUser
|
||||
principals.identity_loaders.appendleft(users.dummy_identity_loader)
|
||||
loginManager.init_app(app, add_context_processor=False)
|
||||
# setup login manager
|
||||
self._setup_login_manager()
|
||||
|
||||
# register API blueprint
|
||||
self._setup_blueprints()
|
||||
@@ -499,7 +520,7 @@ class Server(object):
|
||||
server_routes = self._router.urls + [
|
||||
# various downloads
|
||||
# .mpg and .mp4 timelapses:
|
||||
(r"/downloads/timelapse/([^/]*\.mp[g4])", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")),
|
||||
(r"/downloads/timelapse/([^/]*\.m(.*))", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")),
|
||||
download_handler_kwargs,
|
||||
no_hidden_files_validator)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("uploads"),
|
||||
@@ -508,7 +529,8 @@ class Server(object):
|
||||
download_handler_kwargs,
|
||||
no_hidden_files_validator,
|
||||
additional_mime_types)),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("logs")),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("logs"),
|
||||
mime_type_guesser=lambda *args, **kwargs: "text/plain"),
|
||||
download_handler_kwargs,
|
||||
admin_validator)),
|
||||
# camera snapshot
|
||||
@@ -521,7 +543,11 @@ class Server(object):
|
||||
# online indicators - text file with "online" as content and a transparent gif
|
||||
(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
|
||||
(r"/online.gif", util.tornado.StaticDataHandler, dict(data=bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")),
|
||||
content_type="image/gif"))
|
||||
content_type="image/gif")),
|
||||
|
||||
# deprecated endpoints
|
||||
(r"/api/logs", util.tornado.DeprecatedEndpointHandler, dict(url="/plugin/logging/logs")),
|
||||
(r"/api/logs/(.*)", util.tornado.DeprecatedEndpointHandler, dict(url="/plugin/logging/logs/{0}")),
|
||||
]
|
||||
|
||||
# fetch additional routes from plugins
|
||||
@@ -608,7 +634,7 @@ class Server(object):
|
||||
(port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"])
|
||||
printer_profile = printerProfileManager.get_default()
|
||||
connectionOptions = printer.__class__.get_connection_options()
|
||||
if port in connectionOptions["ports"]:
|
||||
if port in connectionOptions["ports"] or port == "AUTO":
|
||||
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
|
||||
except:
|
||||
self._logger.exception("Something went wrong while attempting to automatically connect to the printer")
|
||||
@@ -746,13 +772,27 @@ class Server(object):
|
||||
|
||||
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
|
||||
|
||||
def _setup_heartbeat_logging(self):
|
||||
logger = logging.getLogger(__name__ + ".heartbeat")
|
||||
|
||||
def log_heartbeat():
|
||||
logger.info("Server heartbeat <3")
|
||||
|
||||
interval = settings().getFloat(["server", "heartbeat"])
|
||||
logger.info("Starting server heartbeat, {}s interval".format(interval))
|
||||
|
||||
timer = octoprint.util.RepeatedTimer(interval, log_heartbeat)
|
||||
timer.start()
|
||||
|
||||
def _setup_app(self, app):
|
||||
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse
|
||||
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse, OctoPrintJsonEncoder
|
||||
|
||||
s = settings()
|
||||
|
||||
app.debug = self._debug
|
||||
|
||||
app.json_encoder = OctoPrintJsonEncoder
|
||||
|
||||
secret_key = s.get(["server", "secretKey"])
|
||||
if not secret_key:
|
||||
import string
|
||||
@@ -893,6 +933,18 @@ class Server(object):
|
||||
|
||||
self._register_template_plugins()
|
||||
|
||||
# make sure plugin lifecycle events relevant for jinja2 are taken care of
|
||||
def template_enabled(name, plugin):
|
||||
if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
|
||||
return
|
||||
self._register_additional_template_plugin(plugin.implementation)
|
||||
def template_disabled(name, plugin):
|
||||
if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
|
||||
return
|
||||
self._unregister_additional_template_plugin(plugin.implementation)
|
||||
pluginLifecycleManager.add_callback("enabled", template_enabled)
|
||||
pluginLifecycleManager.add_callback("disabled", template_disabled)
|
||||
|
||||
def _execute_preemptive_flask_caching(self, preemptive_cache):
|
||||
from werkzeug.test import EnvironBuilder
|
||||
import time
|
||||
@@ -1217,7 +1269,6 @@ class Server(object):
|
||||
"js/app/client/files.js",
|
||||
"js/app/client/job.js",
|
||||
"js/app/client/languages.js",
|
||||
"js/app/client/logs.js",
|
||||
"js/app/client/printer.js",
|
||||
"js/app/client/printerprofiles.js",
|
||||
"js/app/client/settings.js",
|
||||
@@ -1388,6 +1439,25 @@ class Server(object):
|
||||
assets.register("less_plugins", less_plugins_bundle)
|
||||
assets.register("less_app", less_app_bundle)
|
||||
|
||||
def _setup_login_manager(self):
|
||||
util.flask.fix_flask_login_remote_address()
|
||||
|
||||
global loginManager
|
||||
|
||||
loginManager = LoginManager()
|
||||
loginManager.session_protection = "strong"
|
||||
loginManager.user_callback = load_user
|
||||
loginManager.unauthorized_callback = unauthorized_user
|
||||
|
||||
# login users authenticated by basic auth
|
||||
if self._settings.get(["accessControl", "trustBasicAuthentication"]):
|
||||
loginManager.request_callback = load_user_from_request
|
||||
|
||||
if not userManager.enabled:
|
||||
loginManager.anonymous_user = users.DummyUser
|
||||
principals.identity_loaders.appendleft(users.dummy_identity_loader)
|
||||
loginManager.init_app(app, add_context_processor=False)
|
||||
|
||||
def _start_intermediary_server(self):
|
||||
import BaseHTTPServer
|
||||
import SimpleHTTPServer
|
||||
|
||||
@@ -10,8 +10,8 @@ import netaddr
|
||||
import sarge
|
||||
|
||||
from flask import Blueprint, request, jsonify, abort, current_app, session, make_response, g
|
||||
from flask.ext.login import login_user, logout_user, current_user
|
||||
from flask.ext.principal import Identity, identity_changed, AnonymousIdentity
|
||||
from flask_login import login_user, logout_user, current_user
|
||||
from flask_principal import Identity, identity_changed, AnonymousIdentity
|
||||
|
||||
import octoprint.util as util
|
||||
import octoprint.users
|
||||
@@ -19,7 +19,7 @@ import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, corsRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
|
||||
|
||||
|
||||
@@ -34,7 +34,6 @@ from . import files as api_files
|
||||
from . import settings as api_settings
|
||||
from . import timelapse as api_timelapse
|
||||
from . import users as api_users
|
||||
from . import log as api_logs
|
||||
from . import slicing as api_slicing
|
||||
from . import printer_profiles as api_printer_profiles
|
||||
from . import languages as api_languages
|
||||
@@ -47,6 +46,7 @@ api.after_request(noCachingExceptGetResponseHandler)
|
||||
|
||||
api.before_request(corsRequestHandler)
|
||||
api.before_request(enforceApiKeyRequestHandler)
|
||||
api.before_request(loginFromAuthorizationHeaderRequestHandler)
|
||||
api.before_request(loginFromApiKeyRequestHandler)
|
||||
api.after_request(corsResponseHandler)
|
||||
|
||||
@@ -240,6 +240,9 @@ def _logout(user):
|
||||
octoprint.server.userManager.logout_user(user)
|
||||
|
||||
|
||||
#~~ Test utils
|
||||
|
||||
|
||||
@api.route("/util/test", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
@@ -334,6 +337,7 @@ def utilTestPath():
|
||||
url = data["url"]
|
||||
method = data.get("method", "HEAD")
|
||||
timeout = 3.0
|
||||
valid_ssl = True
|
||||
check_status = [status_ranges["normal"]]
|
||||
|
||||
if "timeout" in data:
|
||||
@@ -342,6 +346,9 @@ def utilTestPath():
|
||||
except:
|
||||
return make_response("{!r} is not a valid value for timeout (must be int or float)".format(data["timeout"]), 400)
|
||||
|
||||
if "validSsl" in data:
|
||||
valid_ssl = data["validSsl"] in valid_boolean_trues
|
||||
|
||||
if "status" in data:
|
||||
request_status = data["status"]
|
||||
if not isinstance(request_status, list):
|
||||
@@ -360,7 +367,7 @@ def utilTestPath():
|
||||
check_status.append([code])
|
||||
|
||||
try:
|
||||
response = requests.request(method=method, url=url, timeout=timeout)
|
||||
response = requests.request(method=method, url=url, timeout=timeout, verify=valid_ssl)
|
||||
status = response.status_code
|
||||
except:
|
||||
status = 0
|
||||
@@ -395,25 +402,25 @@ def utilTestPath():
|
||||
port = int(data["port"])
|
||||
except:
|
||||
return make_response("{!r} is not a valid value for port (must be int)".format(data["port"]), 400)
|
||||
|
||||
|
||||
timeout = 3.05
|
||||
if "timeout" in data:
|
||||
try:
|
||||
timeout = float(data["timeout"])
|
||||
except:
|
||||
return make_response("{!r} is not a valid value for timeout (must be int or float)".format(data["timeout"]), 400)
|
||||
|
||||
|
||||
protocol = data.get("protocol", "tcp")
|
||||
if protocol not in ("tcp", "udp"):
|
||||
return make_response("{!r} is not a valid value for protocol, must be tcp or udp".format(protocol), 400)
|
||||
|
||||
|
||||
from octoprint.util import server_reachable
|
||||
reachable = server_reachable(host, port, timeout=timeout, proto=protocol)
|
||||
|
||||
|
||||
result = dict(host=host,
|
||||
port=port,
|
||||
protocol=protocol,
|
||||
result=reachable)
|
||||
|
||||
|
||||
return jsonify(**result)
|
||||
|
||||
@@ -325,7 +325,7 @@ def uploadGcodeFile(target):
|
||||
"""
|
||||
|
||||
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "machinecode"):
|
||||
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint)
|
||||
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint, tags={"source:api", "api:files.sd"})
|
||||
else:
|
||||
selectAndOrPrint(filename, absFilename, destination)
|
||||
return filename
|
||||
@@ -743,7 +743,7 @@ def deleteGcodeFile(filename, target):
|
||||
|
||||
# delete it
|
||||
if target == FileDestinations.SDCARD:
|
||||
printer.delete_sd_file(filename)
|
||||
printer.delete_sd_file(filename, tags={"source:api", "api:files.sd"})
|
||||
else:
|
||||
fileManager.remove_file(target, filename)
|
||||
|
||||
|
||||
@@ -32,30 +32,32 @@ def controlJob():
|
||||
|
||||
activePrintjob = printer.is_printing() or printer.is_paused()
|
||||
|
||||
tags = {"source:api", "api:job"}
|
||||
|
||||
if command == "start":
|
||||
if activePrintjob:
|
||||
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
|
||||
printer.start_print()
|
||||
printer.start_print(tags=tags)
|
||||
elif command == "restart":
|
||||
if not printer.is_paused():
|
||||
return make_response("Printer does not have an active print job or is not paused", 409)
|
||||
printer.start_print()
|
||||
printer.start_print(tags=tags)
|
||||
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()
|
||||
printer.toggle_pause_print(tags=tags)
|
||||
elif action == "pause":
|
||||
printer.pause_print()
|
||||
printer.pause_print(tags=tags)
|
||||
elif action == "resume":
|
||||
printer.resume_print()
|
||||
printer.resume_print(tags=tags)
|
||||
else:
|
||||
return make_response("Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(action), 400)
|
||||
elif command == "cancel":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
|
||||
printer.cancel_print()
|
||||
printer.cancel_print(tags=tags)
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ from octoprint.server.util.flask import restricted_access
|
||||
|
||||
from octoprint.plugin import plugin_manager
|
||||
|
||||
from flask.ext.babel import Locale
|
||||
from flask_babel import Locale
|
||||
|
||||
@api.route("/languages", methods=["GET"])
|
||||
@restricted_access
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Marc Hannappel Salandora"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import os
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
from octoprint.settings import settings
|
||||
|
||||
from octoprint.server import NO_CONTENT, admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
from octoprint.server.api import api
|
||||
|
||||
|
||||
@api.route("/logs", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def getLogFiles():
|
||||
import psutil
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
|
||||
|
||||
files = _getLogFiles()
|
||||
|
||||
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||
|
||||
|
||||
@api.route("/logs/<path:filename>", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def downloadLog(filename):
|
||||
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
|
||||
|
||||
|
||||
@api.route("/logs/<path:filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def deleteLog(filename):
|
||||
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
|
||||
if not os.path.exists(secure):
|
||||
return make_response("File not found: %s" % filename, 404)
|
||||
|
||||
os.remove(secure)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
def _getLogFiles():
|
||||
files = []
|
||||
basedir = settings().getBaseFolder("logs")
|
||||
for entry in scandir(basedir):
|
||||
files.append({
|
||||
"name": entry.name,
|
||||
"date": int(entry.stat().st_mtime),
|
||||
"size": entry.stat().st_size,
|
||||
"refs": {
|
||||
"resource": url_for(".downloadLog", filename=entry.name, _external=True),
|
||||
"download": url_for("index", _external=True) + "downloads/logs/" + entry.name
|
||||
}
|
||||
})
|
||||
|
||||
return files
|
||||
|
||||
@@ -75,6 +75,8 @@ def printerToolCommand():
|
||||
|
||||
validation_regex = re.compile("tool\d+")
|
||||
|
||||
tags = {"source:api", "api:printer.tool"}
|
||||
|
||||
##~~ tool selection
|
||||
if command == "select":
|
||||
tool = data["tool"]
|
||||
@@ -83,7 +85,7 @@ def printerToolCommand():
|
||||
if not tool.startswith("tool"):
|
||||
return make_response("Invalid tool for selection: %s" % tool, 400)
|
||||
|
||||
printer.change_tool(tool)
|
||||
printer.change_tool(tool, tags=tags)
|
||||
|
||||
##~~ temperature
|
||||
elif command == "target":
|
||||
@@ -100,7 +102,7 @@ def printerToolCommand():
|
||||
|
||||
# perform the actual temperature commands
|
||||
for tool in validated_values.keys():
|
||||
printer.set_temperature(tool, validated_values[tool])
|
||||
printer.set_temperature(tool, validated_values[tool], tags=tags)
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
@@ -129,14 +131,14 @@ def printerToolCommand():
|
||||
amount = data["amount"]
|
||||
if not isinstance(amount, (int, long, float)):
|
||||
return make_response("Not a number for extrusion amount: %r" % amount, 400)
|
||||
printer.extrude(amount)
|
||||
printer.extrude(amount, tags=tags)
|
||||
|
||||
elif command == "flowrate":
|
||||
factor = data["factor"]
|
||||
if not isinstance(factor, (int, long, float)):
|
||||
return make_response("Not a number for flow rate: %r" % factor, 400)
|
||||
try:
|
||||
printer.flow_rate(factor)
|
||||
printer.flow_rate(factor, tags=tags)
|
||||
except ValueError as e:
|
||||
return make_response("Invalid value for flow rate: %s" % str(e), 400)
|
||||
|
||||
@@ -171,6 +173,8 @@ def printerBedCommand():
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
tags = {"source:api", "api:printer.bed"}
|
||||
|
||||
##~~ temperature
|
||||
if command == "target":
|
||||
target = data["target"]
|
||||
@@ -180,7 +184,7 @@ def printerBedCommand():
|
||||
return make_response("Not a number: %r" % target, 400)
|
||||
|
||||
# perform the actual temperature command
|
||||
printer.set_temperature("bed", target)
|
||||
printer.set_temperature("bed", target, tags=tags)
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
@@ -232,6 +236,8 @@ def printerPrintheadCommand():
|
||||
# do not jog when a print job is running or we don't have a connection
|
||||
return make_response("Printer is not operational or currently printing", 409)
|
||||
|
||||
tags = {"source:api", "api:printer.printhead"}
|
||||
|
||||
valid_axes = ["x", "y", "z"]
|
||||
##~~ jog command
|
||||
if command == "jog":
|
||||
@@ -248,7 +254,7 @@ def printerPrintheadCommand():
|
||||
speed = data.get("speed", None)
|
||||
|
||||
# execute the jog commands
|
||||
printer.jog(validated_values, relative=not absolute, speed=speed)
|
||||
printer.jog(validated_values, relative=not absolute, speed=speed, tags=tags)
|
||||
|
||||
##~~ home command
|
||||
elif command == "home":
|
||||
@@ -260,14 +266,14 @@ def printerPrintheadCommand():
|
||||
validated_values.append(axis)
|
||||
|
||||
# execute the home command
|
||||
printer.home(validated_values)
|
||||
printer.home(validated_values, tags=tags)
|
||||
|
||||
elif command == "feedrate":
|
||||
factor = data["factor"]
|
||||
if not isinstance(factor, (int, long, float)):
|
||||
return make_response("Not a number for feed rate: %r" % factor, 400)
|
||||
try:
|
||||
printer.feed_rate(factor)
|
||||
printer.feed_rate(factor, tags=tags)
|
||||
except ValueError as e:
|
||||
return make_response("Invalid value for feed rate: %s" % str(e), 400)
|
||||
|
||||
@@ -295,12 +301,14 @@ def printerSdCommand():
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
tags = {"source:api", "api:printer.sd"}
|
||||
|
||||
if command == "init":
|
||||
printer.init_sd_card()
|
||||
printer.init_sd_card(tags=tags)
|
||||
elif command == "refresh":
|
||||
printer.refresh_sd_files()
|
||||
printer.refresh_sd_files(tags=tags)
|
||||
elif command == "release":
|
||||
printer.release_sd_card()
|
||||
printer.release_sd_card(tags=tags)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -341,6 +349,8 @@ def printerCommand():
|
||||
if "parameters" in data:
|
||||
parameters = data["parameters"]
|
||||
|
||||
tags = {"source:api", "api:printer.command"}
|
||||
|
||||
if "command" in data or "commands" in data:
|
||||
if "command" in data:
|
||||
commands = [data["command"]]
|
||||
@@ -356,7 +366,7 @@ def printerCommand():
|
||||
commandToSend = command % parameters
|
||||
commandsToSend.append(commandToSend)
|
||||
|
||||
printer.commands(commandsToSend)
|
||||
printer.commands(commandsToSend, tags=tags)
|
||||
|
||||
elif "script" in data:
|
||||
script_name = data["script"]
|
||||
@@ -365,7 +375,7 @@ def printerCommand():
|
||||
context["context"] = data["context"]
|
||||
|
||||
try:
|
||||
printer.script(script_name, context=context)
|
||||
printer.script(script_name, context=context, tags=tags)
|
||||
except UnknownScript:
|
||||
return make_response("Unknown script: {script_name}".format(**locals()), 404)
|
||||
|
||||
|
||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user