Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6171c76199 | ||
|
|
45c1958d83 | ||
|
|
e51d9439c5 | ||
|
|
18952c57ff | ||
|
|
590d2f2661 | ||
|
|
9b3569be50 | ||
|
|
661302f698 | ||
|
|
7a305b5a5c | ||
|
|
9f463707ee | ||
|
|
e1bcbae975 | ||
|
|
d6959f64c3 | ||
|
|
c5dbc71db3 | ||
|
|
017654852d | ||
|
|
9e2e616e1b | ||
|
|
0d5d28e4a6 | ||
|
|
90e50db189 | ||
|
|
e9a7cad202 | ||
|
|
60cf0b1099 | ||
|
|
aefb72f7cc | ||
|
|
f69abdcc14 | ||
|
|
ee36c31637 | ||
|
|
e0a064a0fa | ||
|
|
568fcbf547 | ||
|
|
7028bbfbfd | ||
|
|
c552e9e9be | ||
|
|
f8e8914f7d | ||
|
|
48dc27e106 | ||
|
|
32a38af4f7 | ||
|
|
772ebd198a | ||
|
|
603f667f93 | ||
|
|
18162cf110 | ||
|
|
f693f26ffc | ||
|
|
4cc1dc405f | ||
|
|
f9a9a405cd | ||
|
|
fa564c6029 | ||
|
|
36d1522f01 | ||
|
|
536e17eac4 | ||
|
|
887ec45b6b | ||
|
|
deb38f8455 | ||
|
|
64dacc7c70 | ||
|
|
f7c75442e7 | ||
|
|
293611287e | ||
|
|
6a2a1da5f9 | ||
|
|
7ebbf5911c | ||
|
|
254c3814d5 | ||
|
|
44c1920d9b | ||
|
|
109372d10b | ||
|
|
94847b846b | ||
|
|
3746332eb5 | ||
|
|
54b01d30da | ||
|
|
0509eb3f0a | ||
|
|
d7e37cf658 | ||
|
|
bdade99837 | ||
|
|
29be139803 | ||
|
|
ca8779676c | ||
|
|
ee03d62997 | ||
|
|
e068012cfb | ||
|
|
8fbb30437c | ||
|
|
9396ed765c | ||
|
|
d7f2075b1d | ||
|
|
e5ac94a16f | ||
|
|
2be05d4f9a | ||
|
|
f3ee2d2bfd | ||
|
|
f580acaf70 | ||
|
|
27322a971f | ||
|
|
8b5d6c9367 | ||
|
|
f09d44d8a0 | ||
|
|
9b031ff9d3 | ||
|
|
de59e8aa56 | ||
|
|
850aa5b797 | ||
|
|
9107fd839b | ||
|
|
89cae22b91 | ||
|
|
82ee48b166 | ||
|
|
17f3c5777e | ||
|
|
2cb787f816 | ||
|
|
feba135cac | ||
|
|
45c9e75e4e | ||
|
|
586a7a85e3 | ||
|
|
f844bd99c7 | ||
|
|
0747336c0f | ||
|
|
ace102e1c1 | ||
|
|
b976461c29 | ||
|
|
ad7243844e | ||
|
|
4a6a458cdd | ||
|
|
197d46b511 | ||
|
|
cf25d3d7be | ||
|
|
036e0af960 | ||
|
|
b115b6f66c | ||
|
|
592f3dce9a | ||
|
|
bcef0dd2c5 | ||
|
|
3f86272913 | ||
|
|
322834b762 | ||
|
|
04ddf30167 | ||
|
|
1935cc4841 | ||
|
|
bd96571d8a | ||
|
|
aa253bf53e | ||
|
|
b8a59097c2 | ||
|
|
a630b74fa8 | ||
|
|
3f7b222b92 | ||
|
|
c5c382ade6 | ||
|
|
858873dfa0 | ||
|
|
7231acc236 | ||
|
|
adea84e123 | ||
|
|
565757580b | ||
|
|
620d7de02f | ||
|
|
bba625a68f | ||
|
|
b282a18f6b | ||
|
|
417487e195 | ||
|
|
fba48b1d90 | ||
|
|
78f62847a3 | ||
|
|
3bfaa33c58 | ||
|
|
d0cb119bb0 | ||
|
|
3fc6b1e8cf | ||
|
|
ae06af9bc5 | ||
|
|
260a378e8c | ||
|
|
94e052af83 | ||
|
|
d56ab9b79b | ||
|
|
ad556e7413 | ||
|
|
b9f49a83e0 | ||
|
|
ebec2c95c0 | ||
|
|
d62627c8a5 | ||
|
|
96d2c7fad9 | ||
|
|
3aac75f5b5 | ||
|
|
908d39ad39 | ||
|
|
084ffb0dc1 | ||
|
|
cec2bdb805 | ||
|
|
a0374cb4ea | ||
|
|
538338abfe | ||
|
|
097e398efc | ||
|
|
0fd9b3354a | ||
|
|
765b941472 | ||
|
|
64084bb628 | ||
|
|
df269eb4f7 | ||
|
|
722b03dca8 | ||
|
|
3ddfc93c1b | ||
|
|
5eb70fa57d | ||
|
|
eccc9d6fbd | ||
|
|
049ed723a7 | ||
|
|
b6cdc5803b | ||
|
|
792299537d | ||
|
|
7b01e72a9b | ||
|
|
755549a745 | ||
|
|
1c39555255 | ||
|
|
ff5aba9a51 | ||
|
|
467d012bce | ||
|
|
09bed4e74f | ||
|
|
7a8e71b837 | ||
|
|
90336277a7 | ||
|
|
2b856e4508 | ||
|
|
ac75ee9831 | ||
|
|
0b662b7211 | ||
|
|
9f7fc73441 | ||
|
|
677d33e448 | ||
|
|
1dd0aba8f5 | ||
|
|
1b4a7c7896 | ||
|
|
5b8126ae17 | ||
|
|
a1350c9344 | ||
|
|
84012d1232 | ||
|
|
0199599880 | ||
|
|
2f3c3c0c20 | ||
|
|
e690053fd4 | ||
|
|
ae3e474c92 | ||
|
|
297d101f5f | ||
|
|
4d2213544e | ||
|
|
895d077d85 | ||
|
|
35b010b059 | ||
|
|
204128e1ca | ||
|
|
fdfa433243 | ||
|
|
aa69d181bf | ||
|
|
e9f218208d | ||
|
|
8ca3baee04 | ||
|
|
3c68353c57 | ||
|
|
fe37ab3cd8 | ||
|
|
f2b0bfb7dc | ||
|
|
f7f8c09a77 | ||
|
|
37c949e83b | ||
|
|
b35258fad6 | ||
|
|
1a6030c737 | ||
|
|
9008a2fb7f | ||
|
|
47f8ab24d9 | ||
|
|
4b41a47f93 | ||
|
|
5d69ee8abc | ||
|
|
edd801aa7b | ||
|
|
ef8787acf9 | ||
|
|
29a9ee40d5 | ||
|
|
4094d28c07 | ||
|
|
3b56cdaaa3 | ||
|
|
079806f11c | ||
|
|
69052d7670 | ||
|
|
4581722bbe | ||
|
|
2afd715f77 | ||
|
|
8d78104be8 | ||
|
|
076c6764a0 | ||
|
|
8ff48ed88d | ||
|
|
00501f0913 | ||
|
|
4b05f125a0 | ||
|
|
df05a80201 | ||
|
|
6b2912b0e2 | ||
|
|
4ea2345eda | ||
|
|
a7477e0184 | ||
|
|
6492ab66b0 | ||
|
|
78972b1d40 | ||
|
|
51ae782f02 | ||
|
|
a87541c354 | ||
|
|
4fbb8f1164 | ||
|
|
32b2c1e2e7 | ||
|
|
242e552f4d | ||
|
|
d7e6d51cc2 | ||
|
|
708c12ddbe | ||
|
|
21d16c8ba0 | ||
|
|
51b0df5c1f | ||
|
|
f07305ae4f | ||
|
|
b352078917 | ||
|
|
79f379a868 | ||
|
|
520c856c57 | ||
|
|
7a4bb8b94e | ||
|
|
4b7300c2e8 | ||
|
|
a7b7f26da5 | ||
|
|
26ebfe3e1f | ||
|
|
8212f28b90 | ||
|
|
2421824535 | ||
|
|
8e500b78aa | ||
|
|
70b2325de0 | ||
|
|
58cbad1828 | ||
|
|
aef0322617 | ||
|
|
d4bb75a2ee | ||
|
|
43cd85b8e4 | ||
|
|
f574267746 | ||
|
|
b2d715f041 | ||
|
|
2831ab0727 | ||
|
|
1f3160571c | ||
|
|
4c1fc14ac5 | ||
|
|
6d703d236a | ||
|
|
de635ae25f | ||
|
|
8dff6d6750 | ||
|
|
1e1e72c9c2 | ||
|
|
f51f4ad5cd | ||
|
|
711d18d9ad | ||
|
|
3cadbbeb85 | ||
|
|
d7fe15d635 | ||
|
|
d6b172c744 | ||
|
|
40650f1bde | ||
|
|
87edcc4966 | ||
|
|
09fa9bc28d | ||
|
|
280d8e8405 | ||
|
|
0eeca11838 | ||
|
|
281ad0f046 |
No files matched your search
@@ -0,0 +1 @@
|
||||
src/octoprint/_version.py export-subst
|
||||
@@ -4,9 +4,20 @@
|
||||
*.pyc
|
||||
*.zip
|
||||
*.exe
|
||||
*.gcode
|
||||
*.swp
|
||||
darwin-Cura-*
|
||||
win32-Cura-*
|
||||
linux-Cura-*
|
||||
*.iml
|
||||
Printrun
|
||||
=======
|
||||
.idea
|
||||
.DS_Store
|
||||
Cura/current_profile.ini
|
||||
Cura/preferences.ini
|
||||
build
|
||||
dist
|
||||
pypy
|
||||
OctoPrint.egg-info
|
||||
*.orig
|
||||
@@ -0,0 +1,18 @@
|
||||
# Configuration file for the versioneer lookup, manually mapping tags based on branches
|
||||
#
|
||||
# Format is
|
||||
#
|
||||
# <branch-regex> <tag> <reference commit>
|
||||
#
|
||||
# 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 staging shall not use the lookup table
|
||||
master
|
||||
staging
|
||||
|
||||
# fix/ branches are fixes for master, so we don't handle those either
|
||||
fix/.*
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.2.0-dev for now
|
||||
.* 1.2.0-dev 50cf776e70b9
|
||||
@@ -0,0 +1,75 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.1.0
|
||||
|
||||
### New Features
|
||||
|
||||
* New REST API, including User API Keys additionally to the global API key. Please note that **this will break existing
|
||||
API clients** as it replaces the old API (same endpoint). You can find the documentation of the new API at
|
||||
[docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/api/index.html).
|
||||
* New Event structure allows more flexibility regarding payload data, configuration files will be migrated automatically.
|
||||
You can find the documentation of the new event format and its usage at [docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/events/index.html).
|
||||
* Support for multi extruder setups. With this OctoPrint now in theory supports an unlimited amount of extruders, however
|
||||
for now it's artificially limited to 9.
|
||||
* Log files can be accessed from within the browser via the Settings dialog ([#361](https://github.com/foosel/OctoPrint/pull/361))
|
||||
* Timelapses can now have a post-roll duration configured which will be rendered into the video too to not let it
|
||||
end so abruptly ([#384](https://github.com/foosel/OctoPrint/issues/384))
|
||||
* The terminal tab now has a command history ([#388](https://github.com/foosel/OctoPrint/pull/388))
|
||||
|
||||
### Improvements
|
||||
|
||||
* Stopping the application via Ctrl-C produces a less scary message ([#277](https://github.com/foosel/OctoPrint/pull/277))
|
||||
* Webcam stream is disabled when control tab is not in focus, reduces bandwidth ([#316](https://github.com/foosel/OctoPrint/issues/316))
|
||||
* M and G commands entered in Terminal tab are automatically converted to uppercase
|
||||
* GCODE viewer now only loads automatically if GCODE file size is beneath certain threshold (different ones for desktop
|
||||
and mobile devices), only actually loads file if user acknowledges that this might be too much for his browser
|
||||
* Added time needed for printing file to PrintDone event's payload ([#333](https://github.com/foosel/OctoPrint/issues/333))
|
||||
* Also provide the filename (basename without the path) in print events
|
||||
* Support for circular beds in the GCODE viewer ([#407](https://github.com/foosel/OctoPrint/pull/407))
|
||||
* The dimensions of the print bed can now be configured via the Settings ([#396](https://github.com/foosel/OctoPrint/pull/396))
|
||||
* Target temperature reporting format of Repetier Firmware is now supported as well ([360](https://github.com/foosel/OctoPrint/issues/360))
|
||||
* Version tracking now based on git tagging and [versioneer](https://github.com/warner/python-versioneer/). Version number,
|
||||
git commit and branch get reported in the format `<version tag>-<commits since then>-g<commit hash> (<branch> branch)`,
|
||||
e.g. `1.2.0-dev-172-ga48b5de (devel branch)`.
|
||||
* Made "Center viewport on model" and "Zoom in on model" in the GCODE viewer automatically deselect and de-apply if
|
||||
viewport gets manipulated by the user ([#398](https://github.com/foosel/OctoPrint/issues/398))
|
||||
* GCODE viewer now interprets inverted axes for printer control and mirrors print bed accordingly ([#431](https://github.com/foosel/OctoPrint/issues/431))
|
||||
* Added `clean` command to `setup.py`, removes old build artifacts (mostly interesting for developers)
|
||||
* Added version resource on API which reports application and API version
|
||||
* Made the navbar static instead of fixed to improve usability on mobile devices ([#257](https://github.com/foosel/OctoPrint/issues/257))
|
||||
* Switch to password field upon enter in username field, submit login form upon enter in password field
|
||||
* Changed default path to OctoPrint executable in included init-script to `/usr/local/bin/octoprint` (the default when
|
||||
installing via `python setup.py install`)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Properly calculate time deltas (forgot to factor in days)
|
||||
* [#35](https://github.com/foosel/OctoPrint/issues/35) - GCODE viewer has been modularized, options are now functional
|
||||
* [#337](https://github.com/foosel/OctoPrint/issues/337) - Also recognize `--iknowwhatimdoing` when running as daemon
|
||||
* [#357](https://github.com/foosel/OctoPrint/issues/357) - Do not run GCODE analyzer when a print is ongoing
|
||||
* [#381](https://github.com/foosel/OctoPrint/issues/381) - Only list those SD files that have an ASCII filename
|
||||
* Fixed a race condition that could occur when pressing "Print" (File not opened yet, but attempt to read from it)
|
||||
* [#398](https://github.com/foosel/OctoPrint/issues/398) - Fixed interfering options in GCODE viewer
|
||||
* [#399](https://github.com/foosel/OctoPrint/issues/399) & [360](https://github.com/foosel/OctoPrint/issues/360) - Leave
|
||||
bed temperature unset when not detected (instead of dying a horrible death)
|
||||
* [#492](https://github.com/foosel/OctoPrint/issues/492) - Fixed a race condition which could lead to an attempt to read
|
||||
from an already closed serial port, causing an error to be displayed to the user
|
||||
* [#257](https://github.com/foosel/OctoPrint/issues/257) - Logging in on mobile devices should now work
|
||||
* [#476](https://github.com/foosel/OctoPrint/issues/476) - Also update the metadata correctly when an analysis finishes
|
||||
* Various fixes of bugs in newly introduced features and improvements:
|
||||
- [#314](https://github.com/foosel/OctoPrint/issues/314) - Use G28 for homing (G1 was copy and paste error)
|
||||
- [#317](https://github.com/foosel/OctoPrint/issues/317) - Fixed "load and print" function
|
||||
- [#326](https://github.com/foosel/OctoPrint/issues/326) - Fixed refresh of SD file list
|
||||
- [#338](https://github.com/foosel/OctoPrint/issues/338) - Refetch file list when deleting a file
|
||||
- [#339](https://github.com/foosel/OctoPrint/issues/339) - More error resilience when handling temperature offset data from the backend
|
||||
- [#345](https://github.com/foosel/OctoPrint/issues/345) - Also recognize such temperature reports that do not contain a `T:` but a `T0:`
|
||||
- [#377](https://github.com/foosel/OctoPrint/pull/377) - URLs in API examples fixed
|
||||
- [#378](https://github.com/foosel/OctoPrint/pull/378) - Fixed crash of API call when `getStartTime()` returns None
|
||||
- [#379](https://github.com/foosel/OctoPrint/pull/379) - Corrected response code for connection success
|
||||
- [#414](https://github.com/foosel/OctoPrint/pull/414) - Fix style attribute for Actual column header
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.0.0...1.1.0))
|
||||
|
||||
## 1.0.0
|
||||
|
||||
First release with new versioning scheme.
|
||||
@@ -0,0 +1,17 @@
|
||||
Issues, Tickets, however you may call them
|
||||
------------------------------------------
|
||||
|
||||
- If you want to report a bug, **READ [How to file a bug report](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)!** Tickets will be automatically checked if they comply with the requirements outlined in that wiki node! Other then what's written in there you don't have to do anything special with your ticket.
|
||||
- If you want to post a **request** of any kind (feature request, documentation request, ...), **add [Request] to your issue's title!**
|
||||
- If you need **support** with a problem of your installation (e.g. if you have problems getting the webcam to work), **add [Support] to your issue's title!**
|
||||
- If you have a general **question**, **add [Question] to your issue's title!**
|
||||
- If you have another reason for creating a ticket that doesn't fit any of the above categories, **add [Misc] to your issue's title!**
|
||||
|
||||
Pull Requests
|
||||
-------------
|
||||
|
||||
1. Please create all pull requests against the `devel` branch.
|
||||
2. Create **one pull request per feature/bug fix**.
|
||||
3. Create a custom branch for your feature/bug fix and use that as base for your pull request. Pull requests directly against your version of `devel` will be closed.
|
||||
4. In your pull request's description, state what your pull request is doing, as in, what feature does it implement, what bug does it fix.
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
recursive-include octoprint/static *
|
||||
recursive-include octoprint/templates *
|
||||
recursive-include src/octoprint/static *
|
||||
recursive-include src/octoprint/templates *
|
||||
include versioneer.py
|
||||
include src/octoprint/_version.py
|
||||
@@ -8,26 +8,26 @@ and released under the [GNU Affero General Public License V3](http://www.gnu.org
|
||||
|
||||
Its website can be found at [octoprint.org](http://octoprint.org).
|
||||
|
||||
Reporting bugs
|
||||
--------------
|
||||
Contributing
|
||||
------------
|
||||
|
||||
OctoPrint's issue tracker can be found [on Github](https://github.com/foosel/OctoPrint/issues). **Before opening a new
|
||||
ticket please take a look at [this guide on how to file a bug report with OctoPrint](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report).**
|
||||
Please see the project's [Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
|
||||
|
||||
Sending pull requests
|
||||
---------------------
|
||||
Installation
|
||||
------------
|
||||
|
||||
Please create all pull requests against the [devel branch](https://github.com/foosel/OctoPrint/tree/devel) of OctoPrint, as that one is used for developing new
|
||||
features and then merged against master when those features are deemed mature enough for general consumption. In case
|
||||
of bug fixes I'll take care to cherry pick them against master if the bugs they are fixing are critical.
|
||||
Installation instructions for installing from source for different operating systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
|
||||
|
||||
If you want to run OctoPrint on a Raspberry Pi you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
|
||||
which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||
|
||||
Dependencies
|
||||
------------
|
||||
|
||||
OctoPrint depends on a couple of python modules to do its job. Those are listed in requirements.txt and can be
|
||||
installed using `pip`:
|
||||
OctoPrint depends on a couple of python modules to do its job. Those are automatically installed when installing
|
||||
OctoPrint via `setup.py`:
|
||||
|
||||
pip install -r requirements.txt
|
||||
python setup.py install
|
||||
|
||||
You should also do this after pulling from the repository, since the dependencies might have changed.
|
||||
|
||||
@@ -36,7 +36,7 @@ OctoPrint currently only supports Python 2.7.
|
||||
Usage
|
||||
-----
|
||||
|
||||
Just start the server via
|
||||
From the source directory you can start the server via
|
||||
|
||||
./run
|
||||
|
||||
@@ -62,6 +62,11 @@ e.g.:
|
||||
|
||||
See `run --help` for further information.
|
||||
|
||||
Running the `setup.py` script also installs the `octoprint` startup script in your Python installation's scripts folder
|
||||
(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The
|
||||
examples above also work with that startup script as it excepts the same parameters as `run`.
|
||||
|
||||
|
||||
Configuration
|
||||
-------------
|
||||
|
||||
@@ -71,8 +76,3 @@ at `~/Library/Application Support/OctoPrint` on MacOS.
|
||||
|
||||
A comprehensive overview of all available configuration settings can be found
|
||||
[on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration).
|
||||
|
||||
Setup on a Raspberry Pi running Raspbian
|
||||
----------------------------------------
|
||||
|
||||
A comprehensive setup guide can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki/Setup-on-a-Raspberry-Pi-running-Raspbian).
|
||||
@@ -0,0 +1,177 @@
|
||||
# Makefile for Sphinx documentation
|
||||
#
|
||||
|
||||
# You can set these variables from the command line.
|
||||
SPHINXOPTS =
|
||||
SPHINXBUILD = sphinx-build
|
||||
PAPER =
|
||||
BUILDDIR = _build
|
||||
|
||||
# User-friendly check for sphinx-build
|
||||
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
|
||||
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
|
||||
endif
|
||||
|
||||
# Internal variables.
|
||||
PAPEROPT_a4 = -D latex_paper_size=a4
|
||||
PAPEROPT_letter = -D latex_paper_size=letter
|
||||
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
|
||||
# the i18n builder cannot share the environment and doctrees with the others
|
||||
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
|
||||
|
||||
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
|
||||
|
||||
help:
|
||||
@echo "Please use \`make <target>' where <target> is one of"
|
||||
@echo " html to make standalone HTML files"
|
||||
@echo " dirhtml to make HTML files named index.html in directories"
|
||||
@echo " singlehtml to make a single large HTML file"
|
||||
@echo " pickle to make pickle files"
|
||||
@echo " json to make JSON files"
|
||||
@echo " htmlhelp to make HTML files and a HTML help project"
|
||||
@echo " qthelp to make HTML files and a qthelp project"
|
||||
@echo " devhelp to make HTML files and a Devhelp project"
|
||||
@echo " epub to make an epub"
|
||||
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
|
||||
@echo " latexpdf to make LaTeX files and run them through pdflatex"
|
||||
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
|
||||
@echo " text to make text files"
|
||||
@echo " man to make manual pages"
|
||||
@echo " texinfo to make Texinfo files"
|
||||
@echo " info to make Texinfo files and run them through makeinfo"
|
||||
@echo " gettext to make PO message catalogs"
|
||||
@echo " changes to make an overview of all changed/added/deprecated items"
|
||||
@echo " xml to make Docutils-native XML files"
|
||||
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
|
||||
@echo " linkcheck to check all external links for integrity"
|
||||
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
|
||||
|
||||
clean:
|
||||
rm -rf $(BUILDDIR)/*
|
||||
|
||||
html:
|
||||
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
|
||||
@echo
|
||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
|
||||
|
||||
dirhtml:
|
||||
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
|
||||
@echo
|
||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
|
||||
|
||||
singlehtml:
|
||||
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
|
||||
@echo
|
||||
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
|
||||
|
||||
pickle:
|
||||
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
|
||||
@echo
|
||||
@echo "Build finished; now you can process the pickle files."
|
||||
|
||||
json:
|
||||
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
|
||||
@echo
|
||||
@echo "Build finished; now you can process the JSON files."
|
||||
|
||||
htmlhelp:
|
||||
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
|
||||
@echo
|
||||
@echo "Build finished; now you can run HTML Help Workshop with the" \
|
||||
".hhp project file in $(BUILDDIR)/htmlhelp."
|
||||
|
||||
qthelp:
|
||||
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
|
||||
@echo
|
||||
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
|
||||
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
|
||||
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/OctoPrint.qhcp"
|
||||
@echo "To view the help file:"
|
||||
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/OctoPrint.qhc"
|
||||
|
||||
devhelp:
|
||||
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
|
||||
@echo
|
||||
@echo "Build finished."
|
||||
@echo "To view the help file:"
|
||||
@echo "# mkdir -p $$HOME/.local/share/devhelp/OctoPrint"
|
||||
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/OctoPrint"
|
||||
@echo "# devhelp"
|
||||
|
||||
epub:
|
||||
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
|
||||
@echo
|
||||
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
|
||||
|
||||
latex:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo
|
||||
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
|
||||
@echo "Run \`make' in that directory to run these through (pdf)latex" \
|
||||
"(use \`make latexpdf' here to do that automatically)."
|
||||
|
||||
latexpdf:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo "Running LaTeX files through pdflatex..."
|
||||
$(MAKE) -C $(BUILDDIR)/latex all-pdf
|
||||
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
|
||||
|
||||
latexpdfja:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo "Running LaTeX files through platex and dvipdfmx..."
|
||||
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
|
||||
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
|
||||
|
||||
text:
|
||||
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
|
||||
@echo
|
||||
@echo "Build finished. The text files are in $(BUILDDIR)/text."
|
||||
|
||||
man:
|
||||
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
|
||||
@echo
|
||||
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
|
||||
|
||||
texinfo:
|
||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||
@echo
|
||||
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
|
||||
@echo "Run \`make' in that directory to run these through makeinfo" \
|
||||
"(use \`make info' here to do that automatically)."
|
||||
|
||||
info:
|
||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||
@echo "Running Texinfo files through makeinfo..."
|
||||
make -C $(BUILDDIR)/texinfo info
|
||||
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
|
||||
|
||||
gettext:
|
||||
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
|
||||
@echo
|
||||
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
|
||||
|
||||
changes:
|
||||
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
|
||||
@echo
|
||||
@echo "The overview file is in $(BUILDDIR)/changes."
|
||||
|
||||
linkcheck:
|
||||
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
|
||||
@echo
|
||||
@echo "Link check complete; look for any errors in the above output " \
|
||||
"or in $(BUILDDIR)/linkcheck/output.txt."
|
||||
|
||||
doctest:
|
||||
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
|
||||
@echo "Testing of doctests in the sources finished, look at the " \
|
||||
"results in $(BUILDDIR)/doctest/output.txt."
|
||||
|
||||
xml:
|
||||
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
|
||||
@echo
|
||||
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
|
||||
|
||||
pseudoxml:
|
||||
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
|
||||
@echo
|
||||
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
|
||||
@@ -0,0 +1,119 @@
|
||||
.. _sec-api-connection:
|
||||
|
||||
*******************
|
||||
Connection handling
|
||||
*******************
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-connection-current:
|
||||
|
||||
Get connection settings
|
||||
=======================
|
||||
|
||||
.. http:get:: /api/connection
|
||||
|
||||
Retrieve the current connection settings, including information regarding the available baudrates and
|
||||
serial ports and the current connection state.
|
||||
|
||||
**Example Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/connection HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
**Example Response**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"current": {
|
||||
"state": "Operational",
|
||||
"port": "/dev/ttyACM0",
|
||||
"baudrate": 250000
|
||||
},
|
||||
"options": {
|
||||
"ports": ["/dev/ttyACM0", "VIRTUAL"],
|
||||
"baudrates": [250000, 230400, 115200, 57600, 38400, 19200, 9600],
|
||||
"portPreference": "/dev/ttyACM0",
|
||||
"baudratePreference": 250000,
|
||||
"autoconnect": true
|
||||
}
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-connection-command:
|
||||
|
||||
Issue a connection command
|
||||
==========================
|
||||
|
||||
.. http:post:: /api/connection
|
||||
|
||||
Issue a connection command. Currently available command are:
|
||||
|
||||
connect
|
||||
Instructs OctoPrint to connect to the printer. Additional parameters are:
|
||||
|
||||
* ``port``: Optional, specific port to connect to. If not set the current ``portPreference`` will be used, or if
|
||||
no preference is available auto detection will be attempted.
|
||||
* ``baudrate``: Optional, specific baudrate to connect with. If not set the current ``baudratePreference`` will
|
||||
be used, or if no preference is available auto detection will be attempted.
|
||||
* ``save``: Optional, whether to save the request's ``port`` and ``baudrate`` settings as new preferences. Defaults
|
||||
to ``false`` if not set.
|
||||
* ``autoconnect``: Optional, whether to automatically connect to the printer on OctoPrint's startup in the future.
|
||||
If not set no changes will be made to the current configuration.
|
||||
|
||||
disconnect
|
||||
Instructs OctoPrint to disconnect from the printer.
|
||||
|
||||
**Example Connect Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/connection HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "connect",
|
||||
"port": "/dev/ttyACM0",
|
||||
"baudrate": 115200,
|
||||
"save": true,
|
||||
"autoconnect": true
|
||||
}
|
||||
|
||||
**Example Disconnect Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/connection HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "disconnect"
|
||||
}
|
||||
|
||||
:json string command: The command to issue, either ``connect`` or ``disconnect``
|
||||
:json string port: ``connect`` command: The port to connect to. If left out either the existing ``portPreference``
|
||||
will be used, or if that is not available OctoPrint will attempt auto detection. Must be part
|
||||
of the available ports.
|
||||
:json number baudrate: ``connect`` command: The baudrate to connect with. If left out either the existing
|
||||
``baudratePreference`` will be used, or if that is not available OctoPrint will attempt
|
||||
autodetection. Must be part of the available baudrates.
|
||||
:json boolean save: ``connect`` command: Whether to save the supplied connection settings as the new preference.
|
||||
Defaults to ``false`` if not set.
|
||||
:json boolean autoconnect: ``connect`` command: Whether to attempt to automatically connect to the printer on server
|
||||
startup. If not set no changes will be made to the current setting.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If the selected `port` or `baudrate` for a ``connect`` command are not part of the available
|
||||
options.
|
||||
@@ -0,0 +1,562 @@
|
||||
.. _sec-api-fileops:
|
||||
|
||||
***************
|
||||
File operations
|
||||
***************
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-fileops-retrieveall:
|
||||
|
||||
Retrieve all files
|
||||
==================
|
||||
|
||||
.. http:get:: /api/files
|
||||
|
||||
Retrieve information regarding all files currently available and regarding the disk space still available
|
||||
locally in the system.
|
||||
|
||||
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
|
||||
|
||||
**Example request**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/files HTTP/1.1
|
||||
Host: example.com
|
||||
|
||||
**Example response**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"name": "whistle_v2.gcode",
|
||||
"size": 1468987,
|
||||
"date": 1378847754,
|
||||
"origin": "local",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
|
||||
"download": "http://example.com/downloads/files/local/whistle_v2.gcode"
|
||||
},
|
||||
"gcodeAnalysis": {
|
||||
"estimatedPrintTime": 1188,
|
||||
"filament": {
|
||||
"length": 810,
|
||||
"volume": 5.36
|
||||
}
|
||||
},
|
||||
"print": {
|
||||
"failure": 4,
|
||||
"success": 23,
|
||||
"last": {
|
||||
"date": 1387144346,
|
||||
"success": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "whistle_.gco",
|
||||
"origin": "sdcard",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/sdcard/whistle_.gco"
|
||||
}
|
||||
}
|
||||
],
|
||||
"free": "3.2GB"
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-fileops-retrievelocation:
|
||||
|
||||
Retrieve files from specific location
|
||||
=====================================
|
||||
|
||||
.. http:get:: /api/files/(string:location)
|
||||
|
||||
Retrieve information regarding the files currently available on the selected `location` and -- if targeting
|
||||
the ``local`` location -- regarding the disk space still available locally in the system.
|
||||
|
||||
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
|
||||
|
||||
**Example request**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/files/local HTTP/1.1
|
||||
Host: example.com
|
||||
|
||||
**Example response**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"name": "whistle_v2.gcode",
|
||||
"size": 1468987,
|
||||
"date": 1378847754,
|
||||
"origin": "local",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
|
||||
"download": "http://example.com/downloads/files/local/whistle_v2.gcode"
|
||||
},
|
||||
"gcodeAnalysis": {
|
||||
"estimatedPrintTime": 1188,
|
||||
"filament": {
|
||||
"length": 810,
|
||||
"volume": 5.36
|
||||
}
|
||||
},
|
||||
"print": {
|
||||
"failure": 4,
|
||||
"success": 23,
|
||||
"last": {
|
||||
"date": 1387144346,
|
||||
"success": true
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"free": "3.2GB"
|
||||
}
|
||||
|
||||
:param location: The origin location from which to retrieve the files. Currently only ``local`` and ``sdcard`` are
|
||||
supported, with ``local`` referring to files stored in OctoPrint's ``uploads`` folder and ``sdcard``
|
||||
referring to files stored on the printer's SD card (if available).
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If `location` is neither ``local`` nor ``sdcard``
|
||||
|
||||
.. _sec-api-fileops-uploadfile:
|
||||
|
||||
Upload file
|
||||
===========
|
||||
|
||||
.. http:post:: /api/files/(string:location)
|
||||
|
||||
Upload a file to the selected `location`.
|
||||
|
||||
Other than most of the other requests on OctoPrint's API which are expected as JSON, this request is expected as
|
||||
``Content-Type: multipart/form-data`` due to the included file upload.
|
||||
|
||||
Returns a :http:statuscode:`201` response with a ``Location`` header set to the management URL of the uploaded
|
||||
file and an :ref:`Upload Response <sec-api-fileops-datamodel-uploadresponse>` as the body upon successful completion.
|
||||
|
||||
**Example request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/files/sdcard HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||
|
||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||
Content-Disposition: form-data; name="file"; filename="whistle_v2.gcode"
|
||||
Content-Type: application/octet-stream
|
||||
|
||||
;Generated with Cura_SteamEngine 13.11.2
|
||||
M109 T0 S220.000000
|
||||
T0
|
||||
;Sliced at: Wed 11-12-2013 16:53:12
|
||||
;Basic settings: Layer height: 0.2 Walls: 0.8 Fill: 20
|
||||
;Print time: #P_TIME#
|
||||
;Filament used: #F_AMNT#m #F_WGHT#g
|
||||
;Filament cost: #F_COST#
|
||||
;M190 S70 ;Uncomment to add your own bed temperature line
|
||||
;M109 S220 ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
...
|
||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||
Content-Disposition: form-data; name="select"
|
||||
|
||||
true
|
||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||
Content-Disposition: form-data; name="print"
|
||||
|
||||
true
|
||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC--
|
||||
|
||||
**Example response**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
Location:
|
||||
|
||||
{
|
||||
"files": {
|
||||
"local": {
|
||||
"name": "whistle_v2.gcode",
|
||||
"origin": "local",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
|
||||
"download": "http://example.com/downloads/files/local/whistle_v2.gcode"
|
||||
}
|
||||
},
|
||||
"sdcard": {
|
||||
"name": "whistle_.gco",
|
||||
"origin": "sdcard",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/sdcard/whistle_.gco"
|
||||
}
|
||||
}
|
||||
},
|
||||
"done": true
|
||||
}
|
||||
|
||||
:param location: The target location to which to upload the file. Currently only ``local`` and ``sdcard`` are supported
|
||||
here, with ``local`` referring to OctoPrint's ``uploads`` folder and ``sdcard`` referring to
|
||||
the printer's SD card. If an upload targets the SD card, it will also be stored locally first.
|
||||
:form file: The file to upload, including a valid ``filename``.
|
||||
:form select: Whether to select the file directly after upload (``true``) or not (``false``). Optional, defaults
|
||||
to ``false``.
|
||||
:form print: Whether to start printing the file directly after upload (``true``) or not (``false``). If set, `select`
|
||||
is implicitely ``true`` as well. Optional, defaults to ``false``.
|
||||
:statuscode 201: No error
|
||||
:statuscode 400: If no `file` is included in the request, or the request is otherwise invalid.
|
||||
:statuscode 404: If `location` is neither ``local`` nor ``sdcard`` or trying to upload to SD card and SD card support
|
||||
is disabled
|
||||
:statuscode 409: If the upload of the file would override the file that is currently being printed or if an upload
|
||||
to SD card was requested and the printer is either not operational or currently busy with a print job.
|
||||
:statuscode 415: If the file is neither a ``gcode`` nor an ``stl`` file (or it is an ``stl`` file but slicing support
|
||||
is disabled)
|
||||
:statuscode 500: If the upload failed internally
|
||||
|
||||
.. _sec-api-fileops-retrievefileinfo:
|
||||
|
||||
Retrieve a specific file's information
|
||||
======================================
|
||||
|
||||
.. http:get:: /api/files/(string:location)/(path:filename)
|
||||
|
||||
Retrieves the selected file's information.
|
||||
|
||||
If the file is unknown, a :http:statuscode:`404` is returned.
|
||||
|
||||
On success, a :http:statuscode:`200` is returned, with a :ref:`file information item <sec-api-fileops-datamodel-fileinfo>`
|
||||
as the response body.
|
||||
|
||||
**Example Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/files/local/whistle_v2.gcode HTTP/1.1
|
||||
Host: example.com
|
||||
|
||||
**Example Response**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 Ok
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "whistle_v2.gcode",
|
||||
"size": 1468987,
|
||||
"date": 1378847754,
|
||||
"origin": "local",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
|
||||
"download": "http://example.com/downloads/files/local/whistle_v2.gcode"
|
||||
},
|
||||
"gcodeAnalysis": {
|
||||
"estimatedPrintTime": 1188,
|
||||
"filament": {
|
||||
"length": 810,
|
||||
"volume": 5.36
|
||||
}
|
||||
},
|
||||
"print": {
|
||||
"failure": 4,
|
||||
"success": 23,
|
||||
"last": {
|
||||
"date": 1387144346,
|
||||
"success": true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:param location: The location of the file for which to retrieve the information, either ``local`` or ``sdcard``.
|
||||
:param filename: The filename of the file for which to retrieve the information
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If `target` is neither ``local`` nor ``sdcard``, ``sdcard`` but SD card support is disabled or the
|
||||
requested file was not found
|
||||
|
||||
.. _sec-api-fileops-filecommand:
|
||||
|
||||
Issue a file command
|
||||
====================
|
||||
|
||||
.. http:post:: /api/files/(string:target)/(path:filename)
|
||||
|
||||
Issue a file command to an existing file. Currently supported commands are:
|
||||
|
||||
select
|
||||
Selects a file for printing. Additional parameters are:
|
||||
|
||||
* ``print``: Optional, if set to ``true`` the file will start printing directly after selection. If the printer
|
||||
is not operational when this parameter is present and set to ``true``, the request will fail with a response
|
||||
of ``409 Conflict``.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
**Example Select Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/files/local/whistle_v2.gcode HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "select",
|
||||
"print": true
|
||||
}
|
||||
|
||||
:param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads``
|
||||
folder) or ``sdcard`` for the printer's SD card (if available)
|
||||
:param filename: The filename of the file for which to issue the command
|
||||
:json string command: The command to issue for the file, currently only ``select`` is supported
|
||||
:json boolean print: ``select`` command: Optional, whether to start printing the file directly after selection,
|
||||
defaults to ``false``.
|
||||
:statuscode 200: No error
|
||||
:statuscode 400: If the `command` is unknown or the request is otherwise invalid
|
||||
:statuscode 404: If `target` is neither ``local`` nor ``sdcard`` or the requested file was not found
|
||||
:statuscode 409: If a selected file is supposed to start printing directly but the printer is not operational.
|
||||
|
||||
.. _sec-api-fileops-delete:
|
||||
|
||||
Delete file
|
||||
===========
|
||||
|
||||
.. http:delete:: /api/files/(string:target)/(path:filename)
|
||||
|
||||
Delete the selected `filename` on the selected `target`.
|
||||
|
||||
If the file to be deleted is currently being printed, a :http:statuscode:`409` will be returned.
|
||||
|
||||
Returns a :http:statuscode:`204` after successful deletion.
|
||||
|
||||
**Example Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
DELETE /api/files/local/whistle_v2.gcode HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
:param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads``
|
||||
folder) or ``sdcard`` for the printer's SD card (if available)
|
||||
:param filename: The filename of the file to delete
|
||||
:statuscode 204: No error
|
||||
:statuscode 404: If `target` is neither ``local`` nor ``sdcard`` or the requested file was not found
|
||||
:statuscode 409: If the file to be deleted is currently being printed
|
||||
|
||||
.. _sec-api-fileops-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-fileops-datamodel-retrieveresponse:
|
||||
|
||||
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-fileops-datamodel-fileinfo>`
|
||||
- The list of requested files. Might be an empty list if no files are available
|
||||
* - ``free``
|
||||
- 0..1
|
||||
- String
|
||||
- The amount of disk space in bytes available in the local disk space (refers to OctoPrint's ``uploads`` folder). Only
|
||||
returned if file list was requested for origin ``local`` or all origins.
|
||||
|
||||
.. _sec-api-fileops-datamodel-uploadresponse:
|
||||
|
||||
Upload response
|
||||
---------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``files``
|
||||
- 1
|
||||
- Object
|
||||
- Abridged information regarding the file that was just uploaded. If only uploaded to ``local`` this will only
|
||||
contain the ``local`` property. If uploaded to SD card, this will contain both ``local`` and ``sdcard`` properties.
|
||||
* - ``files.local``
|
||||
- 1
|
||||
- :ref:`sec-api-fileops-datamodel-fileinfo`
|
||||
- The information regarding the file that was just uploaded to the local storage (only the fields ``name``,
|
||||
``origin`` and ``refs`` will be set).
|
||||
* - ``files.sdcard``
|
||||
- 0..1
|
||||
- :ref:`sec-api-fileops-datamodel-fileinfo`
|
||||
- The information regarding the file that was just uploaded to the printer's SD card (only the fields ``name``,
|
||||
``origin`` and ``refs`` will be set).
|
||||
* - ``done``
|
||||
- 1
|
||||
- Boolean
|
||||
- Whether the file processing after upload has already finished (``true``) or not, e.g. due to first needing
|
||||
to perform a slicing step (``false``). Clients may use this information to direct progress displays related to
|
||||
the upload.
|
||||
|
||||
.. _sec-api-fileops-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``
|
||||
- 0..1
|
||||
- Number
|
||||
- The size of the file in bytes. Only available for ``local`` files.
|
||||
* - ``date``
|
||||
- 0..1
|
||||
- Unix timestamp
|
||||
- The timestamp when this file was uploaded. Only available for ``local`` files.
|
||||
* - ``origin``
|
||||
- 1
|
||||
- String, either ``local`` or ``sdcard``
|
||||
- The origin of the file, ``local`` when stored in OctoPrint's ``uploads`` folder, ``sdcard`` when stored on the
|
||||
printer's SD card (if available)
|
||||
* - ``refs``
|
||||
- 0..1
|
||||
- :ref:`sec-api-fileops-datamodel-ref`
|
||||
- References relevant to this file
|
||||
* - ``gcodeAnalysis``
|
||||
- 0..1
|
||||
- :ref:`GCODE analysis information <sec-api-fileops-datamodel-gcodeanalysis>`
|
||||
- Information from the analysis of the GCODE file, if available.
|
||||
* - ``prints``
|
||||
- 0..1
|
||||
- :ref:`Print information <sec-api-fileops-datamodel-prints>`
|
||||
- Information regarding prints of this file, if available.
|
||||
|
||||
.. _sec-api-fileops-datamodel-gcodeanalysis:
|
||||
|
||||
GCODE analysis information
|
||||
--------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``estimatedPrintTime``
|
||||
- 0..1
|
||||
- Integer
|
||||
- The estimated print time of the file, in seconds
|
||||
* - ``filament``
|
||||
- 0..1
|
||||
- Object
|
||||
- The estimated usage of filament
|
||||
* - ``filament.length``
|
||||
- 0..1
|
||||
- Integer
|
||||
- The length of filament used, in mm
|
||||
* - ``filament.volume``
|
||||
- 0..1
|
||||
- Float
|
||||
- The volume of filament used, in cm³
|
||||
|
||||
|
||||
.. _sec-api-fileops-datamodel-prints:
|
||||
|
||||
Print information
|
||||
-----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``failure``
|
||||
- 1
|
||||
- Number
|
||||
- The number of failed prints on record for the file
|
||||
* - ``success``
|
||||
- 1
|
||||
- Number
|
||||
- The number of successful prints on record for the file
|
||||
* - ``last``
|
||||
- 0..1
|
||||
- Object
|
||||
- Information regarding the last print on record for the file
|
||||
* - ``last.date``
|
||||
- 1
|
||||
- Unix timestamp
|
||||
- Timestamp when this file was printed last
|
||||
* - ``last.success``
|
||||
- 1
|
||||
- Boolean
|
||||
- Whether the last print on record was a success (``true``) or not (``false``)
|
||||
|
||||
.. _sec-api-fileops-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 issuing commands to or for deleting)
|
||||
* - ``download``
|
||||
- 0..1
|
||||
- URL
|
||||
- The download URL for the file
|
||||
* - ``model``
|
||||
- 0..1
|
||||
- URL
|
||||
- The model from which this file was generated (e.g. an STL, currently not used)
|
||||
@@ -0,0 +1,70 @@
|
||||
.. _sec-api-general:
|
||||
|
||||
*******************
|
||||
General information
|
||||
*******************
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-general-authorization:
|
||||
|
||||
Authorization
|
||||
=============
|
||||
|
||||
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
|
||||
configured one or a user specific one if "Access Control" is enabled. 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.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/files HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`401`.
|
||||
|
||||
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/files?apikey=abcdef... HTTP/1.1
|
||||
Host: example.com
|
||||
|
||||
Please be advised that clients should use the header field variant if at all possible.
|
||||
|
||||
.. _fig-api-general-globalapikey:
|
||||
.. figure:: ../images/settings-global-api-key.png
|
||||
:align: center
|
||||
:alt: Global API key in the API settings
|
||||
|
||||
The global API key can be found in the "API" settings
|
||||
|
||||
.. _fig-api-general-userapikey:
|
||||
.. figure:: ../images/settings-user-api-key.png
|
||||
:align: center
|
||||
:alt: User specific API key location in user list
|
||||
|
||||
The user list in the "Access Control" settings shows the API key for users (if available)
|
||||
|
||||
.. _fig-api-general-changepassword:
|
||||
.. figure:: ../images/change-password-api-key.png
|
||||
:align: center
|
||||
:alt: API key options in "Change password" dialog
|
||||
|
||||
The API key options in the "Change password" dialog. Users can generate and revoke their custom API key here.
|
||||
|
||||
.. _sec-api-general-contenttype:
|
||||
|
||||
Content Type
|
||||
============
|
||||
|
||||
If not otherwise stated OctoPrint's API expects request bodies and issues response bodies as ``Content-Type: application/json``.
|
||||
|
||||
.. _sec-api-general-encoding:
|
||||
|
||||
Encoding
|
||||
========
|
||||
|
||||
OctoPrint uses UTF-8 as charset.
|
||||
@@ -0,0 +1,16 @@
|
||||
.. _sec-api:
|
||||
|
||||
#################
|
||||
API Documentation
|
||||
#################
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
general.rst
|
||||
version.rst
|
||||
fileops.rst
|
||||
connection.rst
|
||||
printer.rst
|
||||
job.rst
|
||||
logs.rst
|
||||
@@ -0,0 +1,248 @@
|
||||
.. _sec-api-jobs:
|
||||
|
||||
**************
|
||||
Job operations
|
||||
**************
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-jobs-command:
|
||||
|
||||
Issue a job command
|
||||
===================
|
||||
|
||||
.. http:post:: /api/job
|
||||
|
||||
Job commands allow starting, pausing and cancelling print jobs. Available commands are:
|
||||
|
||||
start
|
||||
Starts the print of the currently selected file. For selecting a file, see :ref:`Issue a file command <sec-api-fileops-filecommand>`.
|
||||
If a print job is already active, a :http:statuscode:`409` will be returned.
|
||||
|
||||
restart
|
||||
Restart the print of the currently selected file from the beginning. There must be an active print job for this to work
|
||||
and the print job must currently be paused. If either is not the case, a :http:statuscode:`409` will be returned.
|
||||
|
||||
pause
|
||||
Pauses/unpauses the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409`
|
||||
will be returned.
|
||||
|
||||
cancel
|
||||
Cancels the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409`
|
||||
will be returned.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
**Example Start Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "start"
|
||||
}
|
||||
|
||||
**Example Restart Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "restart"
|
||||
}
|
||||
|
||||
**Example Pause Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "pause"
|
||||
}
|
||||
|
||||
**Example Cancel Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "cancel"
|
||||
}
|
||||
|
||||
:json string command: The command to issue, either ``start``, ``restart``, ``pause`` or ``cancel``
|
||||
:statuscode 204: No error
|
||||
:statuscode 409: If the printer is not operational or the current print job state does not match the preconditions
|
||||
for the command.
|
||||
|
||||
.. _sec-api-job-information:
|
||||
|
||||
Retrieve information about the current job
|
||||
==========================================
|
||||
|
||||
.. http:get:: /api/job
|
||||
|
||||
Retrieve information about the current job (if there is one).
|
||||
|
||||
Returns a :http:statuscode:`200` with a :ref:`sec-api-job-datamodel-response` in the body.
|
||||
|
||||
**Example Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
|
||||
**Example Response**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"job": {
|
||||
"file": {
|
||||
"name": "whistle_v2.gcode",
|
||||
"origin": "local",
|
||||
"size": 1468987,
|
||||
"date": 1378847754
|
||||
},
|
||||
"estimatedPrintTime": 8811,
|
||||
"filament": {
|
||||
"length": 810,
|
||||
"volume": 5.36
|
||||
}
|
||||
},
|
||||
"progress": {
|
||||
"completion": 0.2298468264184775,
|
||||
"filepos": 337942,
|
||||
"printTime": 276,
|
||||
"printTimeLeft": 912
|
||||
}
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-job-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-job-datamodel-response:
|
||||
|
||||
Job information response
|
||||
------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``job``
|
||||
- 1
|
||||
- :ref:`sec-api-job-datamodel-job`
|
||||
- Information regarding the target of the current print job
|
||||
* - ``progress``
|
||||
- 1
|
||||
- :ref:`sec-api-job-datamodel-progress`
|
||||
- Information regarding the progress of the current print job
|
||||
|
||||
.. _sec-api-job-datamodel-job:
|
||||
|
||||
Job information
|
||||
---------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``file``
|
||||
- 1
|
||||
- Object
|
||||
- The file that is the target of the current print job
|
||||
* - ``file.name``
|
||||
- 1
|
||||
- String
|
||||
- The file's name
|
||||
* - ``file.origin``
|
||||
- 1
|
||||
- String, either ``local`` or ``sdcard``
|
||||
- The file's origin, either ``local`` or ``sdcard``
|
||||
* - ``file.size``
|
||||
- 0..1
|
||||
- Integer
|
||||
- The file's size, in bytes. Only available for files stored locally.
|
||||
* - ``file.date``
|
||||
- 0..1
|
||||
- Unix timestamp
|
||||
- The file's upload date. Only available for files stored locally.
|
||||
* - ``estimatedPrintTime``
|
||||
- 0..1
|
||||
- Integer
|
||||
- The estimated print time for the file, in seconds.
|
||||
* - ``filament``
|
||||
- 0..1
|
||||
- Object
|
||||
- Information regarding the estimated filament usage of the print job
|
||||
* - ``filament.length``
|
||||
- 0..1
|
||||
- Integer
|
||||
- Length of filament used, in mm
|
||||
* - ``filament.volume``
|
||||
- 0..1
|
||||
- Float
|
||||
- Volume of filament used, in cm³
|
||||
|
||||
.. _sec-api-job-datamodel-progress:
|
||||
|
||||
Progress information
|
||||
--------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``completion``
|
||||
- 1
|
||||
- Float
|
||||
- Percentage of completion of the current print job
|
||||
* - ``filepos``
|
||||
- 1
|
||||
- Integer
|
||||
- Current position in the file being printed, in bytes from the beginning
|
||||
* - ``printTime``
|
||||
- 1
|
||||
- Integer
|
||||
- Time already spent printing, in seconds
|
||||
* - ``printTimeLeft``
|
||||
- 1
|
||||
- Integer
|
||||
- Estimate of time left to print, in seconds
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
.. _sec-api-logs:
|
||||
|
||||
*******************
|
||||
Log file management
|
||||
*******************
|
||||
|
||||
.. note::
|
||||
|
||||
All log file management operations require admin rights.
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-logs-list:
|
||||
|
||||
Retrieve a list of available log files
|
||||
======================================
|
||||
|
||||
.. http:post:: /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 Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/logs HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
**Example response**:
|
||||
|
||||
.. 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:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _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
|
||||
@@ -0,0 +1,369 @@
|
||||
.. _sec-api-printer:
|
||||
|
||||
******************
|
||||
Printer operations
|
||||
******************
|
||||
|
||||
.. warning::
|
||||
|
||||
This part of the API is still heavily in development, especially anything that has to do with temperature control.
|
||||
If you happen to want to develop against it, you should drop me an email to make sure I can give you a heads-up when
|
||||
something changes.
|
||||
|
||||
.. contents::
|
||||
|
||||
Printer control is mostly achieved through the use of commands, issued to resources reflecting components of the
|
||||
printer. OctoPrint currently knows the following components:
|
||||
|
||||
Print head
|
||||
Print head commands allow jogging and homing the print head in all three axes. See :ref:`sec-api-printer-printheadcommand`.
|
||||
Heater
|
||||
Heater commands allow setting the temperature and temperature offsets for the printer's hotend and bed. Currently
|
||||
OctoPrint only supports one hotend heater (this will change in the future). See :ref:`sec-api-printer-heatercommand`.
|
||||
Feeder
|
||||
Feeder commands allow extrusion/extraction of filament. Currently OctoPrint only supports one feeder (this will
|
||||
change in a future version). See :ref:`sec-api-printer-feedercommand`.
|
||||
SD card
|
||||
SD commands allow initialization, refresh and release of the printer's SD card (if available). See :ref:`sec-api-printer-sdcommand`.
|
||||
|
||||
.. _sec-api-printer-printheadcommand:
|
||||
|
||||
Issue a print head command
|
||||
==========================
|
||||
|
||||
.. http:post:: /api/printer/printhead
|
||||
|
||||
Print head commands allow jogging and homing the print head in all three axes. Available commands are:
|
||||
|
||||
jog
|
||||
Jogs the print head (relatively) by a defined amount in one or more axes. Additional parameters are:
|
||||
|
||||
* ``x``: Optional. Amount to jog print head on x axis, must be a valid number corresponding to the distance to travel in mm.
|
||||
* ``y``: Optional. Amount to jog print head on y axis, must be a valid number corresponding to the distance to travel in mm.
|
||||
* ``z``: Optional. Amount to jog print head on z axis, must be a valid number corresponding to the distance to travel in mm.
|
||||
|
||||
home
|
||||
Homes the print head in all of the given axes. Additional parameters are:
|
||||
|
||||
* ``axes``: A list of axes which to home, valid values are one or more of ``x``, ``y``, ``z``.
|
||||
|
||||
All of these commands may only be sent if the printer is currently operational and not printing. Otherwise a
|
||||
:http:statuscode:`409` is returned.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
**Example Jog Request**
|
||||
|
||||
Jog the print head by 10mm in X, -5mm in Y and 0.02mm in Z.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/printhead HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "jog",
|
||||
"x": 10,
|
||||
"y": -5,
|
||||
"z": 0.02
|
||||
}
|
||||
|
||||
**Example Home Request**
|
||||
|
||||
Home the X and Y axes.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/printhead HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "home",
|
||||
"axes": ["x", "y"]
|
||||
}
|
||||
|
||||
:json string command: The command to issue, either ``jog`` or ``home``.
|
||||
:json number x: ``jog`` command: The amount to travel on the X axis in mm.
|
||||
:json number y: ``jog`` command: The amount to travel on the Y axis in mm.
|
||||
:json number z: ``jog`` command: The amount to travel on the Z axis in mm.
|
||||
:json array axes: ``home`` command: The axes which to home, valid values are one or more of ``x``, ``y`` and ``z``.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: Invalid axis specified, invalid value for travel amount for a jog command or otherwise invalid
|
||||
request.
|
||||
:statuscode 409: If the printer is not operational or currently printing.
|
||||
|
||||
.. _sec-api-printer-heatercommand:
|
||||
|
||||
Issue a heater command
|
||||
======================
|
||||
|
||||
.. todo::
|
||||
|
||||
Update to current implementation!
|
||||
|
||||
.. http:post:: /api/printer/heater
|
||||
|
||||
Heater commands allow setting the temperature and temperature offsets for the printer's hotend and bed. Available
|
||||
commands are:
|
||||
|
||||
temp
|
||||
Sets the given target temperature on the printer's hotend and/or bed. Additional parameters:
|
||||
|
||||
* ``targets``: Target temperature(s) to set, allowed properties are:
|
||||
|
||||
* ``hotend``: New target temperature of the printer's hotend in centigrade.
|
||||
* ``bed``: New target temperature of the printer's bed in centigrade.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's hotend and/or bed. Additional parameters:
|
||||
|
||||
* ``offsets``: Offset(s) to set, allowed properties are:
|
||||
|
||||
* ``hotend``: New offset of the printer's hotend temperature in centigrade, max/min of +/-50°C.
|
||||
* ``bed``: New offset of the printer's bed temperature in centigrade, max/min of +/-50°C.
|
||||
|
||||
All of these commands may only be sent if the printer is currently operational and not printing. Otherwise a
|
||||
:http:statuscode:`409` is returned.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
Set the printer's hotend target temperature to 220°C and the bed target temperature to 75°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/heater HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "temp",
|
||||
"temps": {
|
||||
"hotend": 220,
|
||||
"bed": 75
|
||||
}
|
||||
}
|
||||
|
||||
**Example Offset Temperature Request**
|
||||
|
||||
Set the offset for hotend temperatures to +10°C and for bed temperatures to -5°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/heater HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "offset",
|
||||
"offsets": {
|
||||
"hotend": 10,
|
||||
"bed": -5
|
||||
}
|
||||
}
|
||||
|
||||
:json string command: The command to issue, either ``temp`` or ``offset``
|
||||
:json object temps: ``temp`` command: The target temperatures to set. Valid properties are ``hotend`` and ``bed``
|
||||
:json object offsets: ``offset`` command: The offset temperature to set. Valid properties are ``hotend`` and ``bed``
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If ``temps`` or ``offsets`` contains a property other than ``hotend`` or ``bed``, the
|
||||
target or offset temperature is not a valid number or outside of the supported range, or if the
|
||||
request is otherwise invalid.
|
||||
:statuscode 409: If the printer is not operational.
|
||||
|
||||
.. _sec-api-printer-feedercommand:
|
||||
|
||||
Issue a feeder command
|
||||
======================
|
||||
|
||||
.. http:post:: /api/printer/feeder
|
||||
|
||||
Feeder commands allow extrusion/extraction of filament. Available commands are:
|
||||
|
||||
extrude
|
||||
Extrudes the given amount of filament. Additional parameters:
|
||||
|
||||
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
|
||||
|
||||
All of these commands may only be sent if the printer is currently operational and not printing. Otherwise a
|
||||
:http:statuscode:`409` is returned.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
**Example Extrude Request**
|
||||
|
||||
Extrudes 1mm of filament
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/feeder HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "extrude",
|
||||
"amount": 1
|
||||
}
|
||||
|
||||
**Example Retract Request**
|
||||
|
||||
Retracts 3mm of filament
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/feeder HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "extrude",
|
||||
"amount": -3
|
||||
}
|
||||
|
||||
:json string command: The command to issue, only ``extrude`` is supported right now.
|
||||
:json number amount: ``extrude`` command: The amount of filament to extrude/retract in mm.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If the value given for `amount` is not a valid number or the request is otherwise invalid.
|
||||
:statuscode 409: If the printer is not operational or currently printing.
|
||||
|
||||
.. _sec-api-printer-sdcommand:
|
||||
|
||||
Issue a SD command
|
||||
==================
|
||||
|
||||
.. http:post:: /api/printer/sd
|
||||
|
||||
SD commands allow initialization, refresh and release of the printer's SD card (if available).
|
||||
|
||||
Available commands are:
|
||||
|
||||
init
|
||||
Initializes the printer's SD card, making it available for use. This also includes an initial retrieval of the
|
||||
list of files currently stored on the SD card, so after issueing that command a :ref:`retrieval of the files
|
||||
on SD card <sec-api-fileops-retrievelocation>` will return a successful result.
|
||||
|
||||
.. note::
|
||||
If OctoPrint detects the availability of a SD card on the printer during connection, it will automatically attempt
|
||||
to initialize it.
|
||||
|
||||
refresh
|
||||
Refreshes the list of files stored on the printer's SD card. Will return a :http:statuscode:`409` if the card
|
||||
has not been initialized yet (see the ``init`` command and :ref:`SD state <sec-api-printer-sdstate>`).
|
||||
|
||||
release
|
||||
Releases the SD card from the printer. The reverse operation to ``init``. After issuing this command, the SD
|
||||
card won't be available anymore, hence and operations targeting files stored on it will fail. Will return a :http:statuscode:`409`
|
||||
if the card has not been initialized yet (see the ``init`` command and :ref:`SD state <sec-api-printer-sdstate>`).
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
**Example Init Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/sd HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "init"
|
||||
}
|
||||
|
||||
**Example Refresh Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/sd HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "refresh"
|
||||
}
|
||||
|
||||
**Example Release Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/sd HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "release"
|
||||
}
|
||||
|
||||
:json string command: The command to issue, either ``init``, ``refresh`` or ``release``.
|
||||
:statuscode 204: No error
|
||||
:statuscode 409: If a ``refresh`` or ``release`` command is issued but the SD card has not been initialized (e.g.
|
||||
via ``init``.
|
||||
|
||||
.. _sec-api-printer-sdstate:
|
||||
|
||||
Retrieve the current SD state
|
||||
=============================
|
||||
|
||||
.. http:get:: /api/printer/sd
|
||||
|
||||
Retrieves the current state of the printer's SD card. For this request no authentication is needed.
|
||||
|
||||
If SD support has been disabled in OctoPrint's settings, a :http:statuscode:`404` is returned.
|
||||
|
||||
Returns a :http:statuscode:`200` with an :ref:`SD State Response <sec-api-printer-datamodel-sdstate>` in the body
|
||||
upon success.
|
||||
|
||||
**Example Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/printer/sd HTTP/1.1
|
||||
Host: example.com
|
||||
|
||||
**Example Response**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"ready": true
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If SD support has been disabled in OctoPrint's config.
|
||||
|
||||
.. _sec-api-printer-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-printer-datamodel-sdstate:
|
||||
|
||||
SD State Response
|
||||
-----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``ready``
|
||||
- 1
|
||||
- Boolean
|
||||
- Whether the SD card has been initialized (``true``) or not (``false``).
|
||||
@@ -0,0 +1,32 @@
|
||||
.. _sec-api-version:
|
||||
|
||||
*******************
|
||||
Version information
|
||||
*******************
|
||||
|
||||
.. http:get:: /api/version
|
||||
|
||||
Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing
|
||||
the API version, ``server`` containing the server version.
|
||||
|
||||
**Example Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/version HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
**Example Response**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"api": "0.1",
|
||||
"server": "1.1.0"
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
@@ -0,0 +1,262 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# OctoPrint documentation build configuration file, created by
|
||||
# sphinx-quickstart on Mon Dec 02 17:08:50 2013.
|
||||
#
|
||||
# This file is execfile()d with the current directory set to its containing dir.
|
||||
#
|
||||
# Note that not all possible configuration values are present in this
|
||||
# autogenerated file.
|
||||
#
|
||||
# All configuration values have a default; values that are commented out
|
||||
# serve to show the default.
|
||||
|
||||
import sys, os
|
||||
import octoprint._version
|
||||
from datetime import date
|
||||
|
||||
year_since = 2013
|
||||
year_current = date.today().year
|
||||
|
||||
# If extensions (or modules to document with autodoc) are in another directory,
|
||||
# add these directories to sys.path here. If the directory is relative to the
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
#sys.path.insert(0, os.path.abspath('.'))
|
||||
|
||||
# -- General configuration -----------------------------------------------------
|
||||
|
||||
# If your documentation needs a minimal Sphinx version, state it here.
|
||||
#needs_sphinx = '1.0'
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||
extensions = ['sphinx.ext.todo', 'sphinxcontrib.httpdomain']
|
||||
todo_include_todos = True
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['_templates']
|
||||
|
||||
# The suffix of source filenames.
|
||||
source_suffix = '.rst'
|
||||
|
||||
# The encoding of source files.
|
||||
#source_encoding = 'utf-8-sig'
|
||||
|
||||
# The master toctree document.
|
||||
master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'OctoPrint'
|
||||
copyright = u'%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else u'%d, Gina Häußge' % year_since
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = octoprint._version.get_versions()["version"]
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = version
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
#language = None
|
||||
|
||||
# There are two options for replacing |today|: either, you set today to some
|
||||
# non-false value, then it is used:
|
||||
#today = ''
|
||||
# Else, today_fmt is used as the format for a strftime call.
|
||||
#today_fmt = '%B %d, %Y'
|
||||
|
||||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
exclude_patterns = ['_build']
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all documents.
|
||||
#default_role = None
|
||||
|
||||
# If true, '()' will be appended to :func: etc. cross-reference text.
|
||||
#add_function_parentheses = True
|
||||
|
||||
# If true, the current module name will be prepended to all description
|
||||
# unit titles (such as .. function::).
|
||||
#add_module_names = True
|
||||
|
||||
# If true, sectionauthor and moduleauthor directives will be shown in the
|
||||
# output. They are ignored by default.
|
||||
#show_authors = False
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = 'sphinx'
|
||||
|
||||
# A list of ignored prefixes for module index sorting.
|
||||
#modindex_common_prefix = []
|
||||
|
||||
# If true, keep warnings as "system message" paragraphs in the built documents.
|
||||
#keep_warnings = False
|
||||
|
||||
|
||||
# -- Options for HTML output ---------------------------------------------------
|
||||
|
||||
# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org
|
||||
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
|
||||
|
||||
if not on_rtd: # only import and set the theme if we're building docs locally
|
||||
import sphinx_rtd_theme
|
||||
html_theme = 'sphinx_rtd_theme'
|
||||
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
#html_theme = "sphinx_rtd_theme"
|
||||
|
||||
# Theme options are theme-specific and customize the look and feel of a theme
|
||||
# further. For a list of options available for each theme, see the
|
||||
# documentation.
|
||||
#html_theme_options = {}
|
||||
|
||||
# Add any paths that contain custom themes here, relative to this directory.
|
||||
#html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
|
||||
|
||||
# The name for this set of Sphinx documents. If None, it defaults to
|
||||
# "<project> v<release> documentation".
|
||||
#html_title = None
|
||||
|
||||
# A shorter title for the navigation bar. Default is the same as html_title.
|
||||
#html_short_title = None
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top
|
||||
# of the sidebar.
|
||||
#html_logo = None
|
||||
|
||||
# The name of an image file (within the static path) to use as favicon of the
|
||||
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
|
||||
# pixels large.
|
||||
#html_favicon = None
|
||||
|
||||
# Add any paths that contain custom static files (such as style sheets) here,
|
||||
# relative to this directory. They are copied after the builtin static files,
|
||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||
html_static_path = ['_static']
|
||||
|
||||
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
||||
# using the given strftime format.
|
||||
#html_last_updated_fmt = '%b %d, %Y'
|
||||
|
||||
# If true, SmartyPants will be used to convert quotes and dashes to
|
||||
# typographically correct entities.
|
||||
#html_use_smartypants = True
|
||||
|
||||
# Custom sidebar templates, maps document names to template names.
|
||||
#html_sidebars = {}
|
||||
|
||||
# Additional templates that should be rendered to pages, maps page names to
|
||||
# template names.
|
||||
#html_additional_pages = {}
|
||||
|
||||
# If false, no module index is generated.
|
||||
#html_domain_indices = True
|
||||
|
||||
# If false, no index is generated.
|
||||
#html_use_index = True
|
||||
|
||||
# If true, the index is split into individual pages for each letter.
|
||||
#html_split_index = False
|
||||
|
||||
# If true, links to the reST sources are added to the pages.
|
||||
#html_show_sourcelink = True
|
||||
|
||||
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
|
||||
#html_show_sphinx = True
|
||||
|
||||
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
|
||||
#html_show_copyright = True
|
||||
|
||||
# If true, an OpenSearch description file will be output, and all pages will
|
||||
# contain a <link> tag referring to it. The value of this option must be the
|
||||
# base URL from which the finished HTML is served.
|
||||
#html_use_opensearch = ''
|
||||
|
||||
# This is the file name suffix for HTML files (e.g. ".xhtml").
|
||||
#html_file_suffix = None
|
||||
|
||||
# Output file base name for HTML help builder.
|
||||
htmlhelp_basename = 'OctoPrintdoc'
|
||||
|
||||
|
||||
# -- Options for LaTeX output --------------------------------------------------
|
||||
|
||||
latex_elements = {
|
||||
# The paper size ('letterpaper' or 'a4paper').
|
||||
#'papersize': 'letterpaper',
|
||||
|
||||
# The font size ('10pt', '11pt' or '12pt').
|
||||
#'pointsize': '10pt',
|
||||
|
||||
# Additional stuff for the LaTeX preamble.
|
||||
#'preamble': '',
|
||||
}
|
||||
|
||||
# Grouping the document tree into LaTeX files. List of tuples
|
||||
# (source start file, target name, title, author, documentclass [howto/manual]).
|
||||
latex_documents = [
|
||||
('index', 'OctoPrint.tex', u'OctoPrint Documentation',
|
||||
u'Gina Häußge', 'manual'),
|
||||
]
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top of
|
||||
# the title page.
|
||||
#latex_logo = None
|
||||
|
||||
# For "manual" documents, if this is true, then toplevel headings are parts,
|
||||
# not chapters.
|
||||
#latex_use_parts = False
|
||||
|
||||
# If true, show page references after internal links.
|
||||
#latex_show_pagerefs = False
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#latex_show_urls = False
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#latex_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#latex_domain_indices = True
|
||||
|
||||
|
||||
# -- Options for manual page output --------------------------------------------
|
||||
|
||||
# One entry per manual page. List of tuples
|
||||
# (source start file, name, description, authors, manual section).
|
||||
man_pages = [
|
||||
('index', 'octoprint', u'OctoPrint Documentation',
|
||||
[u'Gina Häußge'], 1)
|
||||
]
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#man_show_urls = False
|
||||
|
||||
|
||||
# -- Options for Texinfo output ------------------------------------------------
|
||||
|
||||
# Grouping the document tree into Texinfo files. List of tuples
|
||||
# (source start file, target name, title, author,
|
||||
# dir menu entry, description, category)
|
||||
texinfo_documents = [
|
||||
('index', 'OctoPrint', u'OctoPrint Documentation',
|
||||
u'Gina Häußge', 'OctoPrint', 'One line description of project.',
|
||||
'Miscellaneous'),
|
||||
]
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#texinfo_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#texinfo_domain_indices = True
|
||||
|
||||
# How to display URL addresses: 'footnote', 'no', or 'inline'.
|
||||
#texinfo_show_urls = 'footnote'
|
||||
|
||||
# If true, do not generate a @detailmenu in the "Top" node's menu.
|
||||
#texinfo_no_detailmenu = False
|
||||
@@ -0,0 +1,341 @@
|
||||
.. _sec-events:
|
||||
|
||||
####################
|
||||
Events Documentation
|
||||
####################
|
||||
|
||||
.. contents::
|
||||
|
||||
With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events.
|
||||
Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to
|
||||
accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer
|
||||
separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed
|
||||
to indicate what to do with the command contained.
|
||||
|
||||
.. _sec-events-configuration:
|
||||
|
||||
Configuration
|
||||
=============
|
||||
|
||||
Event hooks are configured via OctoPrint's configuration file ``config.yaml``. There they are contained in a
|
||||
``subscriptions`` list located directly under the ``events`` node. The ``command`` node accepts either a single string
|
||||
or a list of strings so that multiple commands can be executed in one go. Each hook carries an additional node type that
|
||||
must be either ``gcode`` (for GCODE commands to be sent to the printer based on the event) or ``system`` (for commands to be
|
||||
executed on the system OctoPrint is running on).
|
||||
|
||||
All event hooks can be disabled completely by setting ``event > enabled`` to ``false``. You can also disable individual
|
||||
hooks by setting the (optional) node ``enabled`` to false, see the example below.
|
||||
|
||||
Example
|
||||
-------
|
||||
|
||||
.. sourcecode:: yaml
|
||||
|
||||
events:
|
||||
enabled: True
|
||||
subscriptions:
|
||||
- event: Disconnected
|
||||
command: python ~/growl.py -t mygrowlserver -d "Lost connection to printer" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
enabled: false
|
||||
- event: PrintStarted
|
||||
command: python ~/growl.py -t mygrowlserver -d "Starting {file}" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
- event: PrintDone
|
||||
command: python ~/growl.py -t mygrowlserver -d "Completed {file}" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
- event: Connected
|
||||
command:
|
||||
- M115
|
||||
- M117 printer connected!
|
||||
- G28
|
||||
type: gcode
|
||||
|
||||
.. _sec-events-placeholders:
|
||||
|
||||
Placeholders
|
||||
============
|
||||
|
||||
You can use the following generic placeholders in your events:
|
||||
|
||||
* ``{__currentZ}``: the current Z position of the head if known, -1 if not available
|
||||
* ``{__filename}``: filename of the currently selected file, "NO FILE" if not available
|
||||
* ``{__progress}``: the progress of the print in percent, 0 if not available
|
||||
* ``{__data}``: a string representation of the payload
|
||||
* ``{__now}``: the date and time of the event in ISO 8601
|
||||
|
||||
Additionally, all data from the payload can be accessed by its key. Example: If the payload happens to be defined
|
||||
something like this:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
then you'll be able to access the filename via the placeholder ``{file}`` and the origin via the placeholder ``{origin}``.
|
||||
|
||||
|
||||
.. _sec-events-available_events:
|
||||
|
||||
Available Events
|
||||
================
|
||||
|
||||
Server
|
||||
------
|
||||
|
||||
Startup
|
||||
The server has started
|
||||
|
||||
ClientOpened
|
||||
A client has connected to the web server.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that connected
|
||||
|
||||
**Note:** Name changed in version 1.1.0
|
||||
|
||||
ClientClosed
|
||||
A client has disconnected from the webserver
|
||||
|
||||
Printer communication
|
||||
---------------------
|
||||
|
||||
Connected
|
||||
The server has connected to the printer.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``port``: the connected serial port
|
||||
* ``baudrate``: the baud rate
|
||||
|
||||
Disconnected
|
||||
The server has disconnected from the printer
|
||||
|
||||
Error
|
||||
An error has occurred in the printer communication.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``error``: the error string
|
||||
|
||||
File handling
|
||||
-------------
|
||||
|
||||
Upload
|
||||
A file has been uploaded.
|
||||
|
||||
Payload:
|
||||
* ``file``: the file's name
|
||||
* ``target``: the target to which the file was uploaded, either ``local`` or ``sdcard``
|
||||
|
||||
UpdatedFiles
|
||||
A file list was modified.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``type``: the type of file list that was modified, currently only ``gcode`` is supported here
|
||||
|
||||
MetadataAnalysisStarted
|
||||
The metadata analysis of a GCODE file has started.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
|
||||
MetadataAnalaysisFinished
|
||||
The metadata analysis of a GCODE file has finished.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``result``: the analysis result -- this is a python object currently only available for internal use
|
||||
|
||||
FileSelected
|
||||
A GCODE file has been selected for printing.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
FileDeselected
|
||||
No file is selected any more for printing.
|
||||
|
||||
TransferStarted
|
||||
A GCODE file transfer to SD has started.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``local``: the file's name as stored locally
|
||||
* ``remote``: the file's name as stored on SD
|
||||
|
||||
**Note:** Name changed in version 1.1.0
|
||||
|
||||
TransferDone
|
||||
A GCODE file transfer to SD has finished.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``time``: the time it took for the transfer to complete in seconds
|
||||
* ``local``: the file's name as stored locally
|
||||
* ``remote``: the file's name as stored on SD
|
||||
|
||||
Printing
|
||||
--------
|
||||
|
||||
PrintStarted
|
||||
A print has started.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
PrintFailed
|
||||
A print failed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
PrintDone
|
||||
A print completed successfully.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
* ``time``: the time needed for the print, in seconds (float)
|
||||
|
||||
PrintCancelled
|
||||
The print has been cancelled via the cancel button.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
PrintPaused
|
||||
The print has been paused.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
PrintResumed
|
||||
The print has been resumed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
GCODE processing
|
||||
----------------
|
||||
|
||||
PowerOn
|
||||
The GCode has turned on the printer power via M80
|
||||
|
||||
PowerOff
|
||||
The GCODE has turned on the printer power via M81
|
||||
|
||||
Home
|
||||
The head has gone home via G28
|
||||
|
||||
ZChange
|
||||
The printer's Z-Height has changed (new layer)
|
||||
|
||||
Paused
|
||||
The print has been paused
|
||||
|
||||
Waiting
|
||||
The print is paused due to a gcode wait command
|
||||
|
||||
Cooling
|
||||
The GCODE has enabled the platform cooler via M245
|
||||
|
||||
Alert
|
||||
The GCODE has issued a user alert (beep) via M300
|
||||
|
||||
Conveyor
|
||||
The GCODE has enabled the conveyor belt via M240
|
||||
|
||||
Eject
|
||||
The GCODE has enabled the part ejector via M40
|
||||
|
||||
EStop
|
||||
The GCODE has issued a panic stop via M112
|
||||
|
||||
Timelapses
|
||||
----------
|
||||
|
||||
CaptureStart
|
||||
A timelapse image has started to be captured.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the name of the image file to be saved
|
||||
|
||||
CaptureDone
|
||||
A timelapse image has completed being captured.
|
||||
|
||||
Payload:
|
||||
* ``file``: the name of the image file that was saved
|
||||
|
||||
MovieRendering
|
||||
The timelapse movie has started rendering.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``gcode``: the GCODE file for which the timelapse would have been created (only the filename without the path)
|
||||
* ``movie``: the movie file that is being created (full path)
|
||||
* ``movie_basename``: the movie file that is being created (only the file name without the path)
|
||||
|
||||
MovieDone
|
||||
The timelapse movie is completed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``gcode``: the GCODE file for which the timelapse would have been created (only the filename without the path)
|
||||
* ``movie``: the movie file that has been created (full path)
|
||||
* ``movie_basename``: the movie file that has been created (only the file name without the path)
|
||||
|
||||
MovieFailed
|
||||
There was an error while rendering the timelapse movie.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``gcode``: the GCODE file for which the timelapse would have been created (only the filename without the path)
|
||||
* ``movie``: the movie file that would have been created (full path)
|
||||
* ``movie_basename``: the movie file that would have been created (only the file name without the path)
|
||||
* ``returncode``: the return code of ``ffmpeg`` that indicates the error that occurred
|
||||
|
||||
Slicing
|
||||
-------
|
||||
|
||||
SlicingStarted
|
||||
The slicing of a file has started.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``stl``: the STL's filename
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
|
||||
SlicingDone
|
||||
The slicing of a file has completed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``stl``: the STL's filename
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
* ``time``: the time needed for slicing, in seconds (float)
|
||||
|
||||
SlicingFailed
|
||||
The slicing of a file has failed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``stl``: the STL's filename
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
* ``reason``: the reason for the slicing having failed
|
||||
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,26 @@
|
||||
.. OctoPrint documentation master file, created by
|
||||
sphinx-quickstart on Mon Dec 02 17:08:50 2013.
|
||||
You can adapt this file completely to your liking, but it should at least
|
||||
contain the root `toctree` directive.
|
||||
|
||||
#####################################
|
||||
Welcome to OctoPrint's documentation!
|
||||
#####################################
|
||||
|
||||
.. image:: images/octoprint-logo.png
|
||||
:alt: The OctoPrint Logo
|
||||
:align: right
|
||||
|
||||
This is a work in progress. The goal is to document OctoPrint's REST API, event system, configuration etc in way that
|
||||
allows different documentation per development branch in Git, which so far did not scale well with the Github-Wiki-based
|
||||
approach.
|
||||
|
||||
Contents
|
||||
========
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
api/index.rst
|
||||
events/index.rst
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
@ECHO OFF
|
||||
|
||||
REM Command file for Sphinx documentation
|
||||
|
||||
if "%SPHINXBUILD%" == "" (
|
||||
set SPHINXBUILD=sphinx-build
|
||||
)
|
||||
set BUILDDIR=_build
|
||||
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
|
||||
set I18NSPHINXOPTS=%SPHINXOPTS% .
|
||||
if NOT "%PAPER%" == "" (
|
||||
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
|
||||
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
|
||||
)
|
||||
|
||||
if "%1" == "" goto help
|
||||
|
||||
if "%1" == "help" (
|
||||
:help
|
||||
echo.Please use `make ^<target^>` where ^<target^> is one of
|
||||
echo. html to make standalone HTML files
|
||||
echo. dirhtml to make HTML files named index.html in directories
|
||||
echo. singlehtml to make a single large HTML file
|
||||
echo. pickle to make pickle files
|
||||
echo. json to make JSON files
|
||||
echo. htmlhelp to make HTML files and a HTML help project
|
||||
echo. qthelp to make HTML files and a qthelp project
|
||||
echo. devhelp to make HTML files and a Devhelp project
|
||||
echo. epub to make an epub
|
||||
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
|
||||
echo. text to make text files
|
||||
echo. man to make manual pages
|
||||
echo. texinfo to make Texinfo files
|
||||
echo. gettext to make PO message catalogs
|
||||
echo. changes to make an overview over all changed/added/deprecated items
|
||||
echo. xml to make Docutils-native XML files
|
||||
echo. pseudoxml to make pseudoxml-XML files for display purposes
|
||||
echo. linkcheck to check all external links for integrity
|
||||
echo. doctest to run all doctests embedded in the documentation if enabled
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "clean" (
|
||||
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
|
||||
del /q /s %BUILDDIR%\*
|
||||
goto end
|
||||
)
|
||||
|
||||
|
||||
%SPHINXBUILD% 2> nul
|
||||
if errorlevel 9009 (
|
||||
echo.
|
||||
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
|
||||
echo.installed, then set the SPHINXBUILD environment variable to point
|
||||
echo.to the full path of the 'sphinx-build' executable. Alternatively you
|
||||
echo.may add the Sphinx directory to PATH.
|
||||
echo.
|
||||
echo.If you don't have Sphinx installed, grab it from
|
||||
echo.http://sphinx-doc.org/
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
if "%1" == "html" (
|
||||
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "dirhtml" (
|
||||
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "singlehtml" (
|
||||
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "pickle" (
|
||||
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can process the pickle files.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "json" (
|
||||
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can process the JSON files.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "htmlhelp" (
|
||||
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can run HTML Help Workshop with the ^
|
||||
.hhp project file in %BUILDDIR%/htmlhelp.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "qthelp" (
|
||||
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can run "qcollectiongenerator" with the ^
|
||||
.qhcp project file in %BUILDDIR%/qthelp, like this:
|
||||
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\OctoPrint.qhcp
|
||||
echo.To view the help file:
|
||||
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\OctoPrint.ghc
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "devhelp" (
|
||||
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "epub" (
|
||||
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The epub file is in %BUILDDIR%/epub.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "latex" (
|
||||
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "latexpdf" (
|
||||
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
|
||||
cd %BUILDDIR%/latex
|
||||
make all-pdf
|
||||
cd %BUILDDIR%/..
|
||||
echo.
|
||||
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "latexpdfja" (
|
||||
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
|
||||
cd %BUILDDIR%/latex
|
||||
make all-pdf-ja
|
||||
cd %BUILDDIR%/..
|
||||
echo.
|
||||
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "text" (
|
||||
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The text files are in %BUILDDIR%/text.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "man" (
|
||||
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The manual pages are in %BUILDDIR%/man.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "texinfo" (
|
||||
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "gettext" (
|
||||
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "changes" (
|
||||
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.The overview file is in %BUILDDIR%/changes.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "linkcheck" (
|
||||
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Link check complete; look for any errors in the above output ^
|
||||
or in %BUILDDIR%/linkcheck/output.txt.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "doctest" (
|
||||
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Testing of doctests in the sources finished, look at the ^
|
||||
results in %BUILDDIR%/doctest/output.txt.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "xml" (
|
||||
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The XML files are in %BUILDDIR%/xml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "pseudoxml" (
|
||||
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
|
||||
goto end
|
||||
)
|
||||
|
||||
:end
|
||||
@@ -0,0 +1,2 @@
|
||||
sphinxcontrib-httpdomain
|
||||
sphinx_rtd_theme
|
||||
@@ -1,49 +0,0 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# Copy this script to /etc/init.d/octoprint and adjust the variables
|
||||
# at the top to match your installation (should be okay for a Raspian
|
||||
# setup). Then link it to the correct run levels. On Debian/Rasbian
|
||||
# just call 'sudo update-rc.d octoprint defaults'
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: octoprint
|
||||
# Required-Start: $local_fs networking
|
||||
# Required-Stop:
|
||||
# Should-Start:
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: Run octoprint
|
||||
# Description: Octoprint provides a responsive web interface for
|
||||
# controlling a 3D printer
|
||||
### END INIT INFO
|
||||
|
||||
|
||||
# OctoPrint's run script
|
||||
DAEMON=/home/pi/OctoPrint/run
|
||||
|
||||
# Port to use
|
||||
PORT=5000
|
||||
|
||||
# Run as this user
|
||||
RUNAS=pi
|
||||
|
||||
# Exit if the run script is not found
|
||||
[ -x "$DAEMON" ] || exit 0
|
||||
|
||||
|
||||
case "$1" in
|
||||
start)
|
||||
su $RUNAS -c "$DAEMON --port=$PORT --daemon start"
|
||||
;;
|
||||
stop)
|
||||
su $RUNAS -c "$DAEMON --port=$PORT --daemon stop"
|
||||
;;
|
||||
restart)
|
||||
su $RUNAS -c "$DAEMON --port=$PORT --daemon restart"
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $0 {start|stop|restart}" >&2
|
||||
;;
|
||||
esac
|
||||
|
||||
:
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
|
Before Width: | Height: | Size: 890 B |
|
Before Width: | Height: | Size: 251 B |
|
Before Width: | Height: | Size: 212 B |
|
Before Width: | Height: | Size: 119 B |
|
Before Width: | Height: | Size: 131 B |
|
Before Width: | Height: | Size: 124 B |
|
Before Width: | Height: | Size: 103 B |
|
Before Width: | Height: | Size: 118 B |
|
Before Width: | Height: | Size: 104 B |
|
Before Width: | Height: | Size: 119 B |
|
Before Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 112 B |
@@ -1,458 +0,0 @@
|
||||
/*! jQuery UI - v1.9.0 - 2012-10-21
|
||||
* http://jqueryui.com
|
||||
* Includes: jquery.ui.core.css, jquery.ui.resizable.css, jquery.ui.selectable.css, jquery.ui.accordion.css, jquery.ui.autocomplete.css, jquery.ui.button.css, jquery.ui.datepicker.css, jquery.ui.dialog.css, jquery.ui.menu.css, jquery.ui.progressbar.css, jquery.ui.slider.css, jquery.ui.spinner.css, jquery.ui.tabs.css, jquery.ui.tooltip.css
|
||||
* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Lucida%20Grande%2CLucida%20Sans%2CArial%2Csans-serif&fwDefault=bold&fsDefault=1.1em&cornerRadius=6px&bgColorHeader=deedf7&bgTextureHeader=03_highlight_soft.png&bgImgOpacityHeader=100&borderColorHeader=aed0ea&fcHeader=222222&iconColorHeader=72a7cf&bgColorContent=f2f5f7&bgTextureContent=04_highlight_hard.png&bgImgOpacityContent=100&borderColorContent=dddddd&fcContent=362b36&iconColorContent=72a7cf&bgColorDefault=d7ebf9&bgTextureDefault=02_glass.png&bgImgOpacityDefault=80&borderColorDefault=aed0ea&fcDefault=2779aa&iconColorDefault=3d80b3&bgColorHover=e4f1fb&bgTextureHover=02_glass.png&bgImgOpacityHover=100&borderColorHover=74b2e2&fcHover=0070a3&iconColorHover=2694e8&bgColorActive=3baae3&bgTextureActive=02_glass.png&bgImgOpacityActive=50&borderColorActive=2694e8&fcActive=ffffff&iconColorActive=ffffff&bgColorHighlight=ffef8f&bgTextureHighlight=03_highlight_soft.png&bgImgOpacityHighlight=25&borderColorHighlight=f9dd34&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=cd0a0a&bgTextureError=01_flat.png&bgImgOpacityError=15&borderColorError=cd0a0a&fcError=ffffff&iconColorError=ffffff&bgColorOverlay=eeeeee&bgTextureOverlay=08_diagonals_thick.png&bgImgOpacityOverlay=90&opacityOverlay=80&bgColorShadow=000000&bgTextureShadow=04_highlight_hard.png&bgImgOpacityShadow=70&opacityShadow=30&thicknessShadow=7px&offsetTopShadow=-7px&offsetLeftShadow=-7px&cornerRadiusShadow=8px
|
||||
* Copyright (c) 2012 jQuery Foundation and other contributors Licensed MIT */
|
||||
|
||||
/* Layout helpers
|
||||
----------------------------------*/
|
||||
.ui-helper-hidden { display: none; }
|
||||
.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); }
|
||||
.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
|
||||
.ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; }
|
||||
.ui-helper-clearfix:after { clear: both; }
|
||||
.ui-helper-clearfix { zoom: 1; }
|
||||
.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }
|
||||
|
||||
|
||||
/* Interaction Cues
|
||||
----------------------------------*/
|
||||
.ui-state-disabled { cursor: default !important; }
|
||||
|
||||
|
||||
/* Icons
|
||||
----------------------------------*/
|
||||
|
||||
/* states and images */
|
||||
.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
|
||||
|
||||
|
||||
/* Misc visuals
|
||||
----------------------------------*/
|
||||
|
||||
/* Overlays */
|
||||
.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
|
||||
.ui-resizable { position: relative;}
|
||||
.ui-resizable-handle { position: absolute;font-size: 0.1px; display: block; }
|
||||
.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; }
|
||||
.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; }
|
||||
.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; }
|
||||
.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; }
|
||||
.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; }
|
||||
.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; }
|
||||
.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; }
|
||||
.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; }
|
||||
.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; }
|
||||
.ui-accordion .ui-accordion-header { display: block; cursor: pointer; position: relative; margin-top: 2px; padding: .5em .5em .5em .7em; zoom: 1; }
|
||||
.ui-accordion .ui-accordion-icons { padding-left: 2.2em; }
|
||||
.ui-accordion .ui-accordion-noicons { padding-left: .7em; }
|
||||
.ui-accordion .ui-accordion-icons .ui-accordion-icons { padding-left: 2.2em; }
|
||||
.ui-accordion .ui-accordion-header .ui-accordion-header-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; }
|
||||
.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; overflow: auto; zoom: 1; }
|
||||
.ui-autocomplete { position: absolute; cursor: default; }
|
||||
|
||||
/* workarounds */
|
||||
* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */
|
||||
.ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; cursor: pointer; text-align: center; zoom: 1; overflow: visible; } /* the overflow property removes extra width in IE */
|
||||
.ui-button, .ui-button:link, .ui-button:visited, .ui-button:hover, .ui-button:active { text-decoration: none; }
|
||||
.ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */
|
||||
button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */
|
||||
.ui-button-icons-only { width: 3.4em; }
|
||||
button.ui-button-icons-only { width: 3.7em; }
|
||||
|
||||
/*button text element */
|
||||
.ui-button .ui-button-text { display: block; line-height: 1.4; }
|
||||
.ui-button-text-only .ui-button-text { padding: .4em 1em; }
|
||||
.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; }
|
||||
.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; }
|
||||
.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; }
|
||||
.ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; }
|
||||
/* no icon support for input elements, provide padding by default */
|
||||
input.ui-button { padding: .4em 1em; }
|
||||
|
||||
/*button icon element(s) */
|
||||
.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; }
|
||||
.ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; }
|
||||
.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; }
|
||||
.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; }
|
||||
.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; }
|
||||
|
||||
/*button sets*/
|
||||
.ui-buttonset { margin-right: 7px; }
|
||||
.ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; }
|
||||
|
||||
/* workarounds */
|
||||
button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */
|
||||
.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; }
|
||||
.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; }
|
||||
.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; }
|
||||
.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; }
|
||||
.ui-datepicker .ui-datepicker-prev { left:2px; }
|
||||
.ui-datepicker .ui-datepicker-next { right:2px; }
|
||||
.ui-datepicker .ui-datepicker-prev-hover { left:1px; }
|
||||
.ui-datepicker .ui-datepicker-next-hover { right:1px; }
|
||||
.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; }
|
||||
.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
|
||||
.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; }
|
||||
.ui-datepicker select.ui-datepicker-month-year {width: 100%;}
|
||||
.ui-datepicker select.ui-datepicker-month,
|
||||
.ui-datepicker select.ui-datepicker-year { width: 49%;}
|
||||
.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; }
|
||||
.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; }
|
||||
.ui-datepicker td { border: 0; padding: 1px; }
|
||||
.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; }
|
||||
.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; }
|
||||
.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; }
|
||||
.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; }
|
||||
|
||||
/* with multiple calendars */
|
||||
.ui-datepicker.ui-datepicker-multi { width:auto; }
|
||||
.ui-datepicker-multi .ui-datepicker-group { float:left; }
|
||||
.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; }
|
||||
.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; }
|
||||
.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; }
|
||||
.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; }
|
||||
.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; }
|
||||
.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; }
|
||||
.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; }
|
||||
.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; }
|
||||
|
||||
/* RTL support */
|
||||
.ui-datepicker-rtl { direction: rtl; }
|
||||
.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; }
|
||||
.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; }
|
||||
.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; }
|
||||
.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; }
|
||||
.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; }
|
||||
.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; }
|
||||
.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; }
|
||||
.ui-datepicker-rtl .ui-datepicker-group { float:right; }
|
||||
.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
|
||||
.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
|
||||
|
||||
/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */
|
||||
.ui-datepicker-cover {
|
||||
position: absolute; /*must have*/
|
||||
z-index: -1; /*must have*/
|
||||
filter: mask(); /*must have*/
|
||||
top: -4px; /*must have*/
|
||||
left: -4px; /*must have*/
|
||||
width: 200px; /*must have*/
|
||||
height: 200px; /*must have*/
|
||||
}.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; }
|
||||
.ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative; }
|
||||
.ui-dialog .ui-dialog-title { float: left; margin: .1em 16px .1em 0; }
|
||||
.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; }
|
||||
.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; }
|
||||
.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; }
|
||||
.ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; }
|
||||
.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; }
|
||||
.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; }
|
||||
.ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; }
|
||||
.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; }
|
||||
.ui-draggable .ui-dialog-titlebar { cursor: move; }
|
||||
.ui-menu { list-style:none; padding: 2px; margin: 0; display:block; outline: none; }
|
||||
.ui-menu .ui-menu { margin-top: -3px; position: absolute; }
|
||||
.ui-menu .ui-menu-item { margin: 0; padding: 0; zoom: 1; width: 100%; }
|
||||
.ui-menu .ui-menu-divider { margin: 5px -2px 5px -2px; height: 0; font-size: 0; line-height: 0; border-width: 1px 0 0 0; }
|
||||
.ui-menu .ui-menu-item a { text-decoration: none; display: block; padding: 2px .4em; line-height: 1.5; zoom: 1; font-weight: normal; }
|
||||
.ui-menu .ui-menu-item a.ui-state-focus,
|
||||
.ui-menu .ui-menu-item a.ui-state-active { font-weight: normal; margin: -1px; }
|
||||
|
||||
.ui-menu .ui-state-disabled { font-weight: normal; margin: .4em 0 .2em; line-height: 1.5; }
|
||||
.ui-menu .ui-state-disabled a { cursor: default; }
|
||||
|
||||
/* icon support */
|
||||
.ui-menu-icons { position: relative; }
|
||||
.ui-menu-icons .ui-menu-item a { position: relative; padding-left: 2em; }
|
||||
|
||||
/* left-aligned */
|
||||
.ui-menu .ui-icon { position: absolute; top: .2em; left: .2em; }
|
||||
|
||||
/* right-aligned */
|
||||
.ui-menu .ui-menu-icon { position: static; float: right; }
|
||||
.ui-progressbar { height:2em; text-align: left; overflow: hidden; }
|
||||
.ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; }.ui-slider { position: relative; text-align: left; }
|
||||
.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; }
|
||||
.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; }
|
||||
|
||||
.ui-slider-horizontal { height: .8em; }
|
||||
.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; }
|
||||
.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; }
|
||||
.ui-slider-horizontal .ui-slider-range-min { left: 0; }
|
||||
.ui-slider-horizontal .ui-slider-range-max { right: 0; }
|
||||
|
||||
.ui-slider-vertical { width: .8em; height: 100px; }
|
||||
.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; }
|
||||
.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; }
|
||||
.ui-slider-vertical .ui-slider-range-min { bottom: 0; }
|
||||
.ui-slider-vertical .ui-slider-range-max { top: 0; }.ui-spinner { position:relative; display: inline-block; overflow: hidden; padding: 0; vertical-align: middle; }
|
||||
.ui-spinner-input { border: none; background: none; padding: 0; margin: .2em 0; vertical-align: middle; margin-left: .4em; margin-right: 22px; }
|
||||
.ui-spinner-button { width: 16px; height: 50%; font-size: .5em; padding: 0; margin: 0; z-index: 100; text-align: center; position: absolute; cursor: default; display: block; overflow: hidden; right: 0; }
|
||||
.ui-spinner a.ui-spinner-button { border-top: none; border-bottom: none; border-right: none; } /* more specificity required here to overide default borders */
|
||||
.ui-spinner .ui-icon { position: absolute; margin-top: -8px; top: 50%; left: 0; } /* vertical centre icon */
|
||||
.ui-spinner-up { top: 0; }
|
||||
.ui-spinner-down { bottom: 0; }
|
||||
|
||||
/* TR overrides */
|
||||
span.ui-spinner { background: none; }
|
||||
.ui-spinner .ui-icon-triangle-1-s {
|
||||
/* need to fix icons sprite */
|
||||
background-position:-65px -16px;
|
||||
}
|
||||
.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */
|
||||
.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; }
|
||||
.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 0; margin: 1px .2em 0 0; border-bottom: 0; padding: 0; white-space: nowrap; }
|
||||
.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; }
|
||||
.ui-tabs .ui-tabs-nav li.ui-tabs-active { margin-bottom: -1px; padding-bottom: 1px; }
|
||||
.ui-tabs .ui-tabs-nav li.ui-tabs-active a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-tabs-loading a { cursor: text; }
|
||||
.ui-tabs .ui-tabs-nav li a, .ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */
|
||||
.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; }
|
||||
.ui-tooltip {
|
||||
padding:8px;
|
||||
position:absolute;
|
||||
z-index:9999;
|
||||
-o-box-shadow: 0 0 5px #aaa;
|
||||
-moz-box-shadow: 0 0 5px #aaa;
|
||||
-webkit-box-shadow: 0 0 5px #aaa;
|
||||
box-shadow: 0 0 5px #aaa;
|
||||
}
|
||||
/* Fades and background-images don't work well together in IE6, drop the image */
|
||||
* html .ui-tooltip {
|
||||
background-image: none;
|
||||
}
|
||||
body .ui-tooltip { border-width:2px; }
|
||||
|
||||
/* Component containers
|
||||
----------------------------------*/
|
||||
.ui-widget { font-family: Lucida Grande,Lucida Sans,Arial,sans-serif; font-size: 1em; }
|
||||
.ui-widget .ui-widget { font-size: 1em; }
|
||||
.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Lucida Grande,Lucida Sans,Arial,sans-serif; font-size: 1em; }
|
||||
.ui-widget-content { border: 1px solid #dddddd; background: #f2f5f7 url(images/ui-bg_highlight-hard_100_f2f5f7_1x100.png) 50% top repeat-x; color: #362b36; }
|
||||
.ui-widget-content a { color: #362b36; }
|
||||
.ui-widget-header { border: 1px solid #aed0ea; background: #deedf7 url(images/ui-bg_highlight-soft_100_deedf7_1x100.png) 50% 50% repeat-x; color: #222222; font-weight: bold; }
|
||||
.ui-widget-header a { color: #222222; }
|
||||
|
||||
/* Interaction states
|
||||
----------------------------------*/
|
||||
.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #aed0ea; background: #d7ebf9 url(images/ui-bg_glass_80_d7ebf9_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #2779aa; }
|
||||
.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #2779aa; text-decoration: none; }
|
||||
.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #74b2e2; background: #e4f1fb url(images/ui-bg_glass_100_e4f1fb_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #0070a3; }
|
||||
.ui-state-hover a, .ui-state-hover a:hover { color: #0070a3; text-decoration: none; }
|
||||
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #2694e8; background: #3baae3 url(images/ui-bg_glass_50_3baae3_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #ffffff; }
|
||||
.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #ffffff; text-decoration: none; }
|
||||
|
||||
/* Interaction Cues
|
||||
----------------------------------*/
|
||||
.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #f9dd34; background: #ffef8f url(images/ui-bg_highlight-soft_25_ffef8f_1x100.png) 50% top repeat-x; color: #363636; }
|
||||
.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636; }
|
||||
.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #cd0a0a url(images/ui-bg_flat_15_cd0a0a_40x100.png) 50% 50% repeat-x; color: #ffffff; }
|
||||
.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #ffffff; }
|
||||
.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #ffffff; }
|
||||
.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; }
|
||||
.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
|
||||
.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }
|
||||
|
||||
/* Icons
|
||||
----------------------------------*/
|
||||
|
||||
/* states and images */
|
||||
.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_72a7cf_256x240.png); }
|
||||
.ui-widget-content .ui-icon {background-image: url(images/ui-icons_72a7cf_256x240.png); }
|
||||
.ui-widget-header .ui-icon {background-image: url(images/ui-icons_72a7cf_256x240.png); }
|
||||
.ui-state-default .ui-icon { background-image: url(images/ui-icons_3d80b3_256x240.png); }
|
||||
.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_2694e8_256x240.png); }
|
||||
.ui-state-active .ui-icon {background-image: url(images/ui-icons_ffffff_256x240.png); }
|
||||
.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_2e83ff_256x240.png); }
|
||||
.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_ffffff_256x240.png); }
|
||||
|
||||
/* positioning */
|
||||
.ui-icon-carat-1-n { background-position: 0 0; }
|
||||
.ui-icon-carat-1-ne { background-position: -16px 0; }
|
||||
.ui-icon-carat-1-e { background-position: -32px 0; }
|
||||
.ui-icon-carat-1-se { background-position: -48px 0; }
|
||||
.ui-icon-carat-1-s { background-position: -64px 0; }
|
||||
.ui-icon-carat-1-sw { background-position: -80px 0; }
|
||||
.ui-icon-carat-1-w { background-position: -96px 0; }
|
||||
.ui-icon-carat-1-nw { background-position: -112px 0; }
|
||||
.ui-icon-carat-2-n-s { background-position: -128px 0; }
|
||||
.ui-icon-carat-2-e-w { background-position: -144px 0; }
|
||||
.ui-icon-triangle-1-n { background-position: 0 -16px; }
|
||||
.ui-icon-triangle-1-ne { background-position: -16px -16px; }
|
||||
.ui-icon-triangle-1-e { background-position: -32px -16px; }
|
||||
.ui-icon-triangle-1-se { background-position: -48px -16px; }
|
||||
.ui-icon-triangle-1-s { background-position: -64px -16px; }
|
||||
.ui-icon-triangle-1-sw { background-position: -80px -16px; }
|
||||
.ui-icon-triangle-1-w { background-position: -96px -16px; }
|
||||
.ui-icon-triangle-1-nw { background-position: -112px -16px; }
|
||||
.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
|
||||
.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
|
||||
.ui-icon-arrow-1-n { background-position: 0 -32px; }
|
||||
.ui-icon-arrow-1-ne { background-position: -16px -32px; }
|
||||
.ui-icon-arrow-1-e { background-position: -32px -32px; }
|
||||
.ui-icon-arrow-1-se { background-position: -48px -32px; }
|
||||
.ui-icon-arrow-1-s { background-position: -64px -32px; }
|
||||
.ui-icon-arrow-1-sw { background-position: -80px -32px; }
|
||||
.ui-icon-arrow-1-w { background-position: -96px -32px; }
|
||||
.ui-icon-arrow-1-nw { background-position: -112px -32px; }
|
||||
.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
|
||||
.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
|
||||
.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
|
||||
.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
|
||||
.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
|
||||
.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
|
||||
.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
|
||||
.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
|
||||
.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
|
||||
.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
|
||||
.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
|
||||
.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
|
||||
.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
|
||||
.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
|
||||
.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
|
||||
.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
|
||||
.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
|
||||
.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
|
||||
.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
|
||||
.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
|
||||
.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
|
||||
.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
|
||||
.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
|
||||
.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
|
||||
.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
|
||||
.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
|
||||
.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
|
||||
.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
|
||||
.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
|
||||
.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
|
||||
.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
|
||||
.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
|
||||
.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
|
||||
.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
|
||||
.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
|
||||
.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
|
||||
.ui-icon-arrow-4 { background-position: 0 -80px; }
|
||||
.ui-icon-arrow-4-diag { background-position: -16px -80px; }
|
||||
.ui-icon-extlink { background-position: -32px -80px; }
|
||||
.ui-icon-newwin { background-position: -48px -80px; }
|
||||
.ui-icon-refresh { background-position: -64px -80px; }
|
||||
.ui-icon-shuffle { background-position: -80px -80px; }
|
||||
.ui-icon-transfer-e-w { background-position: -96px -80px; }
|
||||
.ui-icon-transferthick-e-w { background-position: -112px -80px; }
|
||||
.ui-icon-folder-collapsed { background-position: 0 -96px; }
|
||||
.ui-icon-folder-open { background-position: -16px -96px; }
|
||||
.ui-icon-document { background-position: -32px -96px; }
|
||||
.ui-icon-document-b { background-position: -48px -96px; }
|
||||
.ui-icon-note { background-position: -64px -96px; }
|
||||
.ui-icon-mail-closed { background-position: -80px -96px; }
|
||||
.ui-icon-mail-open { background-position: -96px -96px; }
|
||||
.ui-icon-suitcase { background-position: -112px -96px; }
|
||||
.ui-icon-comment { background-position: -128px -96px; }
|
||||
.ui-icon-person { background-position: -144px -96px; }
|
||||
.ui-icon-print { background-position: -160px -96px; }
|
||||
.ui-icon-trash { background-position: -176px -96px; }
|
||||
.ui-icon-locked { background-position: -192px -96px; }
|
||||
.ui-icon-unlocked { background-position: -208px -96px; }
|
||||
.ui-icon-bookmark { background-position: -224px -96px; }
|
||||
.ui-icon-tag { background-position: -240px -96px; }
|
||||
.ui-icon-home { background-position: 0 -112px; }
|
||||
.ui-icon-flag { background-position: -16px -112px; }
|
||||
.ui-icon-calendar { background-position: -32px -112px; }
|
||||
.ui-icon-cart { background-position: -48px -112px; }
|
||||
.ui-icon-pencil { background-position: -64px -112px; }
|
||||
.ui-icon-clock { background-position: -80px -112px; }
|
||||
.ui-icon-disk { background-position: -96px -112px; }
|
||||
.ui-icon-calculator { background-position: -112px -112px; }
|
||||
.ui-icon-zoomin { background-position: -128px -112px; }
|
||||
.ui-icon-zoomout { background-position: -144px -112px; }
|
||||
.ui-icon-search { background-position: -160px -112px; }
|
||||
.ui-icon-wrench { background-position: -176px -112px; }
|
||||
.ui-icon-gear { background-position: -192px -112px; }
|
||||
.ui-icon-heart { background-position: -208px -112px; }
|
||||
.ui-icon-star { background-position: -224px -112px; }
|
||||
.ui-icon-link { background-position: -240px -112px; }
|
||||
.ui-icon-cancel { background-position: 0 -128px; }
|
||||
.ui-icon-plus { background-position: -16px -128px; }
|
||||
.ui-icon-plusthick { background-position: -32px -128px; }
|
||||
.ui-icon-minus { background-position: -48px -128px; }
|
||||
.ui-icon-minusthick { background-position: -64px -128px; }
|
||||
.ui-icon-close { background-position: -80px -128px; }
|
||||
.ui-icon-closethick { background-position: -96px -128px; }
|
||||
.ui-icon-key { background-position: -112px -128px; }
|
||||
.ui-icon-lightbulb { background-position: -128px -128px; }
|
||||
.ui-icon-scissors { background-position: -144px -128px; }
|
||||
.ui-icon-clipboard { background-position: -160px -128px; }
|
||||
.ui-icon-copy { background-position: -176px -128px; }
|
||||
.ui-icon-contact { background-position: -192px -128px; }
|
||||
.ui-icon-image { background-position: -208px -128px; }
|
||||
.ui-icon-video { background-position: -224px -128px; }
|
||||
.ui-icon-script { background-position: -240px -128px; }
|
||||
.ui-icon-alert { background-position: 0 -144px; }
|
||||
.ui-icon-info { background-position: -16px -144px; }
|
||||
.ui-icon-notice { background-position: -32px -144px; }
|
||||
.ui-icon-help { background-position: -48px -144px; }
|
||||
.ui-icon-check { background-position: -64px -144px; }
|
||||
.ui-icon-bullet { background-position: -80px -144px; }
|
||||
.ui-icon-radio-on { background-position: -96px -144px; }
|
||||
.ui-icon-radio-off { background-position: -112px -144px; }
|
||||
.ui-icon-pin-w { background-position: -128px -144px; }
|
||||
.ui-icon-pin-s { background-position: -144px -144px; }
|
||||
.ui-icon-play { background-position: 0 -160px; }
|
||||
.ui-icon-pause { background-position: -16px -160px; }
|
||||
.ui-icon-seek-next { background-position: -32px -160px; }
|
||||
.ui-icon-seek-prev { background-position: -48px -160px; }
|
||||
.ui-icon-seek-end { background-position: -64px -160px; }
|
||||
.ui-icon-seek-start { background-position: -80px -160px; }
|
||||
/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */
|
||||
.ui-icon-seek-first { background-position: -80px -160px; }
|
||||
.ui-icon-stop { background-position: -96px -160px; }
|
||||
.ui-icon-eject { background-position: -112px -160px; }
|
||||
.ui-icon-volume-off { background-position: -128px -160px; }
|
||||
.ui-icon-volume-on { background-position: -144px -160px; }
|
||||
.ui-icon-power { background-position: 0 -176px; }
|
||||
.ui-icon-signal-diag { background-position: -16px -176px; }
|
||||
.ui-icon-signal { background-position: -32px -176px; }
|
||||
.ui-icon-battery-0 { background-position: -48px -176px; }
|
||||
.ui-icon-battery-1 { background-position: -64px -176px; }
|
||||
.ui-icon-battery-2 { background-position: -80px -176px; }
|
||||
.ui-icon-battery-3 { background-position: -96px -176px; }
|
||||
.ui-icon-circle-plus { background-position: 0 -192px; }
|
||||
.ui-icon-circle-minus { background-position: -16px -192px; }
|
||||
.ui-icon-circle-close { background-position: -32px -192px; }
|
||||
.ui-icon-circle-triangle-e { background-position: -48px -192px; }
|
||||
.ui-icon-circle-triangle-s { background-position: -64px -192px; }
|
||||
.ui-icon-circle-triangle-w { background-position: -80px -192px; }
|
||||
.ui-icon-circle-triangle-n { background-position: -96px -192px; }
|
||||
.ui-icon-circle-arrow-e { background-position: -112px -192px; }
|
||||
.ui-icon-circle-arrow-s { background-position: -128px -192px; }
|
||||
.ui-icon-circle-arrow-w { background-position: -144px -192px; }
|
||||
.ui-icon-circle-arrow-n { background-position: -160px -192px; }
|
||||
.ui-icon-circle-zoomin { background-position: -176px -192px; }
|
||||
.ui-icon-circle-zoomout { background-position: -192px -192px; }
|
||||
.ui-icon-circle-check { background-position: -208px -192px; }
|
||||
.ui-icon-circlesmall-plus { background-position: 0 -208px; }
|
||||
.ui-icon-circlesmall-minus { background-position: -16px -208px; }
|
||||
.ui-icon-circlesmall-close { background-position: -32px -208px; }
|
||||
.ui-icon-squaresmall-plus { background-position: -48px -208px; }
|
||||
.ui-icon-squaresmall-minus { background-position: -64px -208px; }
|
||||
.ui-icon-squaresmall-close { background-position: -80px -208px; }
|
||||
.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
|
||||
.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
|
||||
.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
|
||||
.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
|
||||
.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
|
||||
.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
|
||||
|
||||
|
||||
/* Misc visuals
|
||||
----------------------------------*/
|
||||
|
||||
/* Corner radius */
|
||||
.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 6px; -webkit-border-top-left-radius: 6px; -khtml-border-top-left-radius: 6px; border-top-left-radius: 6px; }
|
||||
.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 6px; -webkit-border-top-right-radius: 6px; -khtml-border-top-right-radius: 6px; border-top-right-radius: 6px; }
|
||||
.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 6px; -webkit-border-bottom-left-radius: 6px; -khtml-border-bottom-left-radius: 6px; border-bottom-left-radius: 6px; }
|
||||
.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 6px; -webkit-border-bottom-right-radius: 6px; -khtml-border-bottom-right-radius: 6px; border-bottom-right-radius: 6px; }
|
||||
|
||||
/* Overlays */
|
||||
.ui-widget-overlay { background: #eeeeee url(images/ui-bg_diagonals-thick_90_eeeeee_40x40.png) 50% 50% repeat; opacity: .8;filter:Alpha(Opacity=80); }
|
||||
.ui-widget-shadow { margin: -7px 0 0 -7px; padding: 7px; background: #000000 url(images/ui-bg_highlight-hard_70_000000_1x100.png) 50% top repeat-x; opacity: .3;filter:Alpha(Opacity=30); -moz-border-radius: 8px; -khtml-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px; }
|
||||
@@ -1,5 +0,0 @@
|
||||
/*! jQuery UI - v1.9.0 - 2012-10-21
|
||||
* http://jqueryui.com
|
||||
* Includes: jquery.ui.core.css, jquery.ui.resizable.css, jquery.ui.selectable.css, jquery.ui.accordion.css, jquery.ui.autocomplete.css, jquery.ui.button.css, jquery.ui.datepicker.css, jquery.ui.dialog.css, jquery.ui.menu.css, jquery.ui.progressbar.css, jquery.ui.slider.css, jquery.ui.spinner.css, jquery.ui.tabs.css, jquery.ui.tooltip.css
|
||||
* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Lucida%20Grande%2CLucida%20Sans%2CArial%2Csans-serif&fwDefault=bold&fsDefault=1.1em&cornerRadius=6px&bgColorHeader=deedf7&bgTextureHeader=03_highlight_soft.png&bgImgOpacityHeader=100&borderColorHeader=aed0ea&fcHeader=222222&iconColorHeader=72a7cf&bgColorContent=f2f5f7&bgTextureContent=04_highlight_hard.png&bgImgOpacityContent=100&borderColorContent=dddddd&fcContent=362b36&iconColorContent=72a7cf&bgColorDefault=d7ebf9&bgTextureDefault=02_glass.png&bgImgOpacityDefault=80&borderColorDefault=aed0ea&fcDefault=2779aa&iconColorDefault=3d80b3&bgColorHover=e4f1fb&bgTextureHover=02_glass.png&bgImgOpacityHover=100&borderColorHover=74b2e2&fcHover=0070a3&iconColorHover=2694e8&bgColorActive=3baae3&bgTextureActive=02_glass.png&bgImgOpacityActive=50&borderColorActive=2694e8&fcActive=ffffff&iconColorActive=ffffff&bgColorHighlight=ffef8f&bgTextureHighlight=03_highlight_soft.png&bgImgOpacityHighlight=25&borderColorHighlight=f9dd34&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=cd0a0a&bgTextureError=01_flat.png&bgImgOpacityError=15&borderColorError=cd0a0a&fcError=ffffff&iconColorError=ffffff&bgColorOverlay=eeeeee&bgTextureOverlay=08_diagonals_thick.png&bgImgOpacityOverlay=90&opacityOverlay=80&bgColorShadow=000000&bgTextureShadow=04_highlight_hard.png&bgImgOpacityShadow=70&opacityShadow=30&thicknessShadow=7px&offsetTopShadow=-7px&offsetLeftShadow=-7px&cornerRadiusShadow=8px
|
||||
* Copyright (c) 2012 jQuery Foundation and other contributors Licensed MIT */.ui-helper-hidden{display:none}.ui-helper-hidden-accessible{position:absolute!important;clip:rect(1px);clip:rect(1px,1px,1px,1px)}.ui-helper-reset{margin:0;padding:0;border:0;outline:0;line-height:1.3;text-decoration:none;font-size:100%;list-style:none}.ui-helper-clearfix:before,.ui-helper-clearfix:after{content:"";display:table}.ui-helper-clearfix:after{clear:both}.ui-helper-clearfix{zoom:1}.ui-helper-zfix{width:100%;height:100%;top:0;left:0;position:absolute;opacity:0;filter:Alpha(Opacity=0)}.ui-state-disabled{cursor:default!important}.ui-icon{display:block;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat}.ui-widget-overlay{position:absolute;top:0;left:0;width:100%;height:100%}.ui-resizable{position:relative}.ui-resizable-handle{position:absolute;font-size:0.1px;display:block}.ui-resizable-disabled .ui-resizable-handle,.ui-resizable-autohide .ui-resizable-handle{display:none}.ui-resizable-n{cursor:n-resize;height:7px;width:100%;top:-5px;left:0}.ui-resizable-s{cursor:s-resize;height:7px;width:100%;bottom:-5px;left:0}.ui-resizable-e{cursor:e-resize;width:7px;right:-5px;top:0;height:100%}.ui-resizable-w{cursor:w-resize;width:7px;left:-5px;top:0;height:100%}.ui-resizable-se{cursor:se-resize;width:12px;height:12px;right:1px;bottom:1px}.ui-resizable-sw{cursor:sw-resize;width:9px;height:9px;left:-5px;bottom:-5px}.ui-resizable-nw{cursor:nw-resize;width:9px;height:9px;left:-5px;top:-5px}.ui-resizable-ne{cursor:ne-resize;width:9px;height:9px;right:-5px;top:-5px}.ui-selectable-helper{position:absolute;z-index:100;border:1px dotted black}.ui-accordion .ui-accordion-header{display:block;cursor:pointer;position:relative;margin-top:2px;padding:.5em .5em .5em .7em;zoom:1}.ui-accordion .ui-accordion-icons{padding-left:2.2em}.ui-accordion .ui-accordion-noicons{padding-left:.7em}.ui-accordion .ui-accordion-icons .ui-accordion-icons{padding-left:2.2em}.ui-accordion .ui-accordion-header .ui-accordion-header-icon{position:absolute;left:.5em;top:50%;margin-top:-8px}.ui-accordion .ui-accordion-content{padding:1em 2.2em;border-top:0;overflow:auto;zoom:1}.ui-autocomplete{position:absolute;cursor:default}* html .ui-autocomplete{width:1px}.ui-button{display:inline-block;position:relative;padding:0;margin-right:.1em;cursor:pointer;text-align:center;zoom:1;overflow:visible}.ui-button,.ui-button:link,.ui-button:visited,.ui-button:hover,.ui-button:active{text-decoration:none}.ui-button-icon-only{width:2.2em}button.ui-button-icon-only{width:2.4em}.ui-button-icons-only{width:3.4em}button.ui-button-icons-only{width:3.7em}.ui-button .ui-button-text{display:block;line-height:1.4}.ui-button-text-only .ui-button-text{padding:.4em 1em}.ui-button-icon-only .ui-button-text,.ui-button-icons-only .ui-button-text{padding:.4em;text-indent:-9999999px}.ui-button-text-icon-primary .ui-button-text,.ui-button-text-icons .ui-button-text{padding:.4em 1em .4em 2.1em}.ui-button-text-icon-secondary .ui-button-text,.ui-button-text-icons .ui-button-text{padding:.4em 2.1em .4em 1em}.ui-button-text-icons .ui-button-text{padding-left:2.1em;padding-right:2.1em}input.ui-button{padding:.4em 1em}.ui-button-icon-only .ui-icon,.ui-button-text-icon-primary .ui-icon,.ui-button-text-icon-secondary .ui-icon,.ui-button-text-icons .ui-icon,.ui-button-icons-only .ui-icon{position:absolute;top:50%;margin-top:-8px}.ui-button-icon-only .ui-icon{left:50%;margin-left:-8px}.ui-button-text-icon-primary .ui-button-icon-primary,.ui-button-text-icons .ui-button-icon-primary,.ui-button-icons-only .ui-button-icon-primary{left:.5em}.ui-button-text-icon-secondary .ui-button-icon-secondary,.ui-button-text-icons .ui-button-icon-secondary,.ui-button-icons-only .ui-button-icon-secondary{right:.5em}.ui-button-text-icons .ui-button-icon-secondary,.ui-button-icons-only .ui-button-icon-secondary{right:.5em}.ui-buttonset{margin-right:7px}.ui-buttonset .ui-button{margin-left:0;margin-right:-.3em}button.ui-button::-moz-focus-inner{border:0;padding:0}.ui-datepicker{width:17em;padding:.2em .2em 0;display:none}.ui-datepicker .ui-datepicker-header{position:relative;padding:.2em 0}.ui-datepicker .ui-datepicker-prev,.ui-datepicker .ui-datepicker-next{position:absolute;top:2px;width:1.8em;height:1.8em}.ui-datepicker .ui-datepicker-prev-hover,.ui-datepicker .ui-datepicker-next-hover{top:1px}.ui-datepicker .ui-datepicker-prev{left:2px}.ui-datepicker .ui-datepicker-next{right:2px}.ui-datepicker .ui-datepicker-prev-hover{left:1px}.ui-datepicker .ui-datepicker-next-hover{right:1px}.ui-datepicker .ui-datepicker-prev span,.ui-datepicker .ui-datepicker-next span{display:block;position:absolute;left:50%;margin-left:-8px;top:50%;margin-top:-8px}.ui-datepicker .ui-datepicker-title{margin:0 2.3em;line-height:1.8em;text-align:center}.ui-datepicker .ui-datepicker-title select{font-size:1em;margin:1px 0}.ui-datepicker select.ui-datepicker-month-year{width:100%}.ui-datepicker select.ui-datepicker-month,.ui-datepicker select.ui-datepLine truncated
|
||||
@@ -1,161 +0,0 @@
|
||||
/*body,*/
|
||||
/*#wrap {*/
|
||||
/*width:1000px;*/
|
||||
/*height: 680px;*/
|
||||
/*position: absolute;*/
|
||||
/*top: 50%;*/
|
||||
/*margin-top: -350px;*/
|
||||
/*left: 50%;*/
|
||||
/*margin-left: -500px;*/
|
||||
/**/
|
||||
/*background:#ffffff;*/
|
||||
/*border: 5px outset #bbb;*/
|
||||
/*-moz-border-radius: 5px;*/
|
||||
/*-webkit-border-radius: 5px;*/
|
||||
/*border-radius: 5px;*/
|
||||
/*}*/
|
||||
/*#control {*/
|
||||
/*float:left;*/
|
||||
/*width:300px;*/
|
||||
/*margin-top: 10px;*/
|
||||
/*margin-left: 10px;*/
|
||||
/*background:#ffffff;*/
|
||||
/*margin-right: 10px;*/
|
||||
/*height: 680px;*/
|
||||
/*}*/
|
||||
#file_block {
|
||||
/*margin-top: 20px;*/
|
||||
/*margin-left: 20px;*/
|
||||
}
|
||||
|
||||
#control_bottom {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
width: 300px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
#options{
|
||||
float: left;
|
||||
margin-left: 5px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
/*#gcode {
|
||||
background: #ffffff;
|
||||
float:right;
|
||||
width: 680px;
|
||||
height: 680px;
|
||||
border-width: 2px;
|
||||
border-style: none none none solid;
|
||||
}*/
|
||||
|
||||
#canvas{
|
||||
/*float: left;*/
|
||||
clear:none;
|
||||
}
|
||||
|
||||
#drop_zone {
|
||||
border: 2px dashed #bbb;
|
||||
-moz-border-radius: 5px;
|
||||
-webkit-border-radius: 5px;
|
||||
border-radius: 5px;
|
||||
padding: 40px;
|
||||
margin: 5px;
|
||||
text-align: center;
|
||||
font: 20pt bold;
|
||||
color: #bbb
|
||||
}
|
||||
#slider-vertical {
|
||||
/*position: absolute;*/
|
||||
/*right: 0;*/
|
||||
/*top: 0;*/
|
||||
height: 580px;
|
||||
width: 10px;
|
||||
float: right;
|
||||
}
|
||||
#slider-horizontal {
|
||||
height: 10px;
|
||||
width: 570px;
|
||||
/*position: absolute;*/
|
||||
/*bottom: 0;*/
|
||||
}
|
||||
|
||||
#main_button_block {
|
||||
/*float: right;*/
|
||||
margin-bottom: 5px;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
#gcode .mbut{
|
||||
height:60px;
|
||||
width: 250px;
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
#tabs-min {
|
||||
height: 680px;
|
||||
padding: 0px;
|
||||
}
|
||||
|
||||
#gcode .mtab{
|
||||
background: transparent;
|
||||
border: none;
|
||||
font-weight: normal;
|
||||
font-size: 0.5em;
|
||||
}
|
||||
|
||||
#gcode .mtab-defstate{
|
||||
background: transparent;
|
||||
border: none;
|
||||
|
||||
}
|
||||
|
||||
#gcode .mtab-content{
|
||||
background: #ffffff;
|
||||
background-image: none;
|
||||
border: 0px none #dddddd;
|
||||
border-bottom-style: none;
|
||||
margin: 0px;
|
||||
}
|
||||
|
||||
#gcode .bar {
|
||||
-webkit-transition: width 0s linear !important;
|
||||
-moz-transition: width 0s linear !important;
|
||||
-o-transition: width 0s linear !important;
|
||||
transition: width 0s linear !important;
|
||||
}
|
||||
|
||||
#gcode .nav {
|
||||
margin-bottom: 0px !important;
|
||||
}
|
||||
|
||||
#gcode .tab-content {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
#gcode .aboutpage {
|
||||
margin: 10px;
|
||||
}
|
||||
|
||||
#accordion_top .ui-accordion-content{
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
#tabs-min .ui-tabs-panel {
|
||||
padding: 0px;
|
||||
}
|
||||
|
||||
#progressBlock {
|
||||
margin-left: 10px;
|
||||
margin-right: 10px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
#gcode .colorBox {
|
||||
width: 50px;
|
||||
height: 15px;
|
||||
border: 1px solid #000000;
|
||||
float:left;
|
||||
}
|
||||
|
||||
#gcode .activeline {background: #fff0b6 !important;}
|
||||
|
||||
@@ -1,473 +0,0 @@
|
||||
/**
|
||||
* User: hudbrog (hudbrog@gmail.com)
|
||||
* Date: 10/24/12
|
||||
* Time: 12:18 PM
|
||||
*/
|
||||
|
||||
var gcode;
|
||||
var firstReport;
|
||||
var z_heights = {};
|
||||
var model = [];
|
||||
var gCodeOptions = {
|
||||
sortLayers: false,
|
||||
purgeEmptyLayers: true,
|
||||
analyzeModel: false
|
||||
};
|
||||
var max = {x: undefined, y: undefined, z: undefined};
|
||||
var min = {x: undefined, y: undefined, z: undefined};
|
||||
var modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
var filamentByLayer = {};
|
||||
var totalFilament=0;
|
||||
var printTime=0;
|
||||
var printTimeByLayer = {};
|
||||
var layerHeight=0;
|
||||
var layerCnt = 0;
|
||||
var speeds = {extrude: [], retract: [], move: []};
|
||||
var speedsByLayer = {extrude: {}, retract: {}, move: {}};
|
||||
|
||||
|
||||
|
||||
var sendLayerToParent = function(layerNum, z, progress){
|
||||
self.postMessage({
|
||||
"cmd": "returnLayer",
|
||||
"msg": {
|
||||
cmds: model[layerNum],
|
||||
layerNum: layerNum,
|
||||
zHeightObject: {zValue: z, layer: z_heights[z]},
|
||||
isEmpty: false,
|
||||
progress: progress
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var sendMultiLayerToParent = function(layerNum, z, progress){
|
||||
var tmpModel = [];
|
||||
var tmpZHeight = {};
|
||||
|
||||
for(var i=0;i<layerNum.length;i++){
|
||||
tmpModel[layerNum[i]] = model[layerNum[i]];
|
||||
tmpZHeight[layerNum[i]] = z_heights[z[i]];
|
||||
}
|
||||
|
||||
self.postMessage({
|
||||
"cmd": "returnMultiLayer",
|
||||
"msg": {
|
||||
model: tmpModel,
|
||||
layerNum: layerNum,
|
||||
zHeightObject: {zValue: z, layer: tmpZHeight},
|
||||
isEmpty: false,
|
||||
progress: progress
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
var sendSizeProgress = function(progress){
|
||||
self.postMessage({
|
||||
"cmd": "analyzeProgress",
|
||||
"msg": {
|
||||
progress: progress,
|
||||
printTime: printTime
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var sendAnalyzeDone = function(){
|
||||
self.postMessage({
|
||||
"cmd": "analyzeDone",
|
||||
"msg": {
|
||||
max: max,
|
||||
min: min,
|
||||
modelSize: modelSize,
|
||||
totalFilament:totalFilament,
|
||||
filamentByLayer: filamentByLayer,
|
||||
printTime: printTime,
|
||||
layerHeight: layerHeight,
|
||||
layerCnt: layerCnt,
|
||||
layerTotal: model.length,
|
||||
speeds: speeds,
|
||||
speedsByLayer: speedsByLayer,
|
||||
printTimeByLayer: printTimeByLayer
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var purgeLayers = function(){
|
||||
var purge=true;
|
||||
for(var i=0;i<model.length;i++){
|
||||
purge=true;
|
||||
if(!model[i])purge=true;
|
||||
else {
|
||||
for(var j=0;j<model[i].length;j++){
|
||||
if(model[i][j].extrude)purge=false;
|
||||
}
|
||||
}
|
||||
if(!purge){
|
||||
layerCnt+=1;
|
||||
}
|
||||
}
|
||||
// self.postMessage('LayerCnt: ' + layerCnt);
|
||||
};
|
||||
|
||||
|
||||
var analyzeModel = function(){
|
||||
var i,j;
|
||||
var x_ok=false, y_ok=false;
|
||||
var cmds;
|
||||
var tmp1= 0, tmp2=0;
|
||||
var speedIndex=0;
|
||||
var type;
|
||||
var printTimeAdd=0;
|
||||
// var moveTime=0;
|
||||
|
||||
for(i=0;i<model.length;i++){
|
||||
cmds = model[i];
|
||||
if(!cmds)continue;
|
||||
for(j=0;j<cmds.length;j++){
|
||||
x_ok=false;
|
||||
y_ok=false;
|
||||
if(typeof(cmds[j].x) !== 'undefined'&&typeof(cmds[j].prevX) !== 'undefined'&&typeof(cmds[j].extrude) !== 'undefined'&&cmds[j].extrude&&!isNaN(cmds[j].x))
|
||||
{
|
||||
max.x = parseFloat(max.x)>parseFloat(cmds[j].x)?parseFloat(max.x):parseFloat(cmds[j].x);
|
||||
max.x = parseFloat(max.x)>parseFloat(cmds[j].prevX)?parseFloat(max.x):parseFloat(cmds[j].prevX);
|
||||
min.x = parseFloat(min.x)<parseFloat(cmds[j].x)?parseFloat(min.x):parseFloat(cmds[j].x);
|
||||
min.x = parseFloat(min.x)<parseFloat(cmds[j].prevX)?parseFloat(min.x):parseFloat(cmds[j].prevX);
|
||||
x_ok=true;
|
||||
}
|
||||
|
||||
if(typeof(cmds[j].y) !== 'undefined'&&typeof(cmds[j].prevY) !== 'undefined'&&typeof(cmds[j].extrude) !== 'undefined'&&cmds[j].extrude&&!isNaN(cmds[j].y)){
|
||||
max.y = parseFloat(max.y)>parseFloat(cmds[j].y)?parseFloat(max.y):parseFloat(cmds[j].y);
|
||||
max.y = parseFloat(max.y)>parseFloat(cmds[j].prevY)?parseFloat(max.y):parseFloat(cmds[j].prevY);
|
||||
min.y = parseFloat(min.y)<parseFloat(cmds[j].y)?parseFloat(min.y):parseFloat(cmds[j].y);
|
||||
min.y = parseFloat(min.y)<parseFloat(cmds[j].prevY)?parseFloat(min.y):parseFloat(cmds[j].prevY);
|
||||
y_ok=true;
|
||||
}
|
||||
|
||||
if(typeof(cmds[j].prevZ) !== 'undefined'&&typeof(cmds[j].extrude) !== 'undefined'&&cmds[j].extrude&&!isNaN(cmds[j].prevZ)){
|
||||
max.z = parseFloat(max.z)>parseFloat(cmds[j].prevZ)?parseFloat(max.z):parseFloat(cmds[j].prevZ);
|
||||
min.z = parseFloat(min.z)<parseFloat(cmds[j].prevZ)?parseFloat(min.z):parseFloat(cmds[j].prevZ);
|
||||
}
|
||||
|
||||
if(typeof(cmds[j].extrude) !== 'undefined'||cmds[j].retract!=0){
|
||||
totalFilament+=cmds[j].extrusion;
|
||||
if(!filamentByLayer[cmds[j].prevZ])filamentByLayer[cmds[j].prevZ]=0;
|
||||
filamentByLayer[cmds[j].prevZ]+=cmds[j].extrusion;
|
||||
}
|
||||
|
||||
if(x_ok&&y_ok){
|
||||
printTimeAdd = Math.sqrt(Math.pow(parseFloat(cmds[j].x)-parseFloat(cmds[j].prevX),2)+Math.pow(parseFloat(cmds[j].y)-parseFloat(cmds[j].prevY),2))/(cmds[j].speed/60);
|
||||
}else if(cmds[j].retract===0&&cmds[j].extrusion!==0){
|
||||
tmp1 = Math.sqrt(Math.pow(parseFloat(cmds[j].x)-parseFloat(cmds[j].prevX),2)+Math.pow(parseFloat(cmds[j].y)-parseFloat(cmds[j].prevY),2))/(cmds[j].speed/60);
|
||||
tmp2 = Math.abs(parseFloat(cmds[j].extrusion)/(cmds[j].speed/60));
|
||||
printTimeAdd = tmp1>=tmp2?tmp1:tmp2;
|
||||
}else if(cmds[j].retract!==0){
|
||||
printTimeAdd = Math.abs(parseFloat(cmds[j].extrusion)/(cmds[j].speed/60));
|
||||
}
|
||||
|
||||
printTime += printTimeAdd;
|
||||
if(typeof(printTimeByLayer[cmds[j].prevZ])==='undefined'){printTimeByLayer[cmds[j].prevZ]=0;}
|
||||
printTimeByLayer[cmds[j].prevZ] += printTimeAdd;
|
||||
|
||||
if(cmds[j].extrude&&cmds[j].retract===0){
|
||||
type = 'extrude';
|
||||
}else if(cmds[j].retract!==0){
|
||||
type = 'retract';
|
||||
}else if(!cmds[j].extrude&&cmds[j].retract===0){
|
||||
type = 'move';
|
||||
// if(cmds[j].prevZ == '17.1'){
|
||||
// self.postMessage({cmd: 'Got speed ' + cmds[j].speed + 'with line ' + cmds[j].gcodeLine});
|
||||
// }
|
||||
}else {
|
||||
self.postMessage({cmd: 'unknown type of move'});
|
||||
type = 'unknown';
|
||||
}
|
||||
speedIndex = speeds[type].indexOf(cmds[j].speed);
|
||||
if (speedIndex === -1) {
|
||||
speeds[type].push(cmds[j].speed);
|
||||
speedIndex = speeds[type].indexOf(cmds[j].speed);
|
||||
}
|
||||
if(typeof(speedsByLayer[type][cmds[j].prevZ]) === 'undefined'){
|
||||
speedsByLayer[type][cmds[j].prevZ] = [];
|
||||
}
|
||||
if(speedsByLayer[type][cmds[j].prevZ].indexOf(cmds[j].speed) === -1){
|
||||
speedsByLayer[type][cmds[j].prevZ][speedIndex] = cmds[j].speed;
|
||||
}
|
||||
|
||||
}
|
||||
sendSizeProgress(i/model.length*100);
|
||||
|
||||
}
|
||||
purgeLayers();
|
||||
|
||||
modelSize.x = Math.abs(max.x - min.x);
|
||||
modelSize.y = Math.abs(max.y - min.y);
|
||||
modelSize.z = Math.abs(max.z - min.z);
|
||||
layerHeight = (max.z-min.z)/(layerCnt-1);
|
||||
|
||||
sendAnalyzeDone();
|
||||
};
|
||||
|
||||
var doParse = function(){
|
||||
var argChar, numSlice;
|
||||
model=[];
|
||||
var sendLayer = undefined;
|
||||
var sendLayerZ = 0;
|
||||
var sendMultiLayer = [];
|
||||
var sendMultiLayerZ = [];
|
||||
var lastSend = 0;
|
||||
// console.time("parseGCode timer");
|
||||
var reg = new RegExp(/^(?:G0|G1)\s/i);
|
||||
var comment = new RegExp()
|
||||
var j, layer= 0, extrude=false, prevRetract= 0, retract=0, x, y, z=0, f, prevZ=0, prevX, prevY,lastF=4000, prev_extrude = {a: undefined, b: undefined, c: undefined, e: undefined, abs: undefined}, extrudeRelative=false;
|
||||
var dcExtrude=false;
|
||||
var assumeNonDC = false;
|
||||
|
||||
for(var i=0;i<gcode.length;i++){
|
||||
x=undefined;
|
||||
y=undefined;
|
||||
z=undefined;
|
||||
retract = 0;
|
||||
|
||||
var line = gcode[i].line;
|
||||
var percentage = gcode[i].percentage;
|
||||
|
||||
extrude=false;
|
||||
line = line.split(/[\(;]/)[0];
|
||||
|
||||
if(reg.test(line)){
|
||||
var args = line.split(/\s/);
|
||||
for(j=0;j<args.length;j++){
|
||||
switch(argChar = args[j].charAt(0).toLowerCase()){
|
||||
case 'x':
|
||||
x=args[j].slice(1);
|
||||
break;
|
||||
case 'y':
|
||||
y=args[j].slice(1);
|
||||
break;
|
||||
case 'z':
|
||||
z=args[j].slice(1);
|
||||
z = Number(z);
|
||||
if(z == prevZ) continue;
|
||||
if(z_heights.hasOwnProperty(z)){
|
||||
layer = z_heights[z];
|
||||
}else{
|
||||
layer = model.length;
|
||||
z_heights[z] = layer;
|
||||
}
|
||||
sendLayer = layer;
|
||||
sendLayerZ = z;
|
||||
prevZ = z;
|
||||
break;
|
||||
case 'e':
|
||||
case 'a':
|
||||
case 'b':
|
||||
case 'c':
|
||||
assumeNonDC = true;
|
||||
numSlice = parseFloat(args[j].slice(1)).toFixed(3);
|
||||
|
||||
if(!extrudeRelative){
|
||||
// absolute extrusion positioning
|
||||
prev_extrude["abs"] = parseFloat(numSlice)-parseFloat(prev_extrude[argChar]);
|
||||
|
||||
}else{
|
||||
prev_extrude["abs"] = parseFloat(numSlice);
|
||||
}
|
||||
extrude = prev_extrude["abs"]>0;
|
||||
if(prev_extrude["abs"]<0){
|
||||
prevRetract = -1;
|
||||
retract = -1;
|
||||
}
|
||||
else if(prev_extrude["abs"]==0){
|
||||
retract = 0;
|
||||
}else if(prev_extrude["abs"]>0&&prevRetract < 0){
|
||||
prevRetract = 0;
|
||||
retract = 1;
|
||||
} else {
|
||||
retract = 0;
|
||||
}
|
||||
prev_extrude[argChar] = numSlice;
|
||||
|
||||
break;
|
||||
case 'f':
|
||||
numSlice = args[j].slice(1);
|
||||
lastF = numSlice;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(dcExtrude&&!assumeNonDC){
|
||||
extrude = true;
|
||||
prev_extrude["abs"] = Math.sqrt((prevX-x)*(prevX-x)+(prevY-y)*(prevY-y));
|
||||
}
|
||||
if(!model[layer])model[layer]=[];
|
||||
if(typeof(x) !== 'undefined' || typeof(y) !== 'undefined' ||typeof(z) !== 'undefined'||retract!=0) model[layer][model[layer].length] = {x: Number(x), y: Number(y), z: Number(z), extrude: extrude, retract: Number(retract), noMove: false, extrusion: (extrude||retract)?Number(prev_extrude["abs"]):0, prevX: Number(prevX), prevY: Number(prevY), prevZ: Number(prevZ), speed: Number(lastF), gcodeLine: Number(i), percentage: percentage};
|
||||
//{x: x, y: y, z: z, extrude: extrude, retract: retract, noMove: false, extrusion: (extrude||retract)?prev_extrude["abs"]:0, prevX: prevX, prevY: prevY, prevZ: prevZ, speed: lastF, gcodeLine: i};
|
||||
if(typeof(x) !== 'undefined') prevX = x;
|
||||
if(typeof(y) !== 'undefined') prevY = y;
|
||||
} else if(line.match(/^(?:M82)/i)){
|
||||
extrudeRelative = false;
|
||||
}else if(line.match(/^(?:G91)/i)){
|
||||
extrudeRelative=true;
|
||||
}else if(line.match(/^(?:G90)/i)){
|
||||
extrudeRelative=false;
|
||||
}else if(line.match(/^(?:M83)/i)){
|
||||
extrudeRelative=true;
|
||||
}else if(line.match(/^(?:M101)/i)){
|
||||
dcExtrude=true;
|
||||
}else if(line.match(/^(?:M103)/i)){
|
||||
dcExtrude=false;
|
||||
}else if(line.match(/^(?:G92)/i)){
|
||||
var args = line.split(/\s/);
|
||||
for(j=0;j<args.length;j++){
|
||||
switch(argChar = args[j].charAt(0).toLowerCase()){
|
||||
case 'x':
|
||||
x=args[j].slice(1);
|
||||
break;
|
||||
case 'y':
|
||||
y=args[j].slice(1);
|
||||
break;
|
||||
case 'z':
|
||||
z=args[j].slice(1);
|
||||
prevZ = z;
|
||||
break;
|
||||
case 'e'||'a'||'b'||'c':
|
||||
numSlice = args[j].slice(1);
|
||||
if(!extrudeRelative)
|
||||
prev_extrude[argChar] = 0;
|
||||
else {
|
||||
prev_extrude[argChar] = numSlice;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(!model[layer])model[layer]=[];
|
||||
if(typeof(x) !== 'undefined' || typeof(y) !== 'undefined' ||typeof(z) !== 'undefined') model[layer][model[layer].length] = {x: parseFloat(x), y: parseFloat(y), z: parseFloat(z), extrude: extrude, retract: parseFloat(retract), noMove: true, extrusion: (extrude||retract)?parseFloat(prev_extrude["abs"]):0, prevX: parseFloat(prevX), prevY: parseFloat(prevY), prevZ: parseFloat(prevZ), speed: parseFloat(lastF),gcodeLine: parseFloat(i), percentage: percentage};
|
||||
}else if(line.match(/^(?:G28)/i)){
|
||||
var args = line.split(/\s/);
|
||||
for(j=0;j<args.length;j++){
|
||||
switch(argChar = args[j].charAt(0).toLowerCase()){
|
||||
case 'x':
|
||||
x=args[j].slice(1);
|
||||
break;
|
||||
case 'y':
|
||||
y=args[j].slice(1);
|
||||
break;
|
||||
case 'z':
|
||||
z=args[j].slice(1);
|
||||
z = Number(z);
|
||||
if(z === prevZ)continue;
|
||||
sendLayer = layer;
|
||||
sendLayerZ = z;//}
|
||||
if(z_heights.hasOwnProperty(z)){
|
||||
layer = z_heights[z];
|
||||
}else{
|
||||
layer = model.length;
|
||||
z_heights[z] = layer;
|
||||
}
|
||||
prevZ = z;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
// G28 with no arguments
|
||||
if(args.length == 1){
|
||||
//need to init values to default here
|
||||
}
|
||||
// if it's the first layer and G28 was without
|
||||
if(layer==0&&typeof(z) === 'undefined'){
|
||||
z=0;
|
||||
if(z_heights.hasOwnProperty(z)){
|
||||
layer = z_heights[z];
|
||||
}else{
|
||||
layer = model.length;
|
||||
z_heights[z] = layer;
|
||||
}
|
||||
prevZ = z;
|
||||
}
|
||||
|
||||
if(!model[layer])model[layer]=[];
|
||||
if(typeof(x) !== 'undefined' || typeof(y) !== 'undefined' ||typeof(z) !== 'undefined'||retract!=0) model[layer][model[layer].length] = {x: Number(x), y: Number(y), z: Number(z), extrude: extrude, retract: Number(retract), noMove: false, extrusion: (extrude||retract)?Number(prev_extrude["abs"]):0, prevX: Number(prevX), prevY: Number(prevY), prevZ: Number(prevZ), speed: Number(lastF), gcodeLine: Number(i), percentage: percentage};
|
||||
}
|
||||
if(typeof(sendLayer) !== "undefined"){
|
||||
|
||||
if(i-lastSend > gcode.length*0.02 && sendMultiLayer.length != 0){
|
||||
lastSend = i;
|
||||
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i/gcode.length*100);
|
||||
sendMultiLayer = [];
|
||||
sendMultiLayerZ = [];
|
||||
}
|
||||
sendMultiLayer[sendMultiLayer.length] = sendLayer;
|
||||
sendMultiLayerZ[sendMultiLayerZ.length] = sendLayerZ;
|
||||
sendLayer = undefined;
|
||||
sendLayerZ = undefined;
|
||||
}
|
||||
}
|
||||
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i/gcode.length*100);
|
||||
};
|
||||
|
||||
|
||||
var parseGCode = function(message){
|
||||
gcode = message.gcode;
|
||||
firstReport = message.options.firstReport;
|
||||
|
||||
|
||||
doParse();
|
||||
gcode = [];
|
||||
self.postMessage({
|
||||
"cmd": "returnModel",
|
||||
"msg": {
|
||||
// model: model
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
var runAnalyze = function(message){
|
||||
analyzeModel();
|
||||
model = [];
|
||||
z_heights = [];
|
||||
gcode = undefined;
|
||||
firstReport = undefined;
|
||||
z_heights = {};
|
||||
model = [];
|
||||
max = {x: undefined, y: undefined, z: undefined};
|
||||
min = {x: undefined, y: undefined, z: undefined};
|
||||
modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
filamentByLayer = {};
|
||||
totalFilament=0;
|
||||
printTime=0;
|
||||
printTimeByLayer = {};
|
||||
layerHeight=0;
|
||||
layerCnt = 0;
|
||||
speeds = {extrude: [], retract: [], move: []};
|
||||
speedsByLayer = {extrude: {}, retract: {}, move: {}};
|
||||
};
|
||||
var setOption = function(options){
|
||||
for(var opt in options){
|
||||
gCodeOptions[opt] = options[opt];
|
||||
}
|
||||
};
|
||||
|
||||
onmessage = function (e){
|
||||
var data = e.data;
|
||||
// for some reason firefox doesn't garbage collect when something inside closures is deleted, so we delete and recreate whole object eaech time
|
||||
switch (data.cmd) {
|
||||
case 'parseGCode':
|
||||
parseGCode(data.msg);
|
||||
break;
|
||||
case 'setOption':
|
||||
setOption(data.msg);
|
||||
break;
|
||||
case 'analyzeModel':
|
||||
runAnalyze(data.msg);
|
||||
break;
|
||||
|
||||
default:
|
||||
self.postMessage('Unknown command: ' + data.msg);
|
||||
}
|
||||
|
||||
};
|
||||
@@ -1,417 +0,0 @@
|
||||
/**
|
||||
* User: hudbrog (hudbrog@gmail.com)
|
||||
* Date: 10/20/12
|
||||
* Time: 1:36 PM
|
||||
* To change this template use File | Settings | File Templates.
|
||||
*/
|
||||
|
||||
|
||||
GCODE.renderer = (function(){
|
||||
// ***** PRIVATE ******
|
||||
var canvas;
|
||||
var ctx;
|
||||
var zoomFactor= 2.8, zoomFactorDelta = 0.4;
|
||||
var gridSizeX=200,gridSizeY=200,gridStep=10;
|
||||
var ctxHeight, ctxWidth;
|
||||
var prevX=0, prevY=0;
|
||||
|
||||
// var colorGrid="#bbbbbb", colorLine="#000000";
|
||||
var sliderHor, sliderVer;
|
||||
var layerNumStore, progressStore={from: 0, to: -1};
|
||||
var lastX, lastY;
|
||||
var dragStart,dragged;
|
||||
var scaleFactor = 1.1;
|
||||
var model;
|
||||
var initialized=false;
|
||||
var renderOptions = {
|
||||
showMoves: true,
|
||||
showRetracts: true,
|
||||
colorGrid: "#bbbbbb",
|
||||
extrusionWidth: 1,
|
||||
// colorLine: ["#000000", "#aabb88", "#ffe7a0", "#6e7700", "#331a00", "#44ba97", "#08262f", "#db0e00", "#ff9977"],
|
||||
colorLine: ["#000000", "#45c7ba", "#a9533a", "#ff44cc", "#dd1177", "#eeee22", "#ffbb55", "#ff5511", "#777788"],
|
||||
colorMove: "#00ff00",
|
||||
colorRetract: "#ff0000",
|
||||
colorRestart: "#0000ff",
|
||||
sizeRetractSpot: 2,
|
||||
modelCenter: {x: 0, y: 0},
|
||||
moveModel: true,
|
||||
differentiateColors: true,
|
||||
showNextLayer: false
|
||||
};
|
||||
|
||||
var offsetModelX=0, offsetModelY=0;
|
||||
var speeds = [];
|
||||
var speedsByLayer = {};
|
||||
|
||||
|
||||
var reRender = function(){
|
||||
var p1 = ctx.transformedPoint(0,0);
|
||||
var p2 = ctx.transformedPoint(canvas.width,canvas.height);
|
||||
ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);
|
||||
drawGrid();
|
||||
if(renderOptions['showNextLayer'] && layerNumStore < model.length - 1) {
|
||||
drawLayer(layerNumStore+1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore+1), true);
|
||||
}
|
||||
drawLayer(layerNumStore, progressStore.from, progressStore.to);
|
||||
};
|
||||
|
||||
function trackTransforms(ctx){
|
||||
var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
|
||||
var xform = svg.createSVGMatrix();
|
||||
ctx.getTransform = function(){ return xform; };
|
||||
|
||||
var savedTransforms = [];
|
||||
var save = ctx.save;
|
||||
ctx.save = function(){
|
||||
savedTransforms.push(xform.translate(0,0));
|
||||
return save.call(ctx);
|
||||
};
|
||||
var restore = ctx.restore;
|
||||
ctx.restore = function(){
|
||||
xform = savedTransforms.pop();
|
||||
return restore.call(ctx);
|
||||
};
|
||||
|
||||
var scale = ctx.scale;
|
||||
ctx.scale = function(sx,sy){
|
||||
xform = xform.scaleNonUniform(sx,sy);
|
||||
return scale.call(ctx,sx,sy);
|
||||
};
|
||||
var rotate = ctx.rotate;
|
||||
ctx.rotate = function(radians){
|
||||
xform = xform.rotate(radians*180/Math.PI);
|
||||
return rotate.call(ctx,radians);
|
||||
};
|
||||
var translate = ctx.translate;
|
||||
ctx.translate = function(dx,dy){
|
||||
xform = xform.translate(dx,dy);
|
||||
return translate.call(ctx,dx,dy);
|
||||
};
|
||||
var transform = ctx.transform;
|
||||
ctx.transform = function(a,b,c,d,e,f){
|
||||
var m2 = svg.createSVGMatrix();
|
||||
m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f;
|
||||
xform = xform.multiply(m2);
|
||||
return transform.call(ctx,a,b,c,d,e,f);
|
||||
};
|
||||
var setTransform = ctx.setTransform;
|
||||
ctx.setTransform = function(a,b,c,d,e,f){
|
||||
xform.a = a;
|
||||
xform.b = b;
|
||||
xform.c = c;
|
||||
xform.d = d;
|
||||
xform.e = e;
|
||||
xform.f = f;
|
||||
return setTransform.call(ctx,a,b,c,d,e,f);
|
||||
};
|
||||
var pt = svg.createSVGPoint();
|
||||
ctx.transformedPoint = function(x,y){
|
||||
pt.x=x; pt.y=y;
|
||||
return pt.matrixTransform(xform.inverse());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var startCanvas = function() {
|
||||
canvas = document.getElementById('canvas');
|
||||
|
||||
// Проверяем понимает ли браузер canvas
|
||||
if (!canvas.getContext) {
|
||||
throw "exception";
|
||||
}
|
||||
|
||||
ctx = canvas.getContext('2d'); // Получаем 2D контекст
|
||||
ctxHeight = canvas.height;
|
||||
ctxWidth = canvas.width;
|
||||
lastX = ctxWidth/2;
|
||||
lastY = ctxHeight/2;
|
||||
ctx.lineWidth = 2;
|
||||
ctx.lineCap = 'round';
|
||||
trackTransforms(ctx);
|
||||
|
||||
canvas.addEventListener('mousedown',function(evt){
|
||||
document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none';
|
||||
lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
|
||||
lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
|
||||
dragStart = ctx.transformedPoint(lastX,lastY);
|
||||
dragged = false;
|
||||
},false);
|
||||
canvas.addEventListener('mousemove',function(evt){
|
||||
lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
|
||||
lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
|
||||
dragged = true;
|
||||
if (dragStart){
|
||||
var pt = ctx.transformedPoint(lastX,lastY);
|
||||
ctx.translate(pt.x-dragStart.x,pt.y-dragStart.y);
|
||||
reRender();
|
||||
}
|
||||
},false);
|
||||
canvas.addEventListener('mouseup',function(evt){
|
||||
dragStart = null;
|
||||
if (!dragged) zoom(evt.shiftKey ? -1 : 1 );
|
||||
},false);
|
||||
var zoom = function(clicks){
|
||||
var pt = ctx.transformedPoint(lastX,lastY);
|
||||
ctx.translate(pt.x,pt.y);
|
||||
var factor = Math.pow(scaleFactor,clicks);
|
||||
ctx.scale(factor,factor);
|
||||
ctx.translate(-pt.x,-pt.y);
|
||||
reRender();
|
||||
};
|
||||
var handleScroll = function(evt){
|
||||
var delta;
|
||||
if(evt.detail<0 || evt.wheelDelta>0)delta=zoomFactorDelta;
|
||||
else delta=-1*zoomFactorDelta;
|
||||
if (delta) zoom(delta);
|
||||
return evt.preventDefault() && false;
|
||||
};
|
||||
canvas.addEventListener('DOMMouseScroll',handleScroll,false);
|
||||
canvas.addEventListener('mousewheel',handleScroll,false);
|
||||
|
||||
};
|
||||
|
||||
var drawGrid = function() {
|
||||
var i;
|
||||
ctx.strokeStyle = renderOptions["colorGrid"];
|
||||
ctx.lineWidth = 1;
|
||||
var offsetX=0, offsetY=0;
|
||||
if(renderOptions["moveModel"]){
|
||||
offsetX = offsetModelX;
|
||||
offsetY = offsetModelY;
|
||||
}
|
||||
|
||||
ctx.beginPath();
|
||||
for(i=0;i<=gridSizeX;i+=gridStep){
|
||||
ctx.moveTo(i*zoomFactor-offsetX, 0-offsetY);
|
||||
ctx.lineTo(i*zoomFactor-offsetX, -gridSizeY*zoomFactor-offsetY);
|
||||
}
|
||||
ctx.stroke();
|
||||
|
||||
ctx.beginPath();
|
||||
for(i=0;i<=gridSizeY;i+=gridStep){
|
||||
ctx.moveTo(0-offsetX, -i*zoomFactor-offsetY);
|
||||
ctx.lineTo(gridSizeX*zoomFactor-offsetX, -i*zoomFactor-offsetY);
|
||||
}
|
||||
ctx.stroke();
|
||||
|
||||
};
|
||||
|
||||
var drawLayer = function(layerNum, fromProgress, toProgress, isNextLayer){
|
||||
var i, speedIndex= 0, prevZ = 0;
|
||||
isNextLayer = typeof isNextLayer !== 'undefined' ? isNextLayer : false;
|
||||
if(!isNextLayer){
|
||||
layerNumStore=layerNum;
|
||||
progressStore = {from: fromProgress, to: toProgress};
|
||||
}
|
||||
if(!model||!model[layerNum])return;
|
||||
|
||||
var cmds = model[layerNum];
|
||||
var x, y;
|
||||
|
||||
// if(toProgress === -1){
|
||||
// toProgress=cmds.length;
|
||||
// }
|
||||
|
||||
if(fromProgress>0){
|
||||
prevX = cmds[fromProgress-1].x*zoomFactor;
|
||||
prevY = -cmds[fromProgress-1].y*zoomFactor;
|
||||
}else if(fromProgress===0 && layerNum==0){
|
||||
if(model[0]&&model[0].x !== undefined &&model[0].y !== undefined){
|
||||
prevX = model[0].x*zoomFactor;
|
||||
prevY = -model[0].y*zoomFactor;
|
||||
}else {
|
||||
prevX = 0;
|
||||
prevY = 0;
|
||||
}
|
||||
}else if(typeof(cmds[0].prevX) !== 'undefined' && typeof(cmds[0].prevY) !== 'undefined'){
|
||||
prevX = cmds[0].prevX*zoomFactor;
|
||||
prevY = -cmds[0].prevY*zoomFactor;
|
||||
}else{
|
||||
if(model[layerNum-1]){
|
||||
prevX=undefined;
|
||||
prevY=undefined;
|
||||
for(i=model[layerNum-1].length-1;i>=0;i--){
|
||||
if(prevX === undefined && model[layerNum-1][i].x!==undefined)prevX=model[layerNum-1][i].x*zoomFactor;
|
||||
if(prevY === undefined && model[layerNum-1][i].y!==undefined)prevY=-model[layerNum-1][i].y*zoomFactor;
|
||||
}
|
||||
if(prevX === undefined)prevX=0;
|
||||
if(prevY === undefined)prevY=0;
|
||||
}else{
|
||||
prevX=0;
|
||||
prevY=0;
|
||||
}
|
||||
}
|
||||
|
||||
prevZ = GCODE.renderer.getZ(layerNum);
|
||||
|
||||
// ctx.strokeStyle = renderOptions["colorLine"];
|
||||
for(i=fromProgress;i<=toProgress;i++){
|
||||
ctx.lineWidth = 1;
|
||||
|
||||
if(typeof(cmds[i]) === 'undefined')continue;
|
||||
|
||||
if(typeof(cmds[i].prevX) !== 'undefined' && typeof(cmds[i].prevY) !== 'undefined'){
|
||||
prevX = cmds[i].prevX*zoomFactor;
|
||||
prevY = -cmds[i].prevY*zoomFactor;
|
||||
}
|
||||
// console.log(cmds[i]);
|
||||
if(typeof(cmds[i].x)==='undefined'||isNaN(cmds[i].x))x=prevX/zoomFactor;
|
||||
else x = cmds[i].x;
|
||||
if(typeof(cmds[i].y) === 'undefined'||isNaN(cmds[i].y))y=prevY/zoomFactor;
|
||||
else y = -cmds[i].y;
|
||||
if(renderOptions["differentiateColors"]&&!renderOptions['showNextLayer']){
|
||||
// if(speedsByLayer['extrude'][prevZ]){
|
||||
speedIndex = speeds['extrude'].indexOf(cmds[i].speed);
|
||||
// speedIndex = GCODE.ui.ArrayIndexOf(speedsByLayer['extrude'][prevZ], function(obj) {return obj.speed === cmds[i].speed;});
|
||||
// } else {
|
||||
// speedIndex = -1;
|
||||
// }
|
||||
if(speedIndex === -1){
|
||||
speedIndex = 0;
|
||||
}else if(speedIndex > renderOptions["colorLine"].length -1){
|
||||
speedIndex = speedIndex % (renderOptions["colorLine"].length-1);
|
||||
// console.log("Too much colors");
|
||||
}
|
||||
}else if(renderOptions['showNextLayer']&&isNextLayer){
|
||||
speedIndex=3;
|
||||
}else{
|
||||
speedIndex=0;
|
||||
}
|
||||
|
||||
|
||||
if(!cmds[i].extrude&&!cmds[i].noMove){
|
||||
// ctx.stroke();
|
||||
if(cmds[i].retract == -1){
|
||||
if(renderOptions["showRetracts"]){
|
||||
|
||||
ctx.strokeStyle = renderOptions["colorRetract"];
|
||||
ctx.fillStyle = renderOptions["colorRetract"];
|
||||
ctx.beginPath();
|
||||
ctx.arc(prevX, prevY, renderOptions["sizeRetractSpot"], 0, Math.PI*2, true);
|
||||
ctx.stroke();
|
||||
ctx.fill();
|
||||
}
|
||||
}
|
||||
if(renderOptions["showMoves"]){
|
||||
ctx.strokeStyle = renderOptions["colorMove"];
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(prevX, prevY);
|
||||
ctx.lineTo(x*zoomFactor,y*zoomFactor);
|
||||
ctx.stroke();
|
||||
}
|
||||
// ctx.strokeStyle = renderOptions["colorLine"][0];
|
||||
// ctx.beginPath();
|
||||
// console.log("moveto: "+cmds[i].x+":"+cmds[i].y)
|
||||
// ctx.moveTo(cmds[i].x*zoomFactor,cmds[i].y*zoomFactor);
|
||||
}
|
||||
else if(cmds[i].extrude){
|
||||
if(cmds[i].retract==0){
|
||||
ctx.strokeStyle = renderOptions["colorLine"][speedIndex];
|
||||
ctx.lineWidth = renderOptions['extrusionWidth'];
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(prevX, prevY);
|
||||
ctx.lineTo(x*zoomFactor,y*zoomFactor);
|
||||
ctx.stroke();
|
||||
}else {
|
||||
if(renderOptions["showRetracts"]){
|
||||
// ctx.stroke();
|
||||
ctx.strokeStyle = renderOptions["colorRestart"];
|
||||
ctx.fillStyle = renderOptions["colorRestart"];
|
||||
ctx.beginPath();
|
||||
ctx.arc(prevX, prevY, renderOptions["sizeRetractSpot"], 0, Math.PI*2, true);
|
||||
ctx.stroke();
|
||||
ctx.fill();
|
||||
// ctx.strokeStyle = renderOptions["colorLine"][0];
|
||||
// ctx.beginPath();
|
||||
}
|
||||
}
|
||||
}
|
||||
prevX = x*zoomFactor;
|
||||
prevY = y*zoomFactor;
|
||||
}
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
|
||||
// ***** PUBLIC *******
|
||||
return {
|
||||
init: function(){
|
||||
startCanvas();
|
||||
initialized = true;
|
||||
ctx.translate(10,gridSizeY*zoomFactor+20);
|
||||
},
|
||||
setOption: function(options){
|
||||
for(var opt in options){
|
||||
if(options.hasOwnProperty(opt))renderOptions[opt] = options[opt];
|
||||
};
|
||||
|
||||
if(initialized)reRender();
|
||||
},
|
||||
getOptions: function(){
|
||||
return renderOptions;
|
||||
},
|
||||
debugGetModel: function(){
|
||||
return model;
|
||||
},
|
||||
render: function(layerNum, fromProgress, toProgress){
|
||||
if(!initialized)this.init();
|
||||
if(!model){
|
||||
drawGrid();
|
||||
}else{
|
||||
if(layerNum < model.length){
|
||||
var p1 = ctx.transformedPoint(0,0);
|
||||
var p2 = ctx.transformedPoint(canvas.width,canvas.height);
|
||||
ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);
|
||||
drawGrid();
|
||||
// ctx.globalAlpha = 0.5;
|
||||
if(renderOptions['showNextLayer'] && layerNum < model.length - 1) {
|
||||
drawLayer(layerNum+1, 0, this.getLayerNumSegments(layerNum+1), true);
|
||||
}
|
||||
drawLayer(layerNum, fromProgress, toProgress);
|
||||
}else{
|
||||
console.log("Got request to render non-existent layer!!");
|
||||
}
|
||||
}
|
||||
},
|
||||
getModelNumLayers: function(){
|
||||
return model?model.length:1;
|
||||
},
|
||||
getLayerNumSegments: function(layer){
|
||||
if(model){
|
||||
return model[layer]?model[layer].length:1;
|
||||
}else{
|
||||
return 1;
|
||||
}
|
||||
},
|
||||
doRender: function(mdl, layerNum){
|
||||
var mdlInfo;
|
||||
model = mdl;
|
||||
prevX=0;
|
||||
prevY=0;
|
||||
if(!initialized)this.init();
|
||||
|
||||
mdlInfo = GCODE.gCodeReader.getModelInfo();
|
||||
speeds = mdlInfo.speeds;
|
||||
speedsByLayer = mdlInfo.speedsByLayer;
|
||||
// console.log(speeds);
|
||||
// console.log(mdlInfo.min.x + ' ' + mdlInfo.modelSize.x);
|
||||
offsetModelX = (gridSizeX/2-(mdlInfo.min.x+mdlInfo.modelSize.x/2))*zoomFactor;
|
||||
offsetModelY = (mdlInfo.min.y+mdlInfo.modelSize.y/2)*zoomFactor-gridSizeY/2*zoomFactor;
|
||||
if(ctx)ctx.translate(offsetModelX, offsetModelY);
|
||||
|
||||
this.render(layerNum, 0, model[layerNum].length);
|
||||
},
|
||||
getZ: function(layerNum){
|
||||
if(!model&&!model[layerNum]){
|
||||
return '-1';
|
||||
}
|
||||
var cmds = model[layerNum];
|
||||
for(var i=0;i<cmds.length;i++){
|
||||
if(cmds[i].prevZ!==undefined)return cmds[i].prevZ;
|
||||
}
|
||||
return '-1';
|
||||
}
|
||||
|
||||
}
|
||||
}());
|
||||
@@ -1,345 +0,0 @@
|
||||
/**
|
||||
* User: hudbrog (hudbrog@gmail.com)
|
||||
* Date: 10/21/12
|
||||
* Time: 7:45 AM
|
||||
*/
|
||||
|
||||
var GCODE = {};
|
||||
|
||||
GCODE.ui = (function(){
|
||||
var reader;
|
||||
var myCodeMirror;
|
||||
var sliderVer;
|
||||
var sliderHor;
|
||||
var gCodeLines = {first: 0, last: 0};
|
||||
var showGCode = false;
|
||||
|
||||
var setProgress = function(id, progress){
|
||||
$('#'+id).width(parseInt(progress)+'%');
|
||||
$('#'+id).text(parseInt(progress)+'%');
|
||||
|
||||
};
|
||||
|
||||
var chooseAccordion = function(id){
|
||||
// debugger;
|
||||
$('#'+id).collapse("show");
|
||||
};
|
||||
|
||||
var setLinesColor = function(toggle){
|
||||
// var i=0;
|
||||
// for(i=gCodeLines.first;i<gCodeLines.last; i++){
|
||||
// if(toggle){
|
||||
// myCodeMirror.setLineClass(Number(i), null, "activeline");
|
||||
// }else{
|
||||
// myCodeMirror.setLineClass(Number(i), null, null);
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
var printLayerInfo = function(layerNum){
|
||||
var z = GCODE.renderer.getZ(layerNum);
|
||||
var segments = GCODE.renderer.getLayerNumSegments(layerNum);
|
||||
var filament = GCODE.gCodeReader.getLayerFilament(z);
|
||||
var layerSpeeds = GCODE.gCodeReader.getModelInfo().speedsByLayer;
|
||||
var renderOptions = GCODE.renderer.getOptions();
|
||||
var colors = renderOptions["colorLine"];
|
||||
var speedIndex = 0;
|
||||
var keys, type;
|
||||
var showMove=false;
|
||||
var i = 0;
|
||||
var output = [];
|
||||
output.push("Layer number: " + layerNum);
|
||||
output.push("Layer height (mm): " + z);
|
||||
output.push("GCODE commands in layer: " + segments);
|
||||
output.push("Filament used by layer (mm): " + filament.toFixed(2));
|
||||
output.push("Print time for layer: " + parseFloat(GCODE.gCodeReader.getModelInfo().printTimeByLayer[z]).toFixed(1) + "sec");
|
||||
output.push("Extrude speeds:");
|
||||
for(i=0;i<layerSpeeds['extrude'][z].length;i++){
|
||||
if(typeof(layerSpeeds['extrude'][z][i])==='undefined'){continue;}
|
||||
speedIndex = i;
|
||||
if(speedIndex > colors.length -1){speedIndex = speedIndex % (colors.length-1);}
|
||||
output.push("<div id='colorBox"+i+"' class='colorBox' style='background-color: "+colors[speedIndex] + "'></div> = " + (parseFloat(layerSpeeds['extrude'][z][i])/60).toFixed(2)+"mm/s");
|
||||
}
|
||||
if(typeof(layerSpeeds['move'][z]) !== 'undefined'){
|
||||
output.push("Move speeds:");
|
||||
for(i=0;i<layerSpeeds['move'][z].length;i++){
|
||||
if(typeof(layerSpeeds['move'][z][i])==='undefined'){continue;}
|
||||
speedIndex = i;
|
||||
if(speedIndex > colors.length -1){speedIndex = speedIndex % (colors.length-1);}
|
||||
output.push("<div id='colorBox"+i+"' class='colorBox' style='background-color: "+renderOptions['colorMove'] + "'></div> = " + (parseFloat(layerSpeeds['move'][z][i])/60).toFixed(2)+"mm/s");
|
||||
}
|
||||
}
|
||||
if(typeof(layerSpeeds['retract'][z]) !== 'undefined'){
|
||||
output.push("Retract speeds:");
|
||||
for(i=0;i<layerSpeeds['retract'][z].length;i++){
|
||||
if(typeof(layerSpeeds['retract'][z][i])==='undefined'){continue;}
|
||||
speedIndex = i;
|
||||
if(speedIndex > colors.length -1){speedIndex = speedIndex % (colors.length-1);}
|
||||
output.push("<span style='color: " + renderOptions['colorRetract'] +"'>●</span> <span style='color: " + renderOptions['colorRestart'] +"'>●</span> = " +(parseFloat(layerSpeeds['retract'][z][i])/60).toFixed(2)+"mm/s");
|
||||
}
|
||||
}
|
||||
|
||||
$('#layerInfo').html(output.join('<br>'));
|
||||
// chooseAccordion('layerAccordionTab');
|
||||
};
|
||||
|
||||
var handleFileSelect = function(evt) {
|
||||
// console.log("handleFileSelect");
|
||||
evt.stopPropagation();
|
||||
evt.preventDefault();
|
||||
|
||||
var files = evt.dataTransfer?evt.dataTransfer.files:evt.target.files; // FileList object.
|
||||
|
||||
var output = [];
|
||||
for (var i = 0, f; f = files[i]; i++) {
|
||||
if(f.name.toLowerCase().match(/^.*\.(?:gcode|g|txt)$/)){
|
||||
output.push('<li>File extensions suggests GCODE</li>');
|
||||
}else{
|
||||
output.push('<li><strong>You should only upload *.gcode files! I will not work with this one!</strong></li>');
|
||||
document.getElementById('errorList').innerHTML = '<ul>' + output.join('') + '</ul>';
|
||||
return;
|
||||
}
|
||||
|
||||
reader = new FileReader();
|
||||
reader.onload = function(theFile){
|
||||
chooseAccordion('progressAccordionTab');
|
||||
setProgress('loadProgress', 0);
|
||||
setProgress('analyzeProgress', 0);
|
||||
// myCodeMirror.setValue(theFile.target.result);
|
||||
GCODE.gCodeReader.loadFile(theFile);
|
||||
if(showGCode){
|
||||
myCodeMirror.setValue(theFile.target.result);
|
||||
}else{
|
||||
myCodeMirror.setValue("GCode view is disabled. You can enable it in 'GCode analyzer options' section.")
|
||||
}
|
||||
|
||||
};
|
||||
reader.readAsText(f);
|
||||
}
|
||||
};
|
||||
|
||||
var handleDragOver = function(evt) {
|
||||
evt.stopPropagation();
|
||||
evt.preventDefault();
|
||||
evt.target.dropEffect = 'copy'; // Explicitly show this is a copy.
|
||||
};
|
||||
|
||||
var initSliders = function(){
|
||||
var prevX=0;
|
||||
var prevY=0;
|
||||
var handle;
|
||||
sliderVer = $( "#slider-vertical" );
|
||||
sliderHor = $( "#slider-horizontal" );
|
||||
|
||||
var onLayerChange = function(val){
|
||||
var progress = GCODE.renderer.getLayerNumSegments(val)-1;
|
||||
GCODE.renderer.render(val,0, progress);
|
||||
sliderHor.slider({max: progress, values: [0,progress]});
|
||||
setLinesColor(false); //clear current selection
|
||||
gCodeLines = GCODE.gCodeReader.getGCodeLines(val, sliderHor.slider("values",0), sliderHor.slider("values",1));
|
||||
setLinesColor(true); // highlight lines
|
||||
printLayerInfo(val);
|
||||
};
|
||||
|
||||
sliderVer.slider({
|
||||
orientation: "vertical",
|
||||
range: "min",
|
||||
min: 0,
|
||||
max: GCODE.renderer.getModelNumLayers()-1,
|
||||
value: 0,
|
||||
slide: function( event, ui ) {
|
||||
onLayerChange(ui.value);
|
||||
}
|
||||
});
|
||||
|
||||
//this stops slider reacting to arrow keys, since we do it below manually
|
||||
$( "#slider-vertical .ui-slider-handle" ).unbind('keydown');
|
||||
|
||||
sliderHor.slider({
|
||||
orientation: "horizontal",
|
||||
range: "min",
|
||||
min: 0,
|
||||
max: GCODE.renderer.getLayerNumSegments(0)-1,
|
||||
values: [0,GCODE.renderer.getLayerNumSegments(0)-1],
|
||||
slide: function( event, ui ) {
|
||||
setLinesColor(false); //clear current selection
|
||||
gCodeLines = GCODE.gCodeReader.getGCodeLines(sliderVer.slider("value"),ui.values[0], ui.values[1]);
|
||||
setLinesColor(true); // highlight lines
|
||||
GCODE.renderer.render(sliderVer.slider("value"), ui.values[0], ui.values[1]);
|
||||
}
|
||||
});
|
||||
|
||||
window.onkeydown = function (event){
|
||||
if(event.keyCode === 38 || event.keyCode === 33){
|
||||
if(sliderVer.slider('value') < sliderVer.slider('option', 'max')){
|
||||
sliderVer.slider('value', sliderVer.slider('value')+1);
|
||||
onLayerChange(sliderVer.slider('value'));
|
||||
}
|
||||
}else if(event.keyCode === 40 || event.keyCode === 34){
|
||||
if(sliderVer.slider('value') > 0){
|
||||
sliderVer.slider('value', sliderVer.slider('value')-1);
|
||||
onLayerChange(sliderVer.slider('value'));
|
||||
}
|
||||
}
|
||||
event.stopPropagation()
|
||||
}
|
||||
};
|
||||
|
||||
var processMessage = function(e){
|
||||
var data = e.data;
|
||||
switch (data.cmd) {
|
||||
case 'returnModel':
|
||||
setProgress('loadProgress', 100);
|
||||
worker.postMessage({
|
||||
"cmd":"analyzeModel",
|
||||
"msg":{
|
||||
}
|
||||
}
|
||||
);
|
||||
break;
|
||||
case 'analyzeDone':
|
||||
var resultSet = [];
|
||||
|
||||
setProgress('analyzeProgress',100);
|
||||
GCODE.gCodeReader.processAnalyzeModelDone(data.msg);
|
||||
GCODE.gCodeReader.passDataToRenderer();
|
||||
initSliders();
|
||||
resultSet.push("Model size is: " + data.msg.modelSize.x.toFixed(2) + 'x' + data.msg.modelSize.y.toFixed(2) + 'x' + data.msg.modelSize.z.toFixed(2)+'mm<br>');
|
||||
resultSet.push("Total filament used: " + data.msg.totalFilament.toFixed(2) + "mm<br>");
|
||||
resultSet.push("Estimated print time: " + parseInt(parseFloat(data.msg.printTime)/60/60) + ":" + parseInt((parseFloat(data.msg.printTime)/60)%60) + ":" + parseInt(parseFloat(data.msg.printTime)%60) + "<br>");
|
||||
resultSet.push("Estimated layer height: " + data.msg.layerHeight.toFixed(2) + "mm<br>");
|
||||
resultSet.push("Layer count: " + data.msg.layerCnt.toFixed(0) + "printed, " + data.msg.layerTotal.toFixed(0) + 'visited<br>');
|
||||
document.getElementById('list').innerHTML = resultSet.join('');
|
||||
chooseAccordion('infoAccordionTab');
|
||||
$('#myTab a[href="#tab2d"]').tab('show');
|
||||
break;
|
||||
case 'returnLayer':
|
||||
GCODE.gCodeReader.processLayerFromWorker(data.msg);
|
||||
setProgress('loadProgress',data.msg.progress);
|
||||
break;
|
||||
case 'returnMultiLayer':
|
||||
GCODE.gCodeReader.processMultiLayerFromWorker(data.msg);
|
||||
setProgress('loadProgress',data.msg.progress);
|
||||
break;
|
||||
case "analyzeProgress":
|
||||
setProgress('analyzeProgress',data.msg.progress);
|
||||
break;
|
||||
default:
|
||||
console.log("default msg received" + data.cmd);
|
||||
}
|
||||
};
|
||||
|
||||
var checkCapabilities = function(){
|
||||
var warnings = [];
|
||||
var fatal = [];
|
||||
|
||||
Modernizr.addTest('filereader', function () {
|
||||
return !!(window.File && window.FileList && window.FileReader);
|
||||
});
|
||||
|
||||
if(!Modernizr.canvas)fatal.push("<li>Your browser doesn't seem to support HTML5 Canvas, this application won't work without it.</li>");
|
||||
//if(!Modernizr.filereader)fatal.push("<li>Your browser doesn't seem to support HTML5 File API, this application won't work without it.</li>");
|
||||
if(!Modernizr.webworkers)fatal.push("<li>Your browser doesn't seem to support HTML5 Web Workers, this application won't work without it.</li>");
|
||||
if(!Modernizr.svg)fatal.push("<li>Your browser doesn't seem to support HTML5 SVG, this application won't work without it.</li>");
|
||||
|
||||
if(fatal.length>0){
|
||||
document.getElementById('errorList').innerHTML = '<ul>' + fatal.join('') + '</ul>';
|
||||
console.log("Initialization failed: unsupported browser.")
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!Modernizr.webgl && GCODE.renderer3d){
|
||||
warnings.push("<li>Your browser doesn't seem to support HTML5 Web GL, 3d mode is not recommended, going to be SLOW!</li>");
|
||||
GCODE.renderer3d.setOption({rendererType: "canvas"});
|
||||
}
|
||||
if(!Modernizr.draganddrop)warnings.push("<li>Your browser doesn't seem to support HTML5 Drag'n'Drop, Drop area will not work.</li>");
|
||||
|
||||
if(warnings.length>0){
|
||||
document.getElementById('errorList').innerHTML = '<ul>' + wanings.join('') + '</ul>';
|
||||
console.log("Initialization succeeded with warnings.")
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
return {
|
||||
worker: undefined,
|
||||
initHandlers: function(){
|
||||
var capabilitiesResult = checkCapabilities();
|
||||
if(!capabilitiesResult){
|
||||
return;
|
||||
}
|
||||
|
||||
setProgress('loadProgress', 0);
|
||||
setProgress('analyzeProgress', 0);
|
||||
|
||||
worker = new Worker('static/gcodeviewer/js/Worker.js');
|
||||
|
||||
worker.addEventListener('message', processMessage, false);
|
||||
|
||||
GCODE.ui.processOptions();
|
||||
GCODE.renderer.render(0,0);
|
||||
|
||||
console.log("Application initialized");
|
||||
|
||||
},
|
||||
|
||||
ArrayIndexOf: function(a, fnc) {
|
||||
if (!fnc || typeof (fnc) != 'function') {
|
||||
return -1;
|
||||
}
|
||||
if (!a || !a.length || a.length < 1) return -1;
|
||||
for (var i = 0; i < a.length; i++) {
|
||||
if(!a[i]) continue;
|
||||
if (fnc(a[i])) return i;
|
||||
}
|
||||
return -1;
|
||||
},
|
||||
updateLayerInfo: function(layerNum){
|
||||
printLayerInfo(layerNum);
|
||||
},
|
||||
|
||||
processOptions: function(){
|
||||
if(document.getElementById('sortLayersCheckbox').checked)GCODE.gCodeReader.setOption({sortLayers: true});
|
||||
else GCODE.gCodeReader.setOption({sortLayers: false});
|
||||
|
||||
if(document.getElementById('purgeEmptyLayersCheckbox').checked)GCODE.gCodeReader.setOption({purgeEmptyLayers: true});
|
||||
else GCODE.gCodeReader.setOption({purgeEmptyLayers: false});
|
||||
|
||||
if(document.getElementById('showGCodeCheckbox').checked)showGCode = true;
|
||||
else showGCode = false;
|
||||
|
||||
|
||||
// if(document.getElementById('sortLayersCheckbox').checked) worker.postMessage({"cmd":"setOption", "msg":{sortLayers: true}});
|
||||
// else worker.postMessage({"cmd":"setOption", "msg":{sortLayers: false}});
|
||||
//
|
||||
// if(document.getElementById('purgeEmptyLayersCheckbox').checked)worker.postMessage({"cmd":"setOption", "msg":{purgeEmptyLayers: true}});
|
||||
// else worker.postMessage({"cmd":"setOption", "msg":{purgeEmptyLayers: false}});
|
||||
|
||||
// if(document.getElementById('analyzeModelCheckbox').checked)worker.postMessage({"cmd":"setOption", "msg":{analyzeModel: true}});
|
||||
// else worker.postMessage({"cmd":"setOption", "msg":{analyzeModel: false}});
|
||||
|
||||
|
||||
if(document.getElementById('moveModelCheckbox').checked)GCODE.renderer.setOption({moveModel: true});
|
||||
else GCODE.renderer.setOption({moveModel: false});
|
||||
|
||||
if(document.getElementById('showMovesCheckbox').checked)GCODE.renderer.setOption({showMoves: true});
|
||||
else GCODE.renderer.setOption({showMoves: false});
|
||||
|
||||
if(document.getElementById('showRetractsCheckbox').checked)GCODE.renderer.setOption({showRetracts: true});
|
||||
else GCODE.renderer.setOption({showRetracts: false});
|
||||
|
||||
if(document.getElementById('differentiateColorsCheckbox').checked)GCODE.renderer.setOption({differentiateColors: true});
|
||||
else GCODE.renderer.setOption({differentiateColors: false});
|
||||
|
||||
var widthMod = 2;
|
||||
if(Number($('#widthModifier').attr('value'))) {widthMod = Number($('#widthModifier').attr('value'));}
|
||||
if(document.getElementById('thickExtrusionCheckbox').checked)GCODE.renderer.setOption({extrusionWidth: widthMod});
|
||||
else GCODE.renderer.setOption({extrusionWidth: 1});
|
||||
|
||||
if(document.getElementById('showNextLayer').checked)GCODE.renderer.setOption({showNextLayer: true});
|
||||
else GCODE.renderer.setOption({showNextLayer: false});
|
||||
}
|
||||
}
|
||||
}());
|
||||
@@ -1,123 +0,0 @@
|
||||
function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewModel, temperatureViewModel, controlViewModel, terminalViewModel, gcodeFilesViewModel, timelapseViewModel, gcodeViewModel) {
|
||||
var self = this;
|
||||
|
||||
self.loginStateViewModel = loginStateViewModel;
|
||||
self.connectionViewModel = connectionViewModel;
|
||||
self.printerStateViewModel = printerStateViewModel;
|
||||
self.temperatureViewModel = temperatureViewModel;
|
||||
self.controlViewModel = controlViewModel;
|
||||
self.terminalViewModel = terminalViewModel;
|
||||
self.gcodeFilesViewModel = gcodeFilesViewModel;
|
||||
self.timelapseViewModel = timelapseViewModel;
|
||||
self.gcodeViewModel = gcodeViewModel;
|
||||
|
||||
self._socket = undefined;
|
||||
self._autoReconnecting = false;
|
||||
self._autoReconnectTrial = 0;
|
||||
self._autoReconnectTimeouts = [1, 1, 2, 3, 5, 8, 13, 20, 40, 100];
|
||||
|
||||
self.connect = function() {
|
||||
var options = {};
|
||||
if (SOCKJS_DEBUG) {
|
||||
options["debug"] = true;
|
||||
}
|
||||
|
||||
self._socket = new SockJS(SOCKJS_URI, undefined, options);
|
||||
self._socket.onopen = self._onconnect;
|
||||
self._socket.onclose = self._onclose;
|
||||
self._socket.onmessage = self._onmessage;
|
||||
}
|
||||
|
||||
self.reconnect = function() {
|
||||
delete self._socket;
|
||||
self.connect();
|
||||
}
|
||||
|
||||
self._onconnect = function() {
|
||||
self._autoReconnecting = false;
|
||||
self._autoReconnectTrial = 0;
|
||||
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
$("#offline_overlay").hide();
|
||||
self.timelapseViewModel.requestData();
|
||||
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
|
||||
self.loginStateViewModel.requestData();
|
||||
self.gcodeFilesViewModel.requestData();
|
||||
}
|
||||
}
|
||||
|
||||
self._onclose = function() {
|
||||
$("#offline_overlay_message").html(
|
||||
"The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect " +
|
||||
"automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect " +
|
||||
"anytime using the button below."
|
||||
);
|
||||
if (!$("#offline_overlay").is(":visible"))
|
||||
$("#offline_overlay").show();
|
||||
|
||||
if (self._autoReconnectTrial < self._autoReconnectTimeouts.length) {
|
||||
var timeout = self._autoReconnectTimeouts[self._autoReconnectTrial];
|
||||
console.log("Reconnect trial #" + self._autoReconnectTrial + ", waiting " + timeout + "s");
|
||||
setTimeout(self.reconnect, timeout * 1000);
|
||||
self._autoReconnectTrial++;
|
||||
} else {
|
||||
self._onreconnectfailed();
|
||||
}
|
||||
}
|
||||
|
||||
self._onreconnectfailed = function() {
|
||||
$("#offline_overlay_message").html(
|
||||
"The server appears to be offline, at least I'm not getting any response from it. I <strong>could not reconnect automatically</strong>, " +
|
||||
"but you may try a manual reconnect using the button below."
|
||||
);
|
||||
}
|
||||
|
||||
self._onmessage = function(e) {
|
||||
for (var prop in e.data) {
|
||||
var payload = e.data[prop];
|
||||
|
||||
switch (prop) {
|
||||
case "history": {
|
||||
self.connectionViewModel.fromHistoryData(payload);
|
||||
self.printerStateViewModel.fromHistoryData(payload);
|
||||
self.temperatureViewModel.fromHistoryData(payload);
|
||||
self.controlViewModel.fromHistoryData(payload);
|
||||
self.terminalViewModel.fromHistoryData(payload);
|
||||
self.timelapseViewModel.fromHistoryData(payload);
|
||||
self.gcodeViewModel.fromHistoryData(payload);
|
||||
self.gcodeFilesViewModel.fromCurrentData(payload);
|
||||
break;
|
||||
}
|
||||
case "current": {
|
||||
self.connectionViewModel.fromCurrentData(payload);
|
||||
self.printerStateViewModel.fromCurrentData(payload);
|
||||
self.temperatureViewModel.fromCurrentData(payload);
|
||||
self.controlViewModel.fromCurrentData(payload);
|
||||
self.terminalViewModel.fromCurrentData(payload);
|
||||
self.timelapseViewModel.fromCurrentData(payload);
|
||||
self.gcodeViewModel.fromCurrentData(payload);
|
||||
self.gcodeFilesViewModel.fromCurrentData(payload);
|
||||
break;
|
||||
}
|
||||
case "updateTrigger": {
|
||||
if (payload == "gcodeFiles") {
|
||||
gcodeFilesViewModel.requestData();
|
||||
} else if (payload == "timelapseFiles") {
|
||||
timelapseViewModel.requestData();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "feedbackCommandOutput": {
|
||||
self.controlViewModel.fromFeedbackCommandData(payload);
|
||||
break;
|
||||
}
|
||||
case "timelapse": {
|
||||
self.printerStateViewModel.fromTimelapseData(payload);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.connect();
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
function GcodeViewModel(loginStateViewModel) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
|
||||
self.loadedFilename = undefined;
|
||||
self.loadedFileMTime = undefined;
|
||||
self.status = 'idle';
|
||||
self.enabled = false;
|
||||
|
||||
self.errorCount = 0;
|
||||
|
||||
self.initialize = function(){
|
||||
self.enabled = true;
|
||||
GCODE.ui.initHandlers();
|
||||
}
|
||||
|
||||
self.loadFile = function(filename, mtime){
|
||||
if (self.status == 'idle' && self.errorCount < 3) {
|
||||
self.status = 'request';
|
||||
$.ajax({
|
||||
url: "/downloads/gcode/" + filename,
|
||||
data: { "mtime": mtime },
|
||||
type: "GET",
|
||||
success: function(response, rstatus) {
|
||||
if(rstatus === 'success'){
|
||||
self.showGCodeViewer(response, rstatus);
|
||||
self.loadedFilename=filename;
|
||||
self.loadedFileMTime=mtime;
|
||||
self.status = 'idle';
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
self.status = 'idle';
|
||||
self.errorCount++;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
self.showGCodeViewer = function(response, rstatus) {
|
||||
var par = {};
|
||||
par.target = {};
|
||||
par.target.result = response;
|
||||
GCODE.gCodeReader.loadFile(par);
|
||||
}
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processData(data);
|
||||
}
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processData(data);
|
||||
}
|
||||
|
||||
self._processData = function(data) {
|
||||
if (!self.enabled) return;
|
||||
if (!data.job.filename) return;
|
||||
|
||||
if(self.loadedFilename && self.loadedFilename == data.job.filename &&
|
||||
self.loadedFileMTime == data.job.mtime) {
|
||||
if (data.state.flags && (data.state.flags.printing || data.state.flags.paused)) {
|
||||
var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(data.progress.progress * 100);
|
||||
if(cmdIndex){
|
||||
GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd);
|
||||
GCODE.ui.updateLayerInfo(cmdIndex.layer);
|
||||
}
|
||||
}
|
||||
self.errorCount = 0
|
||||
} else if (data.job.filename) {
|
||||
self.loadFile(data.job.filename, data.job.mtime);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
function TemperatureViewModel(loginStateViewModel, settingsViewModel) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
|
||||
self.temp = ko.observable(undefined);
|
||||
self.bedTemp = ko.observable(undefined);
|
||||
self.targetTemp = ko.observable(undefined);
|
||||
self.bedTargetTemp = ko.observable(undefined);
|
||||
|
||||
self.newTemp = ko.observable(undefined);
|
||||
self.newBedTemp = ko.observable(undefined);
|
||||
|
||||
self.newTempOffset = ko.observable(undefined);
|
||||
self.tempOffset = ko.observable(0);
|
||||
self.newBedTempOffset = ko.observable(undefined);
|
||||
self.bedTempOffset = ko.observable(0);
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.temperature_profiles = settingsViewModel.temperature_profiles;
|
||||
|
||||
self.tempString = ko.computed(function() {
|
||||
if (!self.temp())
|
||||
return "-";
|
||||
return self.temp() + " °C";
|
||||
});
|
||||
self.bedTempString = ko.computed(function() {
|
||||
if (!self.bedTemp())
|
||||
return "-";
|
||||
return self.bedTemp() + " °C";
|
||||
});
|
||||
self.targetTempString = ko.computed(function() {
|
||||
if (!self.targetTemp())
|
||||
return "-";
|
||||
return self.targetTemp() + " °C";
|
||||
});
|
||||
self.bedTargetTempString = ko.computed(function() {
|
||||
if (!self.bedTargetTemp())
|
||||
return "-";
|
||||
return self.bedTargetTemp() + " °C";
|
||||
});
|
||||
|
||||
self.temperatures = [];
|
||||
self.plotOptions = {
|
||||
yaxis: {
|
||||
min: 0,
|
||||
max: 310,
|
||||
ticks: 10
|
||||
},
|
||||
xaxis: {
|
||||
mode: "time",
|
||||
minTickSize: [2, "minute"],
|
||||
tickFormatter: function(val, axis) {
|
||||
if (val == undefined || val == 0)
|
||||
return ""; // we don't want to display the minutes since the epoch if not connected yet ;)
|
||||
|
||||
// current time in milliseconds in UTC
|
||||
var timestampUtc = Date.now();
|
||||
|
||||
// calculate difference in milliseconds
|
||||
var diff = timestampUtc - val;
|
||||
|
||||
// convert to minutes
|
||||
var diffInMins = Math.round(diff / (60 * 1000));
|
||||
if (diffInMins == 0)
|
||||
return "just now";
|
||||
else
|
||||
return "- " + diffInMins + " min";
|
||||
}
|
||||
},
|
||||
legend: {
|
||||
noColumns: 4
|
||||
}
|
||||
}
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processTemperatureUpdateData(data.temperatures);
|
||||
self._processOffsetData(data.offsets);
|
||||
}
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processTemperatureHistoryData(data.temperatureHistory);
|
||||
self._processOffsetData(data.offsets);
|
||||
}
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
}
|
||||
|
||||
self._processTemperatureUpdateData = function(data) {
|
||||
if (data.length == 0)
|
||||
return;
|
||||
|
||||
self.temp(data[data.length - 1].temp);
|
||||
self.bedTemp(data[data.length - 1].bedTemp);
|
||||
self.targetTemp(data[data.length - 1].targetTemp);
|
||||
self.bedTargetTemp(data[data.length - 1].targetBedTemp);
|
||||
|
||||
if (!CONFIG_TEMPERATURE_GRAPH) return;
|
||||
|
||||
if (!self.temperatures)
|
||||
self.temperatures = [];
|
||||
if (!self.temperatures.actual)
|
||||
self.temperatures.actual = [];
|
||||
if (!self.temperatures.target)
|
||||
self.temperatures.target = [];
|
||||
if (!self.temperatures.actualBed)
|
||||
self.temperatures.actualBed = [];
|
||||
if (!self.temperatures.targetBed)
|
||||
self.temperatures.targetBed = [];
|
||||
|
||||
_.each(data, function(d) {
|
||||
var time = d.currentTime;
|
||||
self.temperatures.actual.push([time, d.temp]);
|
||||
self.temperatures.target.push([time, d.targetTemp]);
|
||||
self.temperatures.actualBed.push([time, d.bedTemp]);
|
||||
self.temperatures.targetBed.push([time, d.targetBedTemp]);
|
||||
});
|
||||
|
||||
self.temperatures.actual = self.temperatures.actual.slice(-300);
|
||||
self.temperatures.target = self.temperatures.target.slice(-300);
|
||||
self.temperatures.actualBed = self.temperatures.actualBed.slice(-300);
|
||||
self.temperatures.targetBed = self.temperatures.targetBed.slice(-300);
|
||||
|
||||
self.updatePlot();
|
||||
}
|
||||
|
||||
self._processTemperatureHistoryData = function(data) {
|
||||
self.temperatures = data;
|
||||
self.updatePlot();
|
||||
}
|
||||
|
||||
self._processOffsetData = function(data) {
|
||||
self.tempOffset(data[0]);
|
||||
self.bedTempOffset(data[1]);
|
||||
}
|
||||
|
||||
self.updatePlot = function() {
|
||||
var graph = $("#temperature-graph");
|
||||
if (graph.length) {
|
||||
var data = [
|
||||
{label: "Actual", color: "#FF4040", data: self.temperatures.actual},
|
||||
{label: "Target", color: "#FFA0A0", data: self.temperatures.target},
|
||||
{label: "Bed Actual", color: "#4040FF", data: self.temperatures.actualBed},
|
||||
{label: "Bed Target", color: "#A0A0FF", data: self.temperatures.targetBed}
|
||||
]
|
||||
|
||||
$.plot(graph, data, self.plotOptions);
|
||||
}
|
||||
}
|
||||
|
||||
self.setTempFromProfile = function(profile) {
|
||||
if (!profile)
|
||||
return;
|
||||
self._updateTemperature(profile.extruder, "temp");
|
||||
}
|
||||
|
||||
self.setTemp = function() {
|
||||
self._updateTemperature(self.newTemp(), "temp", function(){self.targetTemp(self.newTemp()); self.newTemp("");});
|
||||
};
|
||||
|
||||
self.setTempToZero = function() {
|
||||
self._updateTemperature(0, "temp", function(){self.targetTemp(0); self.newTemp("");});
|
||||
}
|
||||
|
||||
self.setTempOffset = function() {
|
||||
self._updateTemperature(self.newTempOffset(), "tempOffset", function() {self.tempOffset(self.newTempOffset()); self.newTempOffset("");});
|
||||
}
|
||||
|
||||
self.setBedTempFromProfile = function(profile) {
|
||||
self._updateTemperature(profile.bed, "bedTemp");
|
||||
}
|
||||
|
||||
self.setBedTemp = function() {
|
||||
self._updateTemperature(self.newBedTemp(), "bedTemp", function() {self.bedTargetTemp(self.newBedTemp()); self.newBedTemp("");});
|
||||
};
|
||||
|
||||
self.setBedTempToZero = function() {
|
||||
self._updateTemperature(0, "bedTemp", function() {self.bedTargetTemp(0); self.newBedTemp("");});
|
||||
}
|
||||
|
||||
self.setBedTempOffset = function() {
|
||||
self._updateTemperature(self.newBedTempOffset(), "bedTempOffset", function() {self.bedTempOffset(self.newBedTempOffset()); self.newBedTempOffset("");});
|
||||
}
|
||||
|
||||
self._updateTemperature = function(temp, type, callback) {
|
||||
var data = {};
|
||||
data[type] = temp;
|
||||
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/temperature",
|
||||
type: "POST",
|
||||
data: data,
|
||||
success: function() { if (callback !== undefined) callback(); }
|
||||
});
|
||||
}
|
||||
|
||||
self.handleEnter = function(event, type) {
|
||||
if (event.keyCode == 13) {
|
||||
if (type == "temp") {
|
||||
self.setTemp();
|
||||
} else if (type == "bedTemp") {
|
||||
self.setBedTemp();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,d=e.filter,g=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,_=Object.keys,j=i.bind,w=function(n){return n instanceof w?n:this instanceof w?(this._wrapped=n,void 0):new w(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=w),exports._=w):n._=w,w.VERSION="1.4.4";var A=w.each=w.forEach=function(n,t,e){if(null!=n)if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a in n)if(w.has(n,a)&&t.call(e,n[a],a,n)===r)return};w.map=w.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e[e.length]=t.call(r,n,u,i)}),e)};var O="Reduce of empty array with no initial value";w.reduce=w.foldl=w.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=w.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(O);return r},w.reduceRight=w.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=w.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=w.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(O);return r},w.find=w.detect=function(n,t,r){var e;return E(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},w.filter=w.select=function(n,t,r){var e=[];return null==n?e:d&&n.filter===d?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&(e[e.length]=n)}),e)},w.reject=function(n,t,r){return w.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},w.every=w.all=function(n,t,e){t||(t=w.identity);var u=!0;return null==n?u:g&&n.every===g?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var E=w.some=w.any=function(n,t,e){t||(t=w.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};w.contains=w.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:E(n,function(n){return n===t})},w.invoke=function(n,t){var r=o.call(arguments,2),e=w.isFunction(t);return w.map(n,function(n){return(e?t:n[t]).apply(n,r)})},w.pluck=function(n,t){return w.map(n,function(n){return n[t]})},w.where=function(n,t,r){return w.isEmpty(t)?r?null:[]:w[r?"find":"filter"](n,function(n){for(var r in t)if(t[r]!==n[r])return!1;return!0})},w.findWhere=function(n,t){return w.where(n,t,!0)},w.max=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.max.apply(Math,n);if(!t&&w.isEmpty(n))return-1/0;var e={computed:-1/0,value:-1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a>=e.computed&&(e={value:n,computed:a})}),e.value},w.min=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.min.apply(Math,n);if(!t&&w.isEmpty(n))return 1/0;var e={computed:1/0,value:1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;e.computed>a&&(e={value:n,computed:a})}),e.value},w.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=w.random(r++),e[r-1]=e[t],e[t]=n}),e};var k=function(n){return w.isFunction(n)?n:function(t){return t[n]}};w.sortBy=function(n,t,r){var e=k(t);return w.pluck(w.map(n,function(n,t,u){return{value:n,index:t,criteria:e.call(r,n,t,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index<t.index?-1:1}),"value")};var F=function(n,t,r,e){var u={},i=k(t||w.identity);return A(n,function(t,a){var o=i.call(r,t,a,n);e(u,o,t)}),u};w.groupBy=function(n,t,r){return F(n,t,r,function(n,t,r){(w.has(n,t)?n[t]:n[t]=[]).push(r)})},w.countBy=function(n,t,r){return F(n,t,r,function(n,t){w.has(n,t)||(n[t]=0),n[t]++})},w.sortedIndex=function(n,t,r,e){r=null==r?w.identity:k(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;u>r.call(e,n[o])?i=o+1:a=o}return i},w.toArray=function(n){return n?w.isArray(n)?o.call(n):n.length===+n.length?w.map(n,w.identity):w.values(n):[]},w.size=function(n){return null==n?0:n.length===+n.length?n.length:w.keys(n).length},w.first=w.head=w.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:o.call(n,0,t)},w.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},w.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},w.rest=w.tail=w.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},w.compact=function(n){return w.filter(n,w.identity)};var R=function(n,t,r){return A(n,function(n){w.isArray(n)?t?a.apply(r,n):R(n,t,r):r.push(n)}),r};w.flatten=function(n,t){return R(n,t,[])},w.without=function(n){return w.difference(n,o.call(arguments,1))},w.uniq=w.unique=function(n,t,r,e){w.isFuncLine truncated
|
||||
@@ -6,3 +6,8 @@ PyYAML==3.10
|
||||
Flask-Login==0.2.2
|
||||
Flask-Principal==0.3.5
|
||||
netaddr>=0.7.10
|
||||
mock>=1.0.1
|
||||
nose>=1.3.0
|
||||
|
||||
sphinxcontrib-httpdomain
|
||||
sphinx_rtd_theme
|
||||
@@ -5,6 +5,10 @@ sockjs-tornado>=1.0.0
|
||||
PyYAML==3.10
|
||||
Flask-Login==0.2.2
|
||||
Flask-Principal==0.3.5
|
||||
numpy>=1.6.2
|
||||
pyserial>=2.6
|
||||
netaddr>=0.7.10
|
||||
mock>=1.0.1
|
||||
nose>=1.3.0
|
||||
|
||||
sphinxcontrib-httpdomain
|
||||
sphinx_rtd_theme
|
||||
@@ -1,65 +1,22 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import os
|
||||
import sys
|
||||
from octoprint.daemon import Daemon
|
||||
from octoprint.server import Server
|
||||
|
||||
class Main(Daemon):
|
||||
def __init__(self, pidfile, configfile, basedir, host, port, debug):
|
||||
Daemon.__init__(self, pidfile)
|
||||
basedir = os.path.dirname(os.path.realpath(__file__))
|
||||
|
||||
self._configfile = configfile
|
||||
self._basedir = basedir
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._debug = debug
|
||||
old = os.path.join(basedir, "octoprint")
|
||||
if os.path.exists(old):
|
||||
# rename left-overs from old file structure
|
||||
print """
|
||||
Found left-overs from old file structure, renaming to
|
||||
"octoprint.backup". Please remove this manually (I don't
|
||||
dare to do so myself since you might have changes in there
|
||||
I don't know anything about).
|
||||
"""
|
||||
os.rename(old, os.path.join(basedir, "octoprint.backup"))
|
||||
|
||||
def run(self):
|
||||
octoprint = Server(self._configfile, self._basedir, self._host, self._port, self._debug)
|
||||
octoprint.run()
|
||||
sys.path.insert(0, os.path.join(basedir, "src"))
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(prog="run")
|
||||
|
||||
parser.add_argument("-d", "--debug", action="store_true", dest="debug",
|
||||
help="Enable debug mode")
|
||||
|
||||
parser.add_argument("--host", action="store", type=str, dest="host",
|
||||
help="Specify the host on which to bind the server")
|
||||
parser.add_argument("--port", action="store", type=int, dest="port",
|
||||
help="Specify the port on which to bind the server")
|
||||
|
||||
parser.add_argument("-c", "--config", action="store", dest="config",
|
||||
help="Specify the config file to use. OctoPrint needs to have write access for the settings dialog to work. Defaults to ~/.octoprint/config.yaml")
|
||||
parser.add_argument("-b", "--basedir", action="store", dest="basedir",
|
||||
help="Specify the basedir to use for uploads, timelapses etc. OctoPrint needs to have write access. Defaults to ~/.octoprint")
|
||||
|
||||
parser.add_argument("--daemon", action="store", type=str, choices=["start", "stop", "restart"],
|
||||
help="Daemonize/control daemonized OctoPrint instance (only supported under Linux right now)")
|
||||
parser.add_argument("--pid", action="store", type=str, dest="pidfile", default="/tmp/octoprint.pid",
|
||||
help="Pidfile to use for daemonizing, defaults to /tmp/octoprint.pid")
|
||||
|
||||
parser.add_argument("--iknowwhatimdoing", action="store_true", dest="allowRoot",
|
||||
help="Allow OctoPrint to run as user root")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.daemon:
|
||||
if sys.platform == "darwin" or sys.platform == "win32":
|
||||
print >> sys.stderr, "Sorry, daemon mode is only supported under Linux right now"
|
||||
sys.exit(2)
|
||||
|
||||
daemon = Main(args.pidfile, args.config, args.basedir, args.host, args.port, args.debug)
|
||||
if "start" == args.daemon:
|
||||
daemon.start()
|
||||
elif "stop" == args.daemon:
|
||||
daemon.stop()
|
||||
elif "restart" == args.daemon:
|
||||
daemon.restart()
|
||||
else:
|
||||
octoprint = Server(args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot)
|
||||
octoprint.run()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
import octoprint
|
||||
octoprint.main()
|
||||
@@ -0,0 +1,19 @@
|
||||
# Configuration for /etc/init.d/octoprint
|
||||
|
||||
# The init.d script will only run if this variable non-empty.
|
||||
OCTOPRINT_USER=pi
|
||||
|
||||
# On what port to run daemon, default is 5000
|
||||
PORT=5000
|
||||
|
||||
# Path to the OctoPrint executable, use this to override the default setting "/usr/bin/octoprint"
|
||||
#DAEMON=/path/to/octoprint/executable
|
||||
|
||||
# What arguments to pass to octoprint, usually no need to touch this
|
||||
DAEMON_ARGS="--port=$PORT"
|
||||
|
||||
# Umask of files octoprint generates, Change this to 000 if running octoprint as its own, separate user
|
||||
UMASK=022
|
||||
|
||||
# Should we run at startup?
|
||||
START=yes
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/bin/sh
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: octoprint
|
||||
# Required-Start: $local_fs networking
|
||||
# Required-Stop:
|
||||
# Should-Start:
|
||||
# Should-Stop:
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: OctoPrint daemon
|
||||
# Description: Starts the OctoPrint daemon with the user specified in
|
||||
# /etc/default/octoprint.
|
||||
### END INIT INFO
|
||||
|
||||
# Author: Sami Olmari
|
||||
|
||||
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
|
||||
DESC="Octoprint Daemon"
|
||||
NAME="Octoprint"
|
||||
DAEMON=/usr/local/bin/octoprint
|
||||
PIDFILE=/var/run/$NAME.pid
|
||||
PKGNAME=octoprint
|
||||
SCRIPTNAME=/etc/init.d/$PKGNAME
|
||||
|
||||
# Read configuration variable file if it is present
|
||||
[ -r /etc/default/$PKGNAME ] && . /etc/default/$PKGNAME
|
||||
|
||||
# Exit if the octoprint is not installed
|
||||
[ -x "$DAEMON" ] || exit 0
|
||||
|
||||
# Load the VERBOSE setting and other rcS variables
|
||||
[ -f /etc/default/rcS ] && . /etc/default/rcS
|
||||
|
||||
# Define LSB log_* functions.
|
||||
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
|
||||
. /lib/lsb/init-functions
|
||||
|
||||
if [ -z "$START" -o "$START" != "yes" ]
|
||||
then
|
||||
log_warning_msg "Not starting $PKGNAME, edit /etc/default/$PKGNAME to start it."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ -z "$OCTOPRINT_USER" ]
|
||||
then
|
||||
log_warning_msg "Not starting $PKGNAME, OCTOPRINT_USER not set in /etc/default/$PKGNAME."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
#
|
||||
# Function to verify if a pid is alive
|
||||
#
|
||||
is_alive()
|
||||
{
|
||||
pid=`cat $1` > /dev/null 2>&1
|
||||
kill -0 $pid > /dev/null 2>&1
|
||||
return $?
|
||||
}
|
||||
|
||||
#
|
||||
# Function that starts the daemon/service
|
||||
#
|
||||
do_start()
|
||||
{
|
||||
# Return
|
||||
# 0 if daemon has been started
|
||||
# 1 if daemon was already running
|
||||
# 2 if daemon could not be started
|
||||
|
||||
is_alive $PIDFILE
|
||||
RETVAL="$?"
|
||||
|
||||
if [ $RETVAL != 0 ]; then
|
||||
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile \
|
||||
--exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK -- $DAEMON_ARGS
|
||||
RETVAL="$?"
|
||||
fi
|
||||
}
|
||||
|
||||
#
|
||||
# Function that stops the daemon/service
|
||||
#
|
||||
do_stop()
|
||||
{
|
||||
# Return
|
||||
# 0 if daemon has been stopped
|
||||
# 1 if daemon was already stopped
|
||||
# 2 if daemon could not be stopped
|
||||
# other if a failure occurred
|
||||
|
||||
start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --user $OCTOPRINT_USER --pidfile $PIDFILE
|
||||
RETVAL="$?"
|
||||
[ "$RETVAL" = "2" ] && return 2
|
||||
|
||||
rm -f $PIDFILE
|
||||
|
||||
[ "$RETVAL" = "0" ] && return 0 || return 1
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
start)
|
||||
[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
|
||||
do_start
|
||||
case "$?" in
|
||||
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
|
||||
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
|
||||
esac
|
||||
;;
|
||||
stop)
|
||||
[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
|
||||
do_stop
|
||||
case "$?" in
|
||||
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
|
||||
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
|
||||
esac
|
||||
;;
|
||||
restart)
|
||||
log_daemon_msg "Restarting $DESC" "$NAME"
|
||||
do_stop
|
||||
case "$?" in
|
||||
0|1)
|
||||
do_start
|
||||
case "$?" in
|
||||
0) log_end_msg 0 ;;
|
||||
1) log_end_msg 1 ;; # Old process is still running
|
||||
*) log_end_msg 1 ;; # Failed to start
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
# Failed to stop
|
||||
log_end_msg 1
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
|
||||
exit 3
|
||||
;;
|
||||
esac
|
||||
|
||||
@@ -1,13 +1,66 @@
|
||||
# coding=utf-8
|
||||
#!/usr/bin/env python
|
||||
|
||||
from setuptools import setup, find_packages
|
||||
import versioneer
|
||||
versioneer.VCS = 'git'
|
||||
versioneer.versionfile_source = 'src/octoprint/_version.py'
|
||||
versioneer.versionfile_build = 'octoprint/_version.py'
|
||||
versioneer.tag_prefix = ''
|
||||
versioneer.parentdir_prefix = ''
|
||||
versioneer.lookupfile = '.versioneer-lookup'
|
||||
|
||||
from setuptools import setup, find_packages, Command
|
||||
import os
|
||||
import shutil
|
||||
import glob
|
||||
|
||||
|
||||
def package_data_dirs(source, sub_folders):
|
||||
dirs = []
|
||||
|
||||
for d in sub_folders:
|
||||
for dirname, _, files in os.walk(os.path.join(source, d)):
|
||||
dirname = os.path.relpath(dirname, source)
|
||||
for f in files:
|
||||
dirs.append(os.path.join(dirname, f))
|
||||
|
||||
return dirs
|
||||
|
||||
|
||||
class CleanCommand(Command):
|
||||
description = "clean build artifacts"
|
||||
user_options = []
|
||||
boolean_options = []
|
||||
|
||||
def initialize_options(self):
|
||||
pass
|
||||
|
||||
def finalize_options(self):
|
||||
pass
|
||||
|
||||
def run(self):
|
||||
if os.path.exists('build'):
|
||||
print "Deleting build directory"
|
||||
shutil.rmtree('build')
|
||||
eggs = glob.glob('OctoPrint*.egg-info')
|
||||
for egg in eggs:
|
||||
print "Deleting %s directory" % egg
|
||||
shutil.rmtree(egg)
|
||||
|
||||
|
||||
def get_cmdclass():
|
||||
cmdclass = versioneer.get_cmdclass()
|
||||
cmdclass.update({
|
||||
'clean': CleanCommand
|
||||
})
|
||||
return cmdclass
|
||||
|
||||
VERSION = "1.0.0-rc1"
|
||||
|
||||
def params():
|
||||
name = "OctoPrint"
|
||||
version = VERSION
|
||||
version = versioneer.get_version()
|
||||
cmdclass = get_cmdclass()
|
||||
|
||||
description = "A responsive web interface for 3D printers"
|
||||
long_description = open("README.md").read()
|
||||
classifiers = [
|
||||
@@ -34,11 +87,24 @@ def params():
|
||||
url = "http://octoprint.org"
|
||||
license = "AGPLv3"
|
||||
|
||||
packages = find_packages()
|
||||
packages = find_packages(where="src")
|
||||
package_dir = {"octoprint": "src/octoprint"}
|
||||
package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates'])}
|
||||
|
||||
include_package_data = True
|
||||
zip_safe = False
|
||||
install_requires = open("requirements.txt").read().split("\n")
|
||||
|
||||
entry_points = {
|
||||
"console_scripts": [
|
||||
"octoprint = octoprint:main"
|
||||
]
|
||||
}
|
||||
|
||||
#scripts = {
|
||||
# "scripts/octoprint.init": "/etc/init.d/octoprint"
|
||||
#}
|
||||
|
||||
return locals()
|
||||
|
||||
setup(**params())
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python
|
||||
import sys
|
||||
from octoprint.daemon import Daemon
|
||||
from octoprint.server import Server
|
||||
|
||||
#~~ version
|
||||
|
||||
from ._version import get_versions
|
||||
__version__ = get_versions()['version']
|
||||
del get_versions
|
||||
|
||||
#~~ main class
|
||||
|
||||
class Main(Daemon):
|
||||
def __init__(self, pidfile, configfile, basedir, host, port, debug, allowRoot):
|
||||
Daemon.__init__(self, pidfile)
|
||||
|
||||
self._configfile = configfile
|
||||
self._basedir = basedir
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._debug = debug
|
||||
self._allowRoot = allowRoot
|
||||
|
||||
def run(self):
|
||||
octoprint = Server(self._configfile, self._basedir, self._host, self._port, self._debug, self._allowRoot)
|
||||
octoprint.run()
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(prog="run")
|
||||
|
||||
parser.add_argument("-v", "--version", action="store_true", dest="version",
|
||||
help="Output OctoPrint's version and exit")
|
||||
|
||||
parser.add_argument("-d", "--debug", action="store_true", dest="debug",
|
||||
help="Enable debug mode")
|
||||
|
||||
parser.add_argument("--host", action="store", type=str, dest="host",
|
||||
help="Specify the host on which to bind the server")
|
||||
parser.add_argument("--port", action="store", type=int, dest="port",
|
||||
help="Specify the port on which to bind the server")
|
||||
|
||||
parser.add_argument("-c", "--config", action="store", dest="config",
|
||||
help="Specify the config file to use. OctoPrint needs to have write access for the settings dialog to work. Defaults to ~/.octoprint/config.yaml")
|
||||
parser.add_argument("-b", "--basedir", action="store", dest="basedir",
|
||||
help="Specify the basedir to use for uploads, timelapses etc. OctoPrint needs to have write access. Defaults to ~/.octoprint")
|
||||
|
||||
parser.add_argument("--daemon", action="store", type=str, choices=["start", "stop", "restart"],
|
||||
help="Daemonize/control daemonized OctoPrint instance (only supported under Linux right now)")
|
||||
parser.add_argument("--pid", action="store", type=str, dest="pidfile", default="/tmp/octoprint.pid",
|
||||
help="Pidfile to use for daemonizing, defaults to /tmp/octoprint.pid")
|
||||
|
||||
parser.add_argument("--iknowwhatimdoing", action="store_true", dest="allowRoot",
|
||||
help="Allow OctoPrint to run as user root")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.version:
|
||||
print "OctoPrint version %s" % __version__
|
||||
sys.exit(0)
|
||||
|
||||
if args.daemon:
|
||||
if sys.platform == "darwin" or sys.platform == "win32":
|
||||
print >> sys.stderr, "Sorry, daemon mode is only supported under Linux right now"
|
||||
sys.exit(2)
|
||||
|
||||
daemon = Main(args.pidfile, args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot)
|
||||
if "start" == args.daemon:
|
||||
daemon.start()
|
||||
elif "stop" == args.daemon:
|
||||
daemon.stop()
|
||||
elif "restart" == args.daemon:
|
||||
daemon.restart()
|
||||
else:
|
||||
octoprint = Server(args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot)
|
||||
octoprint.run()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,278 @@
|
||||
|
||||
# This file helps to compute a version number in source trees obtained from
|
||||
# git-archive tarball (such as those provided by githubs download-from-tag
|
||||
# feature). Distribution tarballs (build by setup.py sdist) and build
|
||||
# directories (produced by setup.py build) will contain a much shorter file
|
||||
# that just contains the computed version number.
|
||||
|
||||
# This file is released into the public domain. Generated by
|
||||
# versioneer-0.10 (https://github.com/warner/python-versioneer)
|
||||
|
||||
# these strings will be replaced by git during git-archive
|
||||
git_refnames = "$Format:%d$"
|
||||
git_full = "$Format:%H$"
|
||||
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import errno
|
||||
|
||||
|
||||
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
||||
assert isinstance(commands, list)
|
||||
p = None
|
||||
for c in commands:
|
||||
try:
|
||||
# remember shell=False, so use git.cmd on windows, not just git
|
||||
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
|
||||
stderr=(subprocess.PIPE if hide_stderr
|
||||
else None))
|
||||
break
|
||||
except EnvironmentError:
|
||||
e = sys.exc_info()[1]
|
||||
if e.errno == errno.ENOENT:
|
||||
continue
|
||||
if verbose:
|
||||
print("unable to run %s" % args[0])
|
||||
print(e)
|
||||
return None
|
||||
else:
|
||||
if verbose:
|
||||
print("unable to find command, tried %s" % (commands,))
|
||||
return None
|
||||
stdout = p.communicate()[0].strip()
|
||||
if sys.version >= '3':
|
||||
stdout = stdout.decode()
|
||||
if p.returncode != 0:
|
||||
if verbose:
|
||||
print("unable to run %s (error)" % args[0])
|
||||
return None
|
||||
return stdout
|
||||
|
||||
|
||||
import sys
|
||||
import re
|
||||
import os.path
|
||||
|
||||
def get_gits(root, verbose=False):
|
||||
if not os.path.exists(os.path.join(root, ".git")):
|
||||
if verbose:
|
||||
print("no .git in %s" % root)
|
||||
return None
|
||||
|
||||
GITS = ["git"]
|
||||
if sys.platform == "win32":
|
||||
GITS = ["git.cmd", "git.exe"]
|
||||
return GITS
|
||||
|
||||
|
||||
def get_expanded_variables(versionfile_abs):
|
||||
# the code embedded in _version.py can just fetch the value of these
|
||||
# variables. When used from setup.py, we don't want to import
|
||||
# _version.py, so we do it with a regexp instead. This function is not
|
||||
# used from _version.py.
|
||||
variables = {}
|
||||
try:
|
||||
f = open(versionfile_abs,"r")
|
||||
for line in f.readlines():
|
||||
if line.strip().startswith("git_refnames ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
if mo:
|
||||
variables["refnames"] = mo.group(1)
|
||||
if line.strip().startswith("git_full ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
if mo:
|
||||
variables["full"] = mo.group(1)
|
||||
f.close()
|
||||
except EnvironmentError:
|
||||
pass
|
||||
return variables
|
||||
|
||||
def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
|
||||
refnames = variables["refnames"].strip()
|
||||
if refnames.startswith("$Format"):
|
||||
if verbose:
|
||||
print("variables are unexpanded, not using")
|
||||
return {} # unexpanded, so not in an unpacked git-archive tarball
|
||||
refs = set([r.strip() for r in refnames.strip("()").split(",")])
|
||||
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
|
||||
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
|
||||
TAG = "tag: "
|
||||
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
|
||||
if not tags:
|
||||
# Either we're using git < 1.8.3, or there really are no tags. We use
|
||||
# a heuristic: assume all version tags have a digit. The old git %d
|
||||
# expansion behaves like git log --decorate=short and strips out the
|
||||
# refs/heads/ and refs/tags/ prefixes that would let us distinguish
|
||||
# between branches and tags. By ignoring refnames without digits, we
|
||||
# filter out many common branch names like "release" and
|
||||
# "stabilization", as well as "HEAD" and "master".
|
||||
tags = set([r for r in refs if re.search(r'\d', r)])
|
||||
if verbose:
|
||||
print("discarding '%s', no digits" % ",".join(refs-tags))
|
||||
if verbose:
|
||||
print("likely tags: %s" % ",".join(sorted(tags)))
|
||||
for ref in sorted(tags):
|
||||
# sorting will prefer e.g. "2.0" over "2.0rc1"
|
||||
if ref.startswith(tag_prefix):
|
||||
r = ref[len(tag_prefix):]
|
||||
if verbose:
|
||||
print("picking %s" % r)
|
||||
return { "version": r,
|
||||
"full": variables["full"].strip() }
|
||||
# no suitable tags, so we use the full revision id
|
||||
if verbose:
|
||||
print("no suitable tags, using full revision id")
|
||||
return { "version": variables["full"].strip(),
|
||||
"full": variables["full"].strip() }
|
||||
|
||||
def versions_from_lookup(lookup, root, verbose=False):
|
||||
GITS = get_gits(root, verbose=verbose)
|
||||
if GITS is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
|
||||
current_branch = stdout.strip()
|
||||
for matcher, tag, ref_commit in lookup:
|
||||
if matcher.match(current_branch):
|
||||
if tag is None or ref_commit is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
num_commits = stdout.strip()
|
||||
|
||||
stdout =run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
short_hash = stdout.strip()
|
||||
|
||||
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
dirty = stdout.strip().endswith("-dirty")
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
full = stdout.strip()
|
||||
|
||||
version = "%s-%s-g%s" % (tag, num_commits, short_hash)
|
||||
if dirty:
|
||||
version += "-dirty"
|
||||
full += "-dirty"
|
||||
return {"version": version, "full": full, "branch": current_branch}
|
||||
|
||||
return {}
|
||||
|
||||
def versions_from_vcs(tag_prefix, root, verbose=False):
|
||||
# this runs 'git' from the root of the source tree. This only gets called
|
||||
# if the git-archive 'subst' variables were *not* expanded, and
|
||||
# _version.py hasn't already been rewritten with a short version string,
|
||||
# meaning we're inside a checked out source tree.
|
||||
|
||||
GITS = get_gits(root, verbose=verbose)
|
||||
if GITS is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
if not stdout.startswith(tag_prefix):
|
||||
if verbose:
|
||||
print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix))
|
||||
return {}
|
||||
tag = stdout[len(tag_prefix):]
|
||||
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
full = stdout.strip()
|
||||
if tag.endswith("-dirty"):
|
||||
full += "-dirty"
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
branch = None
|
||||
else:
|
||||
branch = stdout.strip()
|
||||
return {"version": tag, "full": full, "branch": branch}
|
||||
|
||||
|
||||
def versions_from_parentdir(parentdir_prefix, root, verbose=False):
|
||||
# Source tarballs conventionally unpack into a directory that includes
|
||||
# both the project name and a version string.
|
||||
dirname = os.path.basename(root)
|
||||
if not dirname.startswith(parentdir_prefix):
|
||||
if verbose:
|
||||
print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" %
|
||||
(root, dirname, parentdir_prefix))
|
||||
return None
|
||||
return {"version": dirname[len(parentdir_prefix):], "full": ""}
|
||||
|
||||
tag_prefix = ""
|
||||
parentdir_prefix = ""
|
||||
versionfile_source = "src/octoprint/_version.py"
|
||||
lookupfile = ".versioneer-lookup"
|
||||
|
||||
def parse_lookup_file(root, lookup_path=None):
|
||||
if not lookup_path:
|
||||
lookup_path = lookupfile
|
||||
if not lookup_path:
|
||||
return []
|
||||
|
||||
path = os.path.join(root, lookup_path)
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
|
||||
import re
|
||||
lookup = []
|
||||
with open(os.path.join(root, lookup_path), "r") as f:
|
||||
for line in f:
|
||||
if '#' in line:
|
||||
line = line[:line.rindex('#')]
|
||||
line = line.strip()
|
||||
try:
|
||||
split_line = line.split()
|
||||
if len(split_line) == 3:
|
||||
pattern, tag, ref_commit = split_line
|
||||
lookup.append([re.compile(pattern), tag, ref_commit])
|
||||
elif len(split_line) >= 1:
|
||||
lookup.append([re.compile(split_line[0]), None, None])
|
||||
except:
|
||||
break
|
||||
return lookup
|
||||
|
||||
def get_versions(default={"version": "unknown", "full": ""}, lookup_path=None, verbose=False):
|
||||
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
|
||||
# __file__, we can work backwards from there to the root. Some
|
||||
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
|
||||
# case we can only use expanded variables.
|
||||
|
||||
variables = { "refnames": git_refnames, "full": git_full }
|
||||
ver = versions_from_expanded_variables(variables, tag_prefix, verbose)
|
||||
if ver:
|
||||
return ver
|
||||
|
||||
try:
|
||||
root = os.path.abspath(__file__)
|
||||
# versionfile_source is the relative path from the top of the source
|
||||
# tree (where the .git directory might live) to this file. Invert
|
||||
# this to find the root from __file__.
|
||||
for i in range(len(versionfile_source.split("/"))):
|
||||
root = os.path.dirname(root)
|
||||
except NameError:
|
||||
return default
|
||||
|
||||
lookup = parse_lookup_file(root, lookup_path=lookup_path)
|
||||
return (versions_from_lookup(lookup, root, verbose)
|
||||
or versions_from_vcs(tag_prefix, root, verbose)
|
||||
or versions_from_parentdir(parentdir_prefix, root, verbose)
|
||||
or default)
|
||||
|
||||
@@ -28,7 +28,7 @@ class Daemon:
|
||||
# decouple from parent environment
|
||||
os.chdir('/')
|
||||
os.setsid()
|
||||
os.umask(0)
|
||||
os.umask(002)
|
||||
|
||||
# do second fork
|
||||
try:
|
||||
@@ -7,18 +7,80 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
import datetime
|
||||
import logging
|
||||
import subprocess
|
||||
import Queue
|
||||
import threading
|
||||
|
||||
from octoprint.settings import settings
|
||||
|
||||
# singleton
|
||||
_instance = None
|
||||
|
||||
|
||||
class Events(object):
|
||||
# application startup
|
||||
STARTUP = "Startup"
|
||||
|
||||
# connect/disconnect to printer
|
||||
CONNECTED = "Connected"
|
||||
DISCONNECTED = "Disconnected"
|
||||
|
||||
# connect/disconnect by client
|
||||
CLIENT_OPENED = "ClientOpened"
|
||||
CLIENT_CLOSED = "ClientClosed"
|
||||
|
||||
# File management
|
||||
UPLOAD = "Upload"
|
||||
FILE_SELECTED = "FileSelected"
|
||||
FILE_DESELECTED = "FileDeselected"
|
||||
UPDATED_FILES = "UpdatedFiles"
|
||||
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
|
||||
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
|
||||
|
||||
# SD Upload
|
||||
TRANSFER_STARTED = "TransferStarted"
|
||||
TRANSFER_DONE = "TransferDone"
|
||||
|
||||
# print job
|
||||
PRINT_STARTED = "PrintStarted"
|
||||
PRINT_DONE = "PrintDone"
|
||||
PRINT_FAILED = "PrintFailed"
|
||||
PRINT_CANCELLED = "PrintCancelled"
|
||||
PRINT_PAUSED = "PrintPaused"
|
||||
PRINT_RESUMED = "PrintResumed"
|
||||
ERROR = "Error"
|
||||
|
||||
# print/gcode events
|
||||
POWER_ON = "PowerOn"
|
||||
POWER_OFF = "PowerOff"
|
||||
HOME = "Home"
|
||||
Z_CHANGE = "ZChange"
|
||||
WAITING = "Waiting"
|
||||
COOLING = "Cooling"
|
||||
ALERT = "Alert"
|
||||
CONVEYOR = "Conveyor"
|
||||
EJECT = "Eject"
|
||||
E_STOP = "EStop"
|
||||
|
||||
# Timelapse
|
||||
CAPTURE_START = "CaptureStart"
|
||||
CAPTURE_DONE = "CaptureDone"
|
||||
MOVIE_RENDERING = "MovieRendering"
|
||||
MOVIE_DONE = "MovieDone"
|
||||
MOVIE_FAILED = "MovieFailed"
|
||||
|
||||
# Slicing
|
||||
SLICING_STARTED = "SlicingStarted"
|
||||
SLICING_DONE = "SlicingDone"
|
||||
SLICING_FAILED = "SlicingFailed"
|
||||
|
||||
|
||||
def eventManager():
|
||||
global _instance
|
||||
if _instance is None:
|
||||
_instance = EventManager()
|
||||
return _instance
|
||||
|
||||
|
||||
class EventManager(object):
|
||||
"""
|
||||
Handles receiving events and dispatching them to subscribers
|
||||
@@ -28,6 +90,27 @@ class EventManager(object):
|
||||
self._registeredListeners = {}
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._queue = Queue.PriorityQueue()
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def _work(self):
|
||||
while True:
|
||||
(event, payload) = self._queue.get(True)
|
||||
|
||||
eventListeners = self._registeredListeners.get(event, None)
|
||||
if eventListeners is None:
|
||||
return
|
||||
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
|
||||
|
||||
for listener in eventListeners:
|
||||
self._logger.debug("Sending action to %r" % listener)
|
||||
try:
|
||||
listener(event, payload)
|
||||
except:
|
||||
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
|
||||
|
||||
def fire(self, event, payload=None):
|
||||
"""
|
||||
Fire an event to anyone subscribed to it
|
||||
@@ -41,17 +124,8 @@ class EventManager(object):
|
||||
|
||||
if not event in self._registeredListeners.keys():
|
||||
return
|
||||
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
|
||||
self._queue.put((event, payload), 0)
|
||||
|
||||
eventListeners = self._registeredListeners[event]
|
||||
for listener in eventListeners:
|
||||
self._logger.debug("Sending action to %r" % listener)
|
||||
try:
|
||||
listener(event, payload)
|
||||
except:
|
||||
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
|
||||
|
||||
|
||||
def subscribe(self, event, callback):
|
||||
"""
|
||||
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
|
||||
@@ -68,6 +142,10 @@ class EventManager(object):
|
||||
self._logger.debug("Subscribed listener %r for event %s" % (callback, event))
|
||||
|
||||
def unsubscribe (self, event, callback):
|
||||
"""
|
||||
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
|
||||
"""
|
||||
|
||||
if not event in self._registeredListeners:
|
||||
# no callback registered for callback, just return
|
||||
return
|
||||
@@ -79,6 +157,7 @@ class EventManager(object):
|
||||
self._registeredListeners[event].remove(callback)
|
||||
self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
|
||||
|
||||
|
||||
class GenericEventListener(object):
|
||||
"""
|
||||
The GenericEventListener can be subclassed to easily create custom event listeners.
|
||||
@@ -110,51 +189,56 @@ class GenericEventListener(object):
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class DebugEventListener(GenericEventListener):
|
||||
def __init__(self):
|
||||
GenericEventListener.__init__(self)
|
||||
|
||||
events = ["Startup", "Connected", "Disconnected", "ClientOpen", "ClientClosed", "PowerOn", "PowerOff", "Upload",
|
||||
"FileSelected", "TransferStarted", "TransferDone", "PrintStarted", "PrintDone", "PrintFailed",
|
||||
"Cancelled", "Home", "ZChange", "Paused", "Waiting", "Cooling", "Alert", "Conveyor", "Eject",
|
||||
"CaptureStart", "CaptureDone", "MovieDone", "EStop", "Error"]
|
||||
events = filter(lambda x: not x.startswith("__"), dir(Events))
|
||||
self.subscribe(events)
|
||||
|
||||
def eventCallback(self, event, payload):
|
||||
GenericEventListener.eventCallback(self, event, payload)
|
||||
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
|
||||
|
||||
|
||||
class CommandTrigger(GenericEventListener):
|
||||
def __init__(self, triggerType, printer):
|
||||
def __init__(self, printer):
|
||||
GenericEventListener.__init__(self)
|
||||
self._printer = printer
|
||||
self._subscriptions = {}
|
||||
|
||||
self._initSubscriptions(triggerType)
|
||||
self._initSubscriptions()
|
||||
|
||||
def _initSubscriptions(self, triggerType):
|
||||
def _initSubscriptions(self):
|
||||
"""
|
||||
Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their
|
||||
respective commands.
|
||||
"""
|
||||
if not settings().get(["events", triggerType]):
|
||||
if not settings().get(["events"]):
|
||||
return
|
||||
|
||||
if not settings().getBoolean(["events", triggerType, "enabled"]):
|
||||
if not settings().getBoolean(["events", "enabled"]):
|
||||
return
|
||||
|
||||
eventsToSubscribe = []
|
||||
for subscription in settings().get(["events", triggerType, "subscriptions"]):
|
||||
if not "event" in subscription.keys() or not "command" in subscription.keys():
|
||||
self._logger.info("Invalid %s, missing either event or command: %r" % (triggerType, subscription))
|
||||
for subscription in settings().get(["events", "subscriptions"]):
|
||||
if not "event" in subscription.keys() or not "command" in subscription.keys() \
|
||||
or not "type" in subscription.keys() or not subscription["type"] in ["system", "gcode"]:
|
||||
self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: %r" % subscription)
|
||||
continue
|
||||
|
||||
if "enabled" in subscription.keys() and not subscription["enabled"]:
|
||||
self._logger.info("Disabled command trigger: %r" % subscription)
|
||||
continue
|
||||
|
||||
event = subscription["event"]
|
||||
command = subscription["command"]
|
||||
commandType = subscription["type"]
|
||||
|
||||
if not event in self._subscriptions.keys():
|
||||
self._subscriptions[event] = []
|
||||
self._subscriptions[event].append(command)
|
||||
self._subscriptions[event].append((command, commandType))
|
||||
|
||||
if not event in eventsToSubscribe:
|
||||
eventsToSubscribe.append(event)
|
||||
@@ -172,15 +256,48 @@ class CommandTrigger(GenericEventListener):
|
||||
if not event in self._subscriptions:
|
||||
return
|
||||
|
||||
for command in self._subscriptions[event]:
|
||||
processedCommand = self._processCommand(command, payload)
|
||||
self.executeCommand(processedCommand)
|
||||
for command, commandType in self._subscriptions[event]:
|
||||
try:
|
||||
if isinstance(command, (tuple, list, set)):
|
||||
processedCommand = []
|
||||
for c in command:
|
||||
processedCommand.append(self._processCommand(c, payload))
|
||||
else:
|
||||
processedCommand = self._processCommand(command, payload)
|
||||
self.executeCommand(processedCommand, commandType)
|
||||
except KeyError, e:
|
||||
self._logger.warn("There was an error processing one or more placeholders in the following command: %s" % command)
|
||||
|
||||
def executeCommand(self, command):
|
||||
"""
|
||||
Not implemented, override in child classes
|
||||
"""
|
||||
pass
|
||||
def executeCommand(self, command, commandType):
|
||||
if commandType == "system":
|
||||
self._executeSystemCommand(command)
|
||||
elif commandType == "gcode":
|
||||
self._executeGcodeCommand(command)
|
||||
|
||||
def _executeSystemCommand(self, command):
|
||||
def commandExecutioner(command):
|
||||
self._logger.info("Executing system command: %s" % command)
|
||||
subprocess.Popen(command, shell=True)
|
||||
|
||||
try:
|
||||
if isinstance(command, (list, tuple, set)):
|
||||
for c in command:
|
||||
commandExecutioner(c)
|
||||
else:
|
||||
commandExecutioner(command)
|
||||
except subprocess.CalledProcessError, e:
|
||||
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, e.message))
|
||||
except Exception, ex:
|
||||
self._logger.exception("Command failed")
|
||||
|
||||
def _executeGcodeCommand(self, command):
|
||||
commands = [command]
|
||||
if isinstance(command, (list, tuple, set)):
|
||||
self.logger.debug("Executing GCode commands: %r" % command)
|
||||
commands = list(command)
|
||||
else:
|
||||
self._logger.debug("Executing GCode command: %s" % command)
|
||||
self._printer.commands(commands)
|
||||
|
||||
def _processCommand(self, command, payload):
|
||||
"""
|
||||
@@ -188,59 +305,36 @@ class CommandTrigger(GenericEventListener):
|
||||
|
||||
The following substitutions are currently supported:
|
||||
|
||||
- %(currentZ)s : current Z position of the print head, or -1 if not available
|
||||
- %(filename)s : current selected filename, or "NO FILE" if no file is selected
|
||||
- %(progress)s : current print progress in percent, 0 if no print is in progress
|
||||
- %(data)s : the string representation of the event's payload
|
||||
- %(now)s : ISO 8601 representation of the current date and time
|
||||
- {__currentZ} : current Z position of the print head, or -1 if not available
|
||||
- {__filename} : current selected filename, or "NO FILE" if no file is selected
|
||||
- {__progress} : current print progress in percent, 0 if no print is in progress
|
||||
- {__data} : the string representation of the event's payload
|
||||
- {__now} : ISO 8601 representation of the current date and time
|
||||
|
||||
Additionally, the keys of the event's payload can also be used as placeholder.
|
||||
"""
|
||||
|
||||
params = {
|
||||
"currentZ": "-1",
|
||||
"filename": "NO FILE",
|
||||
"progress": "0",
|
||||
"data": str(payload),
|
||||
"now": datetime.datetime.now().isoformat()
|
||||
"__currentZ": "-1",
|
||||
"__filename": "NO FILE",
|
||||
"__progress": "0",
|
||||
"__data": str(payload),
|
||||
"__now": datetime.datetime.now().isoformat()
|
||||
}
|
||||
|
||||
currentData = self._printer.getCurrentData()
|
||||
|
||||
if "currentZ" in currentData.keys() and currentData["currentZ"] is not None:
|
||||
params["currentZ"] = str(currentData["currentZ"])
|
||||
params["__currentZ"] = str(currentData["currentZ"])
|
||||
|
||||
if "job" in currentData.keys() and currentData["job"] is not None:
|
||||
params["filename"] = currentData["job"]["filename"]
|
||||
params["__filename"] = currentData["job"]["file"]["name"]
|
||||
if "progress" in currentData.keys() and currentData["progress"] is not None \
|
||||
and "progress" in currentData["progress"].keys() and currentData["progress"]["progress"] is not None:
|
||||
params["progress"] = str(round(currentData["progress"]["progress"] * 100))
|
||||
params["__progress"] = str(round(currentData["progress"]["progress"] * 100))
|
||||
|
||||
return command % params
|
||||
# now add the payload keys as well
|
||||
if isinstance(payload, dict):
|
||||
params.update(payload)
|
||||
|
||||
class SystemCommandTrigger(CommandTrigger):
|
||||
"""
|
||||
Performs configured system commands for configured events.
|
||||
"""
|
||||
|
||||
def __init__(self, printer):
|
||||
CommandTrigger.__init__(self, "systemCommandTrigger", printer)
|
||||
|
||||
def executeCommand(self, command):
|
||||
try:
|
||||
self._logger.info("Executing system command: %s" % command)
|
||||
subprocess.Popen(command, shell=True)
|
||||
except subprocess.CalledProcessError, e:
|
||||
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, e.message))
|
||||
except Exception, ex:
|
||||
self._logger.exception("Command failed")
|
||||
|
||||
class GcodeCommandTrigger(CommandTrigger):
|
||||
"""
|
||||
Sends configured GCODE commands to the printer for configured events.
|
||||
"""
|
||||
|
||||
def __init__(self, printer):
|
||||
CommandTrigger.__init__(self, "gcodeCommandTrigger", printer)
|
||||
|
||||
def executeCommand(self, command):
|
||||
self._logger.debug("Executing GCode command: %s" % command)
|
||||
self._printer.commands(command.split(","))
|
||||
return command.format(**params)
|
||||
@@ -0,0 +1,4 @@
|
||||
class FileDestinations(object):
|
||||
|
||||
SDCARD = "sdcard"
|
||||
LOCAL = "local"
|
||||
@@ -0,0 +1,6 @@
|
||||
|
||||
|
||||
class FileTypes(object):
|
||||
|
||||
STL = "stl"
|
||||
GCODE = "gcode"
|
||||
@@ -1,43 +1,91 @@
|
||||
# coding=utf-8
|
||||
import re
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import os
|
||||
import Queue
|
||||
import threading
|
||||
import datetime
|
||||
import yaml
|
||||
import time
|
||||
import logging
|
||||
import octoprint.util as util
|
||||
import octoprint.util.gcodeInterpreter as gcodeInterpreter
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
SUPPORTED_EXTENSIONS=["gcode", "gco"]
|
||||
GCODE_EXTENSIONS = ["gcode", "gco", "g"]
|
||||
STL_EXTENSIONS = ["stl"]
|
||||
SUPPORTED_EXTENSIONS = GCODE_EXTENSIONS + STL_EXTENSIONS
|
||||
|
||||
def isGcodeFileName(filename):
|
||||
"""Simple helper to determine if a filename has the .gcode extension.
|
||||
|
||||
:param filename: :class: `str`
|
||||
|
||||
:returns boolean:
|
||||
"""
|
||||
return "." in filename and filename.rsplit(".", 1)[1].lower() in GCODE_EXTENSIONS
|
||||
|
||||
|
||||
def isSTLFileName(filename):
|
||||
"""Simple helper to determine if a filename has the .stl extension.
|
||||
|
||||
:param filename: :class: `str`
|
||||
|
||||
:returns boolean:
|
||||
"""
|
||||
return "." in filename and filename.rsplit(".", 1)[1].lower() in STL_EXTENSIONS
|
||||
|
||||
|
||||
def genGcodeFileName(filename):
|
||||
if not filename:
|
||||
return None
|
||||
|
||||
name, ext = filename.rsplit(".", 1)
|
||||
return name + ".gcode"
|
||||
|
||||
|
||||
def genStlFileName(filename):
|
||||
if not filename:
|
||||
return None
|
||||
|
||||
name, ext = filename.rsplit(".", 1)
|
||||
return name + ".stl"
|
||||
|
||||
|
||||
class GcodeManager:
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._uploadFolder = settings().getBaseFolder("uploads")
|
||||
self._settings = settings()
|
||||
|
||||
self._uploadFolder = self._settings.getBaseFolder("uploads")
|
||||
|
||||
self._callbacks = []
|
||||
|
||||
self._metadata = {}
|
||||
self._metadataDirty = False
|
||||
self._metadataFile = os.path.join(self._uploadFolder, "metadata.yaml")
|
||||
self._metadataTempFile = os.path.join(self._uploadFolder, "metadata.yaml.tmp")
|
||||
self._metadataFileAccessMutex = threading.Lock()
|
||||
|
||||
self._metadataAnalyzer = MetadataAnalyzer(getPathCallback=self.getAbsolutePath, loadedCallback=self._onMetadataAnalysisFinished)
|
||||
|
||||
self._loadMetadata()
|
||||
self._loadMetadata(migrate=True)
|
||||
self._processAnalysisBacklog()
|
||||
|
||||
def _processAnalysisBacklog(self):
|
||||
for osFile in os.listdir(self._uploadFolder):
|
||||
filename = self._getBasicFilename(osFile)
|
||||
if not isGcodeFileName(filename):
|
||||
continue
|
||||
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
continue
|
||||
@@ -61,12 +109,15 @@ class GcodeManager:
|
||||
analysisResult = {}
|
||||
dirty = False
|
||||
if gcode.totalMoveTimeMinute:
|
||||
analysisResult["estimatedPrintTime"] = util.getFormattedTimeDelta(datetime.timedelta(minutes=gcode.totalMoveTimeMinute))
|
||||
analysisResult["estimatedPrintTime"] = gcode.totalMoveTimeMinute * 60
|
||||
dirty = True
|
||||
if gcode.extrusionAmount:
|
||||
analysisResult["filament"] = "%.2fm" % (gcode.extrusionAmount / 1000)
|
||||
if gcode.calculateVolumeCm3():
|
||||
analysisResult["filament"] += " / %.2fcm³" % gcode.calculateVolumeCm3()
|
||||
analysisResult["filament"] = {}
|
||||
for i in range(len(gcode.extrusionAmount)):
|
||||
analysisResult["filament"]["tool%d" % i] = {
|
||||
"length": gcode.extrusionAmount[i],
|
||||
"volume": gcode.extrusionVolume[i]
|
||||
}
|
||||
dirty = True
|
||||
|
||||
if dirty:
|
||||
@@ -75,25 +126,93 @@ class GcodeManager:
|
||||
self._metadata[basename] = metadata
|
||||
self._metadataDirty = True
|
||||
self._saveMetadata()
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": basename, "result": analysisResult})
|
||||
|
||||
def _loadMetadata(self):
|
||||
def _loadMetadata(self, migrate=False):
|
||||
if os.path.exists(self._metadataFile) and os.path.isfile(self._metadataFile):
|
||||
with self._metadataFileAccessMutex:
|
||||
with open(self._metadataFile, "r") as f:
|
||||
self._metadata = yaml.safe_load(f)
|
||||
|
||||
if self._metadata is None:
|
||||
self._metadata = {}
|
||||
|
||||
# TODO: Remove in a couple of versions (2013-12-21)
|
||||
if migrate:
|
||||
self._migrateMetadata()
|
||||
|
||||
def _migrateMetadata(self):
|
||||
self._logger.info("Migrating metadata if necessary...")
|
||||
|
||||
printTimeRe = re.compile("(\d+):(\d{2}):(\d{2})")
|
||||
filamentRe = re.compile("(\d*\.\d+)m(\s/\s(\d*\.\d+)cm.)?")
|
||||
|
||||
hoursToSeconds = 60 * 60
|
||||
minutesToSeconds = 60
|
||||
|
||||
updateCount = 0
|
||||
for metadata in self._metadata.values():
|
||||
if not "gcodeAnalysis" in metadata:
|
||||
continue
|
||||
|
||||
updated = False
|
||||
if "estimatedPrintTime" in metadata["gcodeAnalysis"]:
|
||||
estimatedPrintTime = metadata["gcodeAnalysis"]["estimatedPrintTime"]
|
||||
if isinstance(estimatedPrintTime, (str, unicode)):
|
||||
match = re.match(printTimeRe, estimatedPrintTime)
|
||||
if match:
|
||||
metadata["gcodeAnalysis"]["estimatedPrintTime"] = int(match.group(1)) * hoursToSeconds + int(match.group(2)) * minutesToSeconds + int(match.group(3))
|
||||
self._metadataDirty = True
|
||||
updated = True
|
||||
if "filament" in metadata["gcodeAnalysis"]:
|
||||
filament = metadata["gcodeAnalysis"]["filament"]
|
||||
if isinstance(filament, (str, unicode)):
|
||||
match = re.match(filamentRe, filament)
|
||||
if match:
|
||||
metadata["gcodeAnalysis"]["filament"] = {
|
||||
"tool0": {
|
||||
"length": int(float(match.group(1)) * 1000)
|
||||
}
|
||||
}
|
||||
if match.group(3) is not None:
|
||||
metadata["gcodeAnalysis"]["filament"]["tool0"].update({
|
||||
"volume": float(match.group(3))
|
||||
})
|
||||
self._metadataDirty = True
|
||||
updated = True
|
||||
elif isinstance(filament, dict) and ("length" in filament.keys() or "volume" in filament.keys()):
|
||||
metadata["gcodeAnalysis"]["filament"] = {
|
||||
"tool0": {}
|
||||
}
|
||||
if "length" in filament.keys():
|
||||
metadata["gcodeAnalysis"]["filament"]["tool0"].update({
|
||||
"length": filament["length"]
|
||||
})
|
||||
if "volume" in filament.keys():
|
||||
metadata["gcodeAnalysis"]["filament"]["tool0"].update({
|
||||
"volume": filament["volume"]
|
||||
})
|
||||
self._metadataDirty = True
|
||||
updated = True
|
||||
|
||||
if updated:
|
||||
updateCount += 1
|
||||
|
||||
self._saveMetadata()
|
||||
|
||||
self._logger.info("Updated %d sets of metadata to new format" % updateCount)
|
||||
|
||||
def _saveMetadata(self, force=False):
|
||||
if not self._metadataDirty and not force:
|
||||
return
|
||||
|
||||
with self._metadataFileAccessMutex:
|
||||
with open(self._metadataFile, "wb") as f:
|
||||
with open(self._metadataTempFile, "wb") as f:
|
||||
yaml.safe_dump(self._metadata, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._metadataDirty = False
|
||||
util.safeRename(self._metadataTempFile, self._metadataFile)
|
||||
|
||||
self._loadMetadata()
|
||||
self._sendUpdateTrigger("gcodeFiles")
|
||||
|
||||
def _getBasicFilename(self, filename):
|
||||
if filename.startswith(self._uploadFolder):
|
||||
@@ -112,12 +231,43 @@ class GcodeManager:
|
||||
|
||||
def _sendUpdateTrigger(self, type):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendUpdateTrigger(type)
|
||||
try: callback.sendEvent(type)
|
||||
except: pass
|
||||
|
||||
#~~ file handling
|
||||
|
||||
def addFile(self, file):
|
||||
def addFile(self, file, destination, uploadCallback=None):
|
||||
"""
|
||||
Adds the given file for the given destination to the systems. Takes care of slicing if enabled and
|
||||
necessary.
|
||||
|
||||
If the file's processing won't be finished directly with the return from this method but happen
|
||||
asynchronously in the background (e.g. due to slicing), returns a tuple containing the just added file's
|
||||
filename and False. Otherwise returns a tuple (filename, True).
|
||||
"""
|
||||
if not file or not destination:
|
||||
return None, True
|
||||
|
||||
curaEnabled = self._settings.getBoolean(["cura", "enabled"])
|
||||
filename = file.filename
|
||||
|
||||
absolutePath = self.getAbsolutePath(filename, mustExist=False)
|
||||
gcode = isGcodeFileName(filename)
|
||||
|
||||
if absolutePath is None or (not curaEnabled and not gcode):
|
||||
return None, True
|
||||
|
||||
file.save(absolutePath)
|
||||
|
||||
if gcode:
|
||||
return self.processGcode(absolutePath, destination, uploadCallback), True
|
||||
else:
|
||||
if curaEnabled and isSTLFileName(filename):
|
||||
return self.processStl(absolutePath, destination, uploadCallback), False
|
||||
else:
|
||||
return filename, False
|
||||
|
||||
def getFutureFileName(self, file):
|
||||
if not file:
|
||||
return None
|
||||
|
||||
@@ -125,15 +275,50 @@ class GcodeManager:
|
||||
if absolutePath is None:
|
||||
return None
|
||||
|
||||
basename = self._getBasicFilename(absolutePath)
|
||||
if basename in self._metadata.keys():
|
||||
return self._getBasicFilename(absolutePath)
|
||||
|
||||
def processStl(self, absolutePath, destination, uploadCallback=None):
|
||||
from octoprint.slicers.cura import CuraFactory
|
||||
|
||||
cura = CuraFactory.create_slicer()
|
||||
gcodePath = genGcodeFileName(absolutePath)
|
||||
config = self._settings.get(["cura", "config"])
|
||||
|
||||
slicingStart = time.time()
|
||||
|
||||
def stlProcessed(stlPath, gcodePath, error=None):
|
||||
if error:
|
||||
eventManager().fire(Events.SLICING_FAILED, {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "reason": error})
|
||||
if os.path.exists(stlPath):
|
||||
os.remove(stlPath)
|
||||
else:
|
||||
slicingStop = time.time()
|
||||
eventManager().fire(Events.SLICING_DONE, {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "time": slicingStop - slicingStart})
|
||||
self.processGcode(gcodePath, destination, uploadCallback)
|
||||
|
||||
eventManager().fire(Events.SLICING_STARTED, {"stl": self._getBasicFilename(absolutePath), "gcode": self._getBasicFilename(gcodePath)})
|
||||
cura.process_file(config, gcodePath, absolutePath, stlProcessed, [absolutePath, gcodePath])
|
||||
|
||||
return self._getBasicFilename(gcodePath)
|
||||
|
||||
def processGcode(self, absolutePath, destination, uploadCallback=None):
|
||||
if absolutePath is None:
|
||||
return None
|
||||
|
||||
filename = self._getBasicFilename(absolutePath)
|
||||
|
||||
if filename in self._metadata.keys():
|
||||
# delete existing metadata entry, since the file is going to get overwritten
|
||||
del self._metadata[basename]
|
||||
del self._metadata[filename]
|
||||
self._metadataDirty = True
|
||||
self._saveMetadata()
|
||||
file.save(absolutePath)
|
||||
self._metadataAnalyzer.addFileToQueue(basename)
|
||||
return basename
|
||||
|
||||
self._metadataAnalyzer.addFileToQueue(os.path.basename(absolutePath))
|
||||
|
||||
if uploadCallback is not None:
|
||||
return uploadCallback(filename, absolutePath, destination)
|
||||
else:
|
||||
return filename
|
||||
|
||||
def getFutureFilename(self, file):
|
||||
if not file:
|
||||
@@ -148,10 +333,15 @@ class GcodeManager:
|
||||
def removeFile(self, filename):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
stlPath = genStlFileName(absolutePath)
|
||||
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
os.remove(absolutePath)
|
||||
if os.path.exists(stlPath):
|
||||
os.remove(stlPath)
|
||||
|
||||
if filename in self._metadata.keys():
|
||||
del self._metadata[filename]
|
||||
self._metadataDirty = True
|
||||
@@ -159,11 +349,11 @@ class GcodeManager:
|
||||
|
||||
def getAbsolutePath(self, filename, mustExist=True):
|
||||
"""
|
||||
Returns the absolute path of the given filename in the gcode upload folder.
|
||||
Returns the absolute path of the given filename in the correct upload folder.
|
||||
|
||||
Ensures that the file
|
||||
<ul>
|
||||
<li>has the extension ".gcode"</li>
|
||||
<li>has any of the extensions listed in SUPPORTED_EXTENSIONS</li>
|
||||
<li>exists and is a file (not a directory) if "mustExist" is set to True</li>
|
||||
</ul>
|
||||
|
||||
@@ -176,12 +366,16 @@ class GcodeManager:
|
||||
if not util.isAllowedFile(filename.lower(), set(SUPPORTED_EXTENSIONS)):
|
||||
return None
|
||||
|
||||
# TODO: detect which type of file and add in the extra folder portion
|
||||
secure = os.path.join(self._uploadFolder, secure_filename(self._getBasicFilename(filename)))
|
||||
if mustExist and (not os.path.exists(secure) or not os.path.isfile(secure)):
|
||||
return None
|
||||
|
||||
return secure
|
||||
|
||||
def getAllFilenames(self):
|
||||
return map(lambda x: x["name"], self.getAllFileData())
|
||||
|
||||
def getAllFileData(self):
|
||||
files = []
|
||||
for osFile in os.listdir(self._uploadFolder):
|
||||
@@ -191,7 +385,15 @@ class GcodeManager:
|
||||
return files
|
||||
|
||||
def getFileData(self, filename):
|
||||
if not filename:
|
||||
return
|
||||
|
||||
filename = self._getBasicFilename(filename)
|
||||
|
||||
# TODO: Make this more robust when STLs will be viewable from the client
|
||||
if isSTLFileName(filename):
|
||||
return
|
||||
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return None
|
||||
@@ -199,9 +401,9 @@ class GcodeManager:
|
||||
statResult = os.stat(absolutePath)
|
||||
fileData = {
|
||||
"name": filename,
|
||||
"size": util.getFormattedSize(statResult.st_size),
|
||||
"bytes": statResult.st_size,
|
||||
"date": util.getFormattedDateTime(datetime.datetime.fromtimestamp(statResult.st_ctime))
|
||||
"size": statResult.st_size,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"date": int(statResult.st_ctime)
|
||||
}
|
||||
|
||||
# enrich with additional metadata from analysis if available
|
||||
@@ -209,18 +411,18 @@ class GcodeManager:
|
||||
for key in self._metadata[filename].keys():
|
||||
if key == "prints":
|
||||
val = self._metadata[filename][key]
|
||||
formattedLast = None
|
||||
if val["last"] is not None:
|
||||
formattedLast = {
|
||||
"date": util.getFormattedDateTime(datetime.datetime.fromtimestamp(val["last"]["date"])),
|
||||
last = None
|
||||
if "last" in val and val["last"] is not None:
|
||||
last = {
|
||||
"date": val["last"]["date"],
|
||||
"success": val["last"]["success"]
|
||||
}
|
||||
formattedPrints = {
|
||||
prints = {
|
||||
"success": val["success"],
|
||||
"failure": val["failure"],
|
||||
"last": formattedLast
|
||||
"last": last
|
||||
}
|
||||
fileData["prints"] = formattedPrints
|
||||
fileData["prints"] = prints
|
||||
else:
|
||||
fileData[key] = self._metadata[filename][key]
|
||||
|
||||
@@ -358,8 +560,6 @@ class MetadataAnalyzer:
|
||||
def _work(self):
|
||||
aborted = None
|
||||
while True:
|
||||
self._active.wait()
|
||||
|
||||
if aborted is not None:
|
||||
filename = aborted
|
||||
aborted = None
|
||||
@@ -368,6 +568,8 @@ class MetadataAnalyzer:
|
||||
(priority, filename) = self._queue.get()
|
||||
self._logger.debug("Processing file %s from queue (priority %d)" % (filename, priority))
|
||||
|
||||
self._active.wait()
|
||||
|
||||
try:
|
||||
self._analyzeGcode(filename)
|
||||
self._queue.task_done()
|
||||
@@ -377,7 +579,7 @@ class MetadataAnalyzer:
|
||||
|
||||
def _analyzeGcode(self, filename):
|
||||
path = self._getPathCallback(filename)
|
||||
if path is None:
|
||||
if path is None or not os.path.exists(path):
|
||||
return
|
||||
|
||||
self._currentFile = filename
|
||||
@@ -385,6 +587,7 @@ class MetadataAnalyzer:
|
||||
|
||||
try:
|
||||
self._logger.debug("Starting analysis of file %s" % filename)
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"file": filename})
|
||||
self._gcode = gcodeInterpreter.gcode()
|
||||
self._gcode.progressCallback = self._onParsingProgress
|
||||
self._gcode.load(path)
|
||||
@@ -7,14 +7,15 @@ import datetime
|
||||
import threading
|
||||
import copy
|
||||
import os
|
||||
|
||||
#import logging, logging.config
|
||||
import logging
|
||||
|
||||
import octoprint.util.comm as comm
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.events import eventManager
|
||||
from octoprint.events import eventManager, Events
|
||||
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
def getConnectionOptions():
|
||||
"""
|
||||
@@ -36,16 +37,12 @@ class Printer():
|
||||
self._gcodeManager.registerCallback(self)
|
||||
|
||||
# state
|
||||
# TODO do we really need to hold the temperature here?
|
||||
self._temp = None
|
||||
self._bedTemp = None
|
||||
self._targetTemp = None
|
||||
self._targetBedTemp = None
|
||||
self._temps = {
|
||||
"actual": deque([], 300),
|
||||
"target": deque([], 300),
|
||||
"actualBed": deque([], 300),
|
||||
"targetBed": deque([], 300)
|
||||
}
|
||||
self._temps = deque([], 300)
|
||||
self._tempBacklog = []
|
||||
|
||||
self._latestMessage = None
|
||||
@@ -70,6 +67,8 @@ class Printer():
|
||||
self._sdPrinting = False
|
||||
self._sdStreaming = False
|
||||
self._sdFilelistAvailable = threading.Event()
|
||||
self._sdRemoteName = None
|
||||
self._streamingFinishedCallback = None
|
||||
|
||||
self._selectedFile = None
|
||||
|
||||
@@ -89,11 +88,25 @@ class Printer():
|
||||
)
|
||||
self._stateMonitor.reset(
|
||||
state={"state": None, "stateString": self.getStateString(), "flags": self._getStateFlags()},
|
||||
jobData={"filename": None, "filesize": None, "estimatedPrintTime": None, "filament": None},
|
||||
progress={"progress": None, "filepos": None, "printTime": None, "printTimeLeft": None},
|
||||
jobData={
|
||||
"file": {
|
||||
"name": None,
|
||||
"size": None,
|
||||
"origin": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"filament": {
|
||||
"length": None,
|
||||
"volume": None
|
||||
}
|
||||
},
|
||||
progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
|
||||
currentZ=None
|
||||
)
|
||||
|
||||
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished);
|
||||
|
||||
#~~ callback handling
|
||||
|
||||
def registerCallback(self, callback):
|
||||
@@ -126,7 +139,7 @@ class Printer():
|
||||
|
||||
def _sendTriggerUpdateCallbacks(self, type):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendUpdateTrigger(type)
|
||||
try: callback.sendEvent(type)
|
||||
except: pass
|
||||
|
||||
def _sendFeedbackCommandOutput(self, name, output):
|
||||
@@ -142,6 +155,14 @@ class Printer():
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
|
||||
#~~ callback from metadata analysis event
|
||||
|
||||
def onMetadataAnalysisFinished(self, event, data):
|
||||
if self._selectedFile:
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
|
||||
#~~ printer commands
|
||||
|
||||
def connect(self, port=None, baudrate=None):
|
||||
@@ -160,7 +181,7 @@ class Printer():
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = None
|
||||
eventManager().fire("Disconnected")
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
def command(self, command):
|
||||
"""
|
||||
@@ -178,15 +199,64 @@ class Printer():
|
||||
for command in commands:
|
||||
self._comm.sendCommand(command)
|
||||
|
||||
def setTemperatureOffset(self, extruder, bed):
|
||||
def jog(self, axis, amount):
|
||||
movementSpeed = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z"]], asdict=True)
|
||||
self.commands(["G91", "G1 %s%.4f F%d" % (axis.upper(), amount, movementSpeed[axis]), "G90"])
|
||||
|
||||
def home(self, axes):
|
||||
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), axes)), "G90"])
|
||||
|
||||
def extrude(self, amount):
|
||||
extrusionSpeed = settings().get(["printerParameters", "movementSpeed", "e"])
|
||||
self.commands(["G91", "G1 E%s F%d" % (amount, extrusionSpeed), "G90"])
|
||||
|
||||
def changeTool(self, tool):
|
||||
try:
|
||||
toolNum = int(tool[len("tool"):])
|
||||
self.command("T%d" % toolNum)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def setTemperature(self, type, value):
|
||||
if type.startswith("tool"):
|
||||
if settings().getInt(["printerParameters", "numExtruders"]) > 1:
|
||||
try:
|
||||
toolNum = int(type[len("tool"):])
|
||||
self.command("M104 T%d S%f" % (toolNum, value))
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
self.command("M104 S%f" % value)
|
||||
elif type == "bed":
|
||||
self.command("M140 S%f" % value)
|
||||
|
||||
def setTemperatureOffset(self, offsets={}):
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.setTemperatureOffset(extruder, bed)
|
||||
self._stateMonitor.setTempOffsets(extruder, bed)
|
||||
tool, bed = self._comm.getOffsets()
|
||||
|
||||
validatedOffsets = {}
|
||||
|
||||
for key in offsets:
|
||||
value = offsets[key]
|
||||
if key == "bed":
|
||||
bed = value
|
||||
validatedOffsets[key] = value
|
||||
elif key.startswith("tool"):
|
||||
try:
|
||||
toolNum = int(key[len("tool"):])
|
||||
tool[toolNum] = value
|
||||
validatedOffsets[key] = value
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
self._comm.setTemperatureOffset(tool, bed)
|
||||
self._stateMonitor.setTempOffsets(validatedOffsets)
|
||||
|
||||
def selectFile(self, filename, sd, printAfterSelect=False):
|
||||
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
logging.info("Cannot load file: printer not connected or currently busy")
|
||||
return
|
||||
|
||||
self._printAfterSelect = printAfterSelect
|
||||
@@ -234,7 +304,11 @@ class Printer():
|
||||
self._comm.cancelPrint()
|
||||
|
||||
if disableMotorsAndHeater:
|
||||
self.commands(["M84", "M104 S0", "M140 S0", "M106 S0"]) # disable motors, switch off heaters and fan
|
||||
# disable motors, switch off hotends, bed and fan
|
||||
commands = ["M84"]
|
||||
commands.extend(map(lambda x: "M104 T%d S0" % x, range(settings().getInt(["printerParameters", "numExtruders"]))))
|
||||
commands.extend(["M140 S0", "M106 S0"])
|
||||
self.commands(commands)
|
||||
|
||||
# reset progress, height, print time
|
||||
self._setCurrentZ(None)
|
||||
@@ -243,17 +317,19 @@ class Printer():
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
self._gcodeManager.printFailed(self._selectedFile["filename"])
|
||||
eventManager().fire("PrintFailed", self._selectedFile["filename"])
|
||||
payload = {
|
||||
"file": self._selectedFile["filename"],
|
||||
"origin": FileDestinations.LOCAL
|
||||
}
|
||||
if self._selectedFile["sd"]:
|
||||
payload["origin"] = FileDestinations.SDCARD
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
#~~ state monitoring
|
||||
|
||||
def _setCurrentZ(self, currentZ):
|
||||
self._currentZ = currentZ
|
||||
|
||||
formattedCurrentZ = None
|
||||
if self._currentZ:
|
||||
formattedCurrentZ = "%.2f mm" % (self._currentZ)
|
||||
self._stateMonitor.setCurrentZ(formattedCurrentZ)
|
||||
self._stateMonitor.setCurrentZ(self._currentZ)
|
||||
|
||||
def _setState(self, state):
|
||||
self._state = state
|
||||
@@ -272,34 +348,36 @@ class Printer():
|
||||
self._printTime = printTime
|
||||
self._printTimeLeft = printTimeLeft
|
||||
|
||||
formattedPrintTime = None
|
||||
if (self._printTime):
|
||||
formattedPrintTime = util.getFormattedTimeDelta(datetime.timedelta(seconds=self._printTime))
|
||||
self._stateMonitor.setProgress({
|
||||
"completion": self._progress * 100 if self._progress is not None else None,
|
||||
"filepos": filepos,
|
||||
"printTime": int(self._printTime) if self._printTime is not None else None,
|
||||
"printTimeLeft": int(self._printTimeLeft * 60) if self._printTimeLeft is not None else None
|
||||
})
|
||||
|
||||
formattedPrintTimeLeft = None
|
||||
if (self._printTimeLeft):
|
||||
formattedPrintTimeLeft = util.getFormattedTimeDelta(datetime.timedelta(minutes=self._printTimeLeft))
|
||||
def _addTemperatureData(self, temp, bedTemp):
|
||||
currentTimeUtc = int(time.time())
|
||||
|
||||
formattedFilePos = None
|
||||
if (filepos):
|
||||
formattedFilePos = util.getFormattedSize(filepos)
|
||||
data = {
|
||||
"time": currentTimeUtc
|
||||
}
|
||||
for tool in temp.keys():
|
||||
data["tool%d" % tool] = {
|
||||
"actual": temp[tool][0],
|
||||
"target": temp[tool][1]
|
||||
}
|
||||
if bedTemp is not None and isinstance(bedTemp, tuple):
|
||||
data["bed"] = {
|
||||
"actual": bedTemp[0],
|
||||
"target": bedTemp[1]
|
||||
}
|
||||
|
||||
self._stateMonitor.setProgress({"progress": self._progress, "filepos": formattedFilePos, "printTime": formattedPrintTime, "printTimeLeft": formattedPrintTimeLeft})
|
||||
|
||||
def _addTemperatureData(self, temp, bedTemp, targetTemp, bedTargetTemp):
|
||||
currentTimeUtc = int(time.time() * 1000)
|
||||
|
||||
self._temps["actual"].append((currentTimeUtc, temp))
|
||||
self._temps["target"].append((currentTimeUtc, targetTemp))
|
||||
self._temps["actualBed"].append((currentTimeUtc, bedTemp))
|
||||
self._temps["targetBed"].append((currentTimeUtc, bedTargetTemp))
|
||||
self._temps.append(data)
|
||||
|
||||
self._temp = temp
|
||||
self._bedTemp = bedTemp
|
||||
self._targetTemp = targetTemp
|
||||
self._targetBedTemp = bedTargetTemp
|
||||
|
||||
self._stateMonitor.addTemperature({"currentTime": currentTimeUtc, "temp": self._temp, "bedTemp": self._bedTemp, "targetTemp": self._targetTemp, "targetBedTemp": self._targetBedTemp})
|
||||
self._stateMonitor.addTemperature(data)
|
||||
|
||||
def _setJobData(self, filename, filesize, sd):
|
||||
if filename is not None:
|
||||
@@ -311,21 +389,14 @@ class Printer():
|
||||
else:
|
||||
self._selectedFile = None
|
||||
|
||||
formattedFilename = None
|
||||
formattedFilesize = None
|
||||
estimatedPrintTime = None
|
||||
fileMTime = None
|
||||
date = None
|
||||
filament = None
|
||||
if filename:
|
||||
formattedFilename = os.path.basename(filename)
|
||||
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
fileMTime = str(os.stat(filename).st_mtime)
|
||||
|
||||
if filesize:
|
||||
formattedFilesize = util.getFormattedSize(filesize)
|
||||
date = int(os.stat(filename).st_ctime)
|
||||
|
||||
fileData = self._gcodeManager.getFileData(filename)
|
||||
if fileData is not None and "gcodeAnalysis" in fileData.keys():
|
||||
@@ -334,15 +405,22 @@ class Printer():
|
||||
if "filament" in fileData["gcodeAnalysis"].keys():
|
||||
filament = fileData["gcodeAnalysis"]["filament"]
|
||||
|
||||
self._stateMonitor.setJobData({"filename": formattedFilename, "filesize": formattedFilesize, "estimatedPrintTime": estimatedPrintTime, "filament": filament, "sd": sd, "mtime": fileMTime})
|
||||
self._stateMonitor.setJobData({
|
||||
"file": {
|
||||
"name": os.path.basename(filename),
|
||||
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
"size": filesize,
|
||||
"date": date
|
||||
},
|
||||
"estimatedPrintTime": estimatedPrintTime,
|
||||
"filament": filament,
|
||||
})
|
||||
|
||||
def _sendInitialStateUpdate(self, callback):
|
||||
try:
|
||||
data = self._stateMonitor.getCurrentData()
|
||||
# convert the dict of deques to a dict of lists
|
||||
temps = {k: list(v) for (k,v) in self._temps.iteritems()}
|
||||
data.update({
|
||||
"temperatureHistory": temps,
|
||||
"tempHistory": list(self._temps),
|
||||
"logHistory": list(self._log),
|
||||
"messageHistory": list(self._messages)
|
||||
})
|
||||
@@ -353,11 +431,6 @@ class Printer():
|
||||
pass
|
||||
|
||||
def _getStateFlags(self):
|
||||
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
|
||||
sdReady = False
|
||||
else:
|
||||
sdReady = self._comm.isSdReady()
|
||||
|
||||
return {
|
||||
"operational": self.isOperational(),
|
||||
"printing": self.isPrinting(),
|
||||
@@ -365,7 +438,7 @@ class Printer():
|
||||
"error": self.isError(),
|
||||
"paused": self.isPaused(),
|
||||
"ready": self.isReady(),
|
||||
"sdReady": sdReady
|
||||
"sdReady": self.isSdReady()
|
||||
}
|
||||
|
||||
def getCurrentData(self):
|
||||
@@ -379,8 +452,8 @@ class Printer():
|
||||
"""
|
||||
self._addLog(message)
|
||||
|
||||
def mcTempUpdate(self, temp, bedTemp, targetTemp, bedTargetTemp):
|
||||
self._addTemperatureData(temp, bedTemp, targetTemp, bedTargetTemp)
|
||||
def mcTempUpdate(self, temp, bedTemp):
|
||||
self._addTemperatureData(temp, bedTemp)
|
||||
|
||||
def mcStateChange(self, state):
|
||||
"""
|
||||
@@ -424,7 +497,7 @@ class Printer():
|
||||
if newZ != oldZ:
|
||||
# we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or
|
||||
# anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes
|
||||
eventManager().fire("ZChange", newZ)
|
||||
eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ})
|
||||
|
||||
self._setCurrentZ(newZ)
|
||||
|
||||
@@ -432,7 +505,7 @@ class Printer():
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcSdFiles(self, files):
|
||||
self._sendTriggerUpdateCallbacks("gcodeFiles")
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
|
||||
self._sdFilelistAvailable.set()
|
||||
|
||||
def mcFileSelected(self, filename, filesize, sd):
|
||||
@@ -453,9 +526,13 @@ class Printer():
|
||||
self._setProgressData(0.0, 0, 0, None)
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcFileTransferDone(self):
|
||||
def mcFileTransferDone(self, filename):
|
||||
self._sdStreaming = False
|
||||
|
||||
if self._streamingFinishedCallback is not None:
|
||||
self._streamingFinishedCallback(self._sdRemoteName, FileDestinations.SDCARD)
|
||||
|
||||
self._sdRemoteName = None
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
@@ -471,15 +548,20 @@ class Printer():
|
||||
return []
|
||||
return self._comm.getSdFiles()
|
||||
|
||||
def addSdFile(self, filename, path):
|
||||
def addSdFile(self, filename, absolutePath, streamingFinishedCallback):
|
||||
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
|
||||
logging.error("No connection to printer or printer is busy")
|
||||
return
|
||||
|
||||
self._streamingFinishedCallback = streamingFinishedCallback
|
||||
|
||||
self.refreshSdFiles(blocking=True)
|
||||
existingSdFiles = self._comm.getSdFiles()
|
||||
|
||||
sdFilename = util.getDosFilename(filename, existingSdFiles)
|
||||
self._comm.startFileTransfer(path, sdFilename)
|
||||
remoteName = util.getDosFilename(filename, existingSdFiles)
|
||||
self._comm.startFileTransfer(absolutePath, filename, remoteName)
|
||||
|
||||
return remoteName
|
||||
|
||||
def deleteSdFile(self, filename):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
@@ -529,23 +611,36 @@ class Printer():
|
||||
|
||||
def getCurrentTemperatures(self):
|
||||
if self._comm is not None:
|
||||
(tempOffset, bedTempOffset) = self._comm.getOffsets()
|
||||
tempOffset, bedTempOffset = self._comm.getOffsets()
|
||||
else:
|
||||
tempOffset = 0
|
||||
bedTempOffset = 0
|
||||
tempOffset = {}
|
||||
bedTempOffset = None
|
||||
|
||||
return {
|
||||
"extruder": {
|
||||
"current": self._temp,
|
||||
"target": self._targetTemp,
|
||||
"offset": tempOffset
|
||||
},
|
||||
"bed": {
|
||||
"current": self._bedTemp,
|
||||
"target": self._targetBedTemp,
|
||||
result = {}
|
||||
for tool in self._temp.keys():
|
||||
result["tool%d" % tool] = {
|
||||
"actual": self._temp[tool][0],
|
||||
"target": self._temp[tool][1],
|
||||
"offset": tempOffset[tool] if tool in tempOffset.keys() and tempOffset[tool] is not None else 0
|
||||
}
|
||||
if self._bedTemp is not None:
|
||||
result["bed"] = {
|
||||
"actual": self._bedTemp[0],
|
||||
"target": self._bedTemp[1],
|
||||
"offset": bedTempOffset
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
def getTemperatureHistory(self):
|
||||
return self._temps
|
||||
|
||||
def getCurrentConnection(self):
|
||||
if self._comm is None:
|
||||
return "Closed", None, None
|
||||
|
||||
port, baudrate = self._comm.getConnection()
|
||||
return self._comm.getStateString(), port, baudrate
|
||||
|
||||
def isClosedOrError(self):
|
||||
return self._comm is None or self._comm.isClosedOrError()
|
||||
@@ -565,6 +660,12 @@ class Printer():
|
||||
def isReady(self):
|
||||
return self.isOperational() and not self._comm.isStreaming()
|
||||
|
||||
def isSdReady(self):
|
||||
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
|
||||
return False
|
||||
else:
|
||||
return self._comm.isSdReady()
|
||||
|
||||
def isLoading(self):
|
||||
return self._gcodeLoader is not None
|
||||
|
||||
@@ -583,10 +684,10 @@ class StateMonitor(object):
|
||||
self._currentZ = None
|
||||
self._progress = None
|
||||
|
||||
self._tempOffset = 0
|
||||
self._bedTempOffset = 0
|
||||
self._offsets = {}
|
||||
|
||||
self._changeEvent = threading.Event()
|
||||
self._stateMutex = threading.Lock()
|
||||
|
||||
self._lastUpdate = time.time()
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
@@ -616,8 +717,9 @@ class StateMonitor(object):
|
||||
self._changeEvent.set()
|
||||
|
||||
def setState(self, state):
|
||||
self._state = state
|
||||
self._changeEvent.set()
|
||||
with self._stateMutex:
|
||||
self._state = state
|
||||
self._changeEvent.set()
|
||||
|
||||
def setJobData(self, jobData):
|
||||
self._jobData = jobData
|
||||
@@ -627,27 +729,25 @@ class StateMonitor(object):
|
||||
self._progress = progress
|
||||
self._changeEvent.set()
|
||||
|
||||
def setTempOffsets(self, tempOffset, bedTempOffset):
|
||||
if tempOffset is not None:
|
||||
self._tempOffset = tempOffset
|
||||
if bedTempOffset is not None:
|
||||
self._bedTempOffset = bedTempOffset
|
||||
def setTempOffsets(self, offsets):
|
||||
self._offsets = offsets
|
||||
self._changeEvent.set()
|
||||
|
||||
def _work(self):
|
||||
while True:
|
||||
self._changeEvent.wait()
|
||||
|
||||
now = time.time()
|
||||
delta = now - self._lastUpdate
|
||||
additionalWaitTime = self._ratelimit - delta
|
||||
if additionalWaitTime > 0:
|
||||
time.sleep(additionalWaitTime)
|
||||
with self._stateMutex:
|
||||
now = time.time()
|
||||
delta = now - self._lastUpdate
|
||||
additionalWaitTime = self._ratelimit - delta
|
||||
if additionalWaitTime > 0:
|
||||
time.sleep(additionalWaitTime)
|
||||
|
||||
data = self.getCurrentData()
|
||||
self._updateCallback(data)
|
||||
self._lastUpdate = time.time()
|
||||
self._changeEvent.clear()
|
||||
data = self.getCurrentData()
|
||||
self._updateCallback(data)
|
||||
self._lastUpdate = time.time()
|
||||
self._changeEvent.clear()
|
||||
|
||||
def getCurrentData(self):
|
||||
return {
|
||||
@@ -655,6 +755,6 @@ class StateMonitor(object):
|
||||
"job": self._jobData,
|
||||
"currentZ": self._currentZ,
|
||||
"progress": self._progress,
|
||||
"offsets": (self._tempOffset, self._bedTempOffset)
|
||||
"offsets": self._offsets
|
||||
}
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import flask
|
||||
import tornado.wsgi
|
||||
from sockjs.tornado import SockJSRouter
|
||||
from flask import Flask, render_template, send_from_directory, make_response
|
||||
from flask.ext.login import LoginManager
|
||||
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
|
||||
|
||||
import os
|
||||
import logging
|
||||
import logging.config
|
||||
|
||||
SUCCESS = {}
|
||||
NO_CONTENT = ("", 204)
|
||||
|
||||
app = Flask("octoprint")
|
||||
debug = False
|
||||
|
||||
printer = None
|
||||
gcodeManager = None
|
||||
userManager = None
|
||||
eventManager = None
|
||||
loginManager = None
|
||||
|
||||
principals = Principal(app)
|
||||
admin_permission = Permission(RoleNeed("admin"))
|
||||
user_permission = Permission(RoleNeed("user"))
|
||||
|
||||
# only import the octoprint stuff down here, as it might depend on things defined above to be initialized already
|
||||
from octoprint.server.util import LargeResponseHandler, ReverseProxied, restricted_access, PrinterStateConnection, admin_validator
|
||||
from octoprint.printer import Printer, getConnectionOptions
|
||||
from octoprint.settings import settings
|
||||
import octoprint.gcodefiles as gcodefiles
|
||||
import octoprint.util as util
|
||||
import octoprint.users as users
|
||||
import octoprint.events as events
|
||||
import octoprint.timelapse
|
||||
import octoprint._version
|
||||
|
||||
|
||||
|
||||
versions = octoprint._version.get_versions()
|
||||
VERSION = versions['version']
|
||||
BRANCH = versions['branch'] if 'branch' in versions else None
|
||||
DISPLAY_VERSION = "%s (%s branch)" % (VERSION, BRANCH) if BRANCH else VERSION
|
||||
del versions
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return render_template(
|
||||
"index.jinja2",
|
||||
webcamStream=settings().get(["webcam", "stream"]),
|
||||
enableTimelapse=(settings().get(["webcam", "snapshot"]) is not None and settings().get(["webcam", "ffmpeg"]) is not None),
|
||||
enableGCodeVisualizer=settings().get(["gcodeViewer", "enabled"]),
|
||||
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
|
||||
enableSystemMenu=settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0,
|
||||
enableAccessControl=userManager is not None,
|
||||
enableSdSupport=settings().get(["feature", "sdSupport"]),
|
||||
firstRun=settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()),
|
||||
debug=debug,
|
||||
version=VERSION,
|
||||
display_version=DISPLAY_VERSION,
|
||||
stylesheet=settings().get(["devel", "stylesheet"]),
|
||||
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
|
||||
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"])
|
||||
)
|
||||
|
||||
|
||||
@app.route("/robots.txt")
|
||||
def robotsTxt():
|
||||
return send_from_directory(app.static_folder, "robots.txt")
|
||||
|
||||
|
||||
@identity_loaded.connect_via(app)
|
||||
def on_identity_loaded(sender, identity):
|
||||
user = load_user(identity.id)
|
||||
if user is None:
|
||||
return
|
||||
|
||||
identity.provides.add(UserNeed(user.get_name()))
|
||||
if user.is_user():
|
||||
identity.provides.add(RoleNeed("user"))
|
||||
if user.is_admin():
|
||||
identity.provides.add(RoleNeed("admin"))
|
||||
|
||||
|
||||
def load_user(id):
|
||||
if userManager is not None:
|
||||
return userManager.findUser(id)
|
||||
return users.DummyUser()
|
||||
|
||||
|
||||
#~~ startup code
|
||||
|
||||
|
||||
class Server():
|
||||
def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False):
|
||||
self._configfile = configfile
|
||||
self._basedir = basedir
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._debug = debug
|
||||
self._allowRoot = allowRoot
|
||||
|
||||
|
||||
def run(self):
|
||||
if not self._allowRoot:
|
||||
self._checkForRoot()
|
||||
|
||||
global printer
|
||||
global gcodeManager
|
||||
global userManager
|
||||
global eventManager
|
||||
global loginManager
|
||||
global debug
|
||||
|
||||
from tornado.wsgi import WSGIContainer
|
||||
from tornado.httpserver import HTTPServer
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.web import Application, FallbackHandler
|
||||
|
||||
debug = self._debug
|
||||
|
||||
# first initialize the settings singleton and make sure it uses given configfile and basedir if available
|
||||
self._initSettings(self._configfile, self._basedir)
|
||||
|
||||
# then initialize logging
|
||||
self._initLogging(self._debug)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)
|
||||
|
||||
eventManager = events.eventManager()
|
||||
gcodeManager = gcodefiles.GcodeManager()
|
||||
printer = Printer(gcodeManager)
|
||||
|
||||
# configure timelapse
|
||||
octoprint.timelapse.configureTimelapse()
|
||||
|
||||
# setup command triggers
|
||||
events.CommandTrigger(printer)
|
||||
if self._debug:
|
||||
events.DebugEventListener()
|
||||
|
||||
if settings().getBoolean(["accessControl", "enabled"]):
|
||||
userManagerName = settings().get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = util.getClass(userManagerName)
|
||||
userManager = clazz()
|
||||
except AttributeError, e:
|
||||
logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName)
|
||||
|
||||
app.wsgi_app = ReverseProxied(app.wsgi_app)
|
||||
|
||||
app.secret_key = "k3PuVYgtxNm8DXKKTw2nWmFQQun9qceV"
|
||||
loginManager = LoginManager()
|
||||
loginManager.session_protection = "strong"
|
||||
loginManager.user_callback = load_user
|
||||
if userManager is None:
|
||||
loginManager.anonymous_user = users.DummyUser
|
||||
principals.identity_loaders.appendleft(users.dummy_identity_loader)
|
||||
loginManager.init_app(app)
|
||||
|
||||
if self._host is None:
|
||||
self._host = settings().get(["server", "host"])
|
||||
if self._port is None:
|
||||
self._port = settings().getInt(["server", "port"])
|
||||
|
||||
logger.info("Listening on http://%s:%d" % (self._host, self._port))
|
||||
app.debug = self._debug
|
||||
|
||||
from octoprint.server.api import api
|
||||
|
||||
app.register_blueprint(api, url_prefix="/api")
|
||||
|
||||
self._router = SockJSRouter(self._createSocketConnection, "/sockjs")
|
||||
|
||||
def admin_access_validation(request):
|
||||
"""
|
||||
Creates a custom wsgi and Flask request context in order to be able to process user information
|
||||
stored in the current session.
|
||||
|
||||
:param request: The Tornado request for which to create the environment and context
|
||||
"""
|
||||
wsgi_environ = tornado.wsgi.WSGIContainer.environ(request)
|
||||
with app.request_context(wsgi_environ):
|
||||
app.session_interface.open_session(app, flask.request)
|
||||
loginManager.reload_user()
|
||||
admin_validator(flask.request)
|
||||
|
||||
self._tornado_app = Application(self._router.urls + [
|
||||
(r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, {"path": settings().getBaseFolder("timelapse"), "as_attachment": True}),
|
||||
(r"/downloads/files/local/([^/]*\.(gco|gcode))", LargeResponseHandler, {"path": settings().getBaseFolder("uploads"), "as_attachment": True}),
|
||||
(r"/downloads/logs/([^/]*)", LargeResponseHandler, {"path": settings().getBaseFolder("logs"), "as_attachment": True, "access_validation": admin_access_validation}),
|
||||
(r".*", FallbackHandler, {"fallback": WSGIContainer(app.wsgi_app)})
|
||||
])
|
||||
self._server = HTTPServer(self._tornado_app)
|
||||
self._server.listen(self._port, address=self._host)
|
||||
|
||||
eventManager.fire(events.Events.STARTUP)
|
||||
if settings().getBoolean(["serial", "autoconnect"]):
|
||||
(port, baudrate) = settings().get(["serial", "port"]), settings().getInt(["serial", "baudrate"])
|
||||
connectionOptions = getConnectionOptions()
|
||||
if port in connectionOptions["ports"]:
|
||||
printer.connect(port, baudrate)
|
||||
try:
|
||||
IOLoop.instance().start()
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Goodbye!")
|
||||
except:
|
||||
logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!")
|
||||
logger.exception("Stacktrace follows:")
|
||||
|
||||
def _createSocketConnection(self, session):
|
||||
global printer, gcodeManager, userManager, eventManager
|
||||
return PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session)
|
||||
|
||||
def _checkForRoot(self):
|
||||
if "geteuid" in dir(os) and os.geteuid() == 0:
|
||||
exit("You should not run OctoPrint as root!")
|
||||
|
||||
def _initSettings(self, configfile, basedir):
|
||||
settings(init=True, basedir=basedir, configfile=configfile)
|
||||
|
||||
def _initLogging(self, debug):
|
||||
config = {
|
||||
"version": 1,
|
||||
"formatters": {
|
||||
"simple": {
|
||||
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
}
|
||||
},
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "simple",
|
||||
"stream": "ext://sys.stdout"
|
||||
},
|
||||
"file": {
|
||||
"class": "logging.handlers.TimedRotatingFileHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "simple",
|
||||
"when": "D",
|
||||
"backupCount": "1",
|
||||
"filename": os.path.join(settings().getBaseFolder("logs"), "octoprint.log")
|
||||
},
|
||||
"serialFile": {
|
||||
"class": "logging.handlers.RotatingFileHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "simple",
|
||||
"maxBytes": 2 * 1024 * 1024, # let's limit the serial log to 2MB in size
|
||||
"filename": os.path.join(settings().getBaseFolder("logs"), "serial.log")
|
||||
}
|
||||
},
|
||||
"loggers": {
|
||||
#"octoprint.timelapse": {
|
||||
# "level": "DEBUG"
|
||||
#},
|
||||
#"octoprint.events": {
|
||||
# "level": "DEBUG"
|
||||
#},
|
||||
"SERIAL": {
|
||||
"level": "CRITICAL",
|
||||
"handlers": ["serialFile"],
|
||||
"propagate": False
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"level": "INFO",
|
||||
"handlers": ["console", "file"]
|
||||
}
|
||||
}
|
||||
|
||||
if debug:
|
||||
config["root"]["level"] = "DEBUG"
|
||||
|
||||
logging.config.dictConfig(config)
|
||||
|
||||
if settings().getBoolean(["serial", "log"]):
|
||||
# enable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
|
||||
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
||||
|
||||
if __name__ == "__main__":
|
||||
octoprint = Server()
|
||||
octoprint.run()
|
||||
@@ -0,0 +1,167 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
import netaddr
|
||||
|
||||
from flask import Blueprint, request, jsonify, abort, current_app, session, make_response
|
||||
from flask.ext.login import login_user, logout_user, current_user
|
||||
from flask.ext.principal import Identity, identity_changed, AnonymousIdentity
|
||||
|
||||
import octoprint.util as util
|
||||
import octoprint.users
|
||||
import octoprint.server
|
||||
from octoprint.server import restricted_access, admin_permission, NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
|
||||
#~~ init api blueprint, including sub modules
|
||||
|
||||
api = Blueprint("api", __name__)
|
||||
|
||||
from . import printer as api_printer
|
||||
from . import job as api_job
|
||||
from . import connection as api_connection
|
||||
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
|
||||
|
||||
|
||||
VERSION = "0.1"
|
||||
|
||||
#~~ first run setup
|
||||
|
||||
|
||||
@api.route("/setup", methods=["POST"])
|
||||
def firstRunSetup():
|
||||
if not s().getBoolean(["server", "firstRun"]):
|
||||
abort(403)
|
||||
|
||||
if "ac" in request.values.keys() and request.values["ac"] in valid_boolean_trues and \
|
||||
"user" in request.values.keys() and "pass1" in request.values.keys() and \
|
||||
"pass2" in request.values.keys() and request.values["pass1"] == request.values["pass2"]:
|
||||
# configure access control
|
||||
s().setBoolean(["accessControl", "enabled"], True)
|
||||
octoprint.server.userManager.addUser(request.values["user"], request.values["pass1"], True, ["user", "admin"])
|
||||
s().setBoolean(["server", "firstRun"], False)
|
||||
elif "ac" in request.values.keys() and not request.values["ac"] in valid_boolean_trues:
|
||||
# disable access control
|
||||
s().setBoolean(["accessControl", "enabled"], False)
|
||||
s().setBoolean(["server", "firstRun"], False)
|
||||
|
||||
octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
|
||||
octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
|
||||
|
||||
s().save()
|
||||
return NO_CONTENT
|
||||
|
||||
#~~ system state
|
||||
|
||||
|
||||
@api.route("/state", methods=["GET"])
|
||||
@restricted_access
|
||||
def apiPrinterState():
|
||||
currentData = octoprint.server.printer.getCurrentData()
|
||||
currentData.update({
|
||||
"temperatures": octoprint.server.printer.getCurrentTemperatures()
|
||||
})
|
||||
return jsonify(currentData)
|
||||
|
||||
|
||||
@api.route("/version", methods=["GET"])
|
||||
@restricted_access
|
||||
def apiVersion():
|
||||
return jsonify({
|
||||
"server": octoprint.server.VERSION,
|
||||
"api": octoprint.server.api.VERSION
|
||||
})
|
||||
|
||||
#~~ system control
|
||||
|
||||
|
||||
@api.route("/system", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def performSystemAction():
|
||||
logger = logging.getLogger(__name__)
|
||||
if request.values.has_key("action"):
|
||||
action = request.values["action"]
|
||||
availableActions = s().get(["system", "actions"])
|
||||
for availableAction in availableActions:
|
||||
if availableAction["action"] == action:
|
||||
logger.info("Performing command: %s" % availableAction["command"])
|
||||
try:
|
||||
subprocess.check_output(availableAction["command"], shell=True)
|
||||
except subprocess.CalledProcessError, e:
|
||||
logger.warn("Command failed with return code %i: %s" % (e.returncode, e.message))
|
||||
return make_response(("Command failed with return code %i: %s" % (e.returncode, e.message), 500, []))
|
||||
except Exception, ex:
|
||||
logger.exception("Command failed")
|
||||
return make_response(("Command failed: %r" % ex, 500, []))
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
#~~ Login/user handling
|
||||
|
||||
|
||||
@api.route("/login", methods=["POST"])
|
||||
def login():
|
||||
if octoprint.server.userManager is not None and "user" in request.values.keys() and "pass" in request.values.keys():
|
||||
username = request.values["user"]
|
||||
password = request.values["pass"]
|
||||
|
||||
if "remember" in request.values.keys() and request.values["remember"] == "true":
|
||||
remember = True
|
||||
else:
|
||||
remember = False
|
||||
|
||||
user = octoprint.server.userManager.findUser(username)
|
||||
if user is not None:
|
||||
if user.check_password(octoprint.users.UserManager.createPasswordHash(password)):
|
||||
login_user(user, remember=remember)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
return make_response(("User unknown or password incorrect", 401, []))
|
||||
elif "passive" in request.values.keys():
|
||||
user = current_user
|
||||
if user is not None and not user.is_anonymous():
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
elif s().getBoolean(["accessControl", "autologinLocal"]) \
|
||||
and s().get(["accessControl", "autologinAs"]) is not None \
|
||||
and s().get(["accessControl", "localNetworks"]) is not None:
|
||||
|
||||
autologinAs = s().get(["accessControl", "autologinAs"])
|
||||
localNetworks = netaddr.IPSet([])
|
||||
for ip in s().get(["accessControl", "localNetworks"]):
|
||||
localNetworks.add(ip)
|
||||
|
||||
try:
|
||||
remoteAddr = util.getRemoteAddress(request)
|
||||
if netaddr.IPAddress(remoteAddr) in localNetworks:
|
||||
user = octoprint.server.userManager.findUser(autologinAs)
|
||||
if user is not None:
|
||||
login_user(user)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
except:
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/logout", methods=["POST"])
|
||||
@restricted_access
|
||||
def logout():
|
||||
# Remove session keys set by Flask-Principal
|
||||
for key in ('identity.id', 'identity.auth_type'):
|
||||
del session[key]
|
||||
identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
|
||||
|
||||
logout_user()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
from flask import request, jsonify, make_response
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.printer import getConnectionOptions
|
||||
from octoprint.server import printer, restricted_access, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
import octoprint.util as util
|
||||
|
||||
|
||||
@api.route("/connection", methods=["GET"])
|
||||
def connectionState():
|
||||
state, port, baudrate = printer.getCurrentConnection()
|
||||
current = {
|
||||
"state": state,
|
||||
"port": port,
|
||||
"baudrate": baudrate
|
||||
}
|
||||
return jsonify({"current": current, "options": getConnectionOptions()})
|
||||
|
||||
|
||||
@api.route("/connection", methods=["POST"])
|
||||
@restricted_access
|
||||
def connectionCommand():
|
||||
valid_commands = {
|
||||
"connect": ["autoconnect"],
|
||||
"disconnect": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "connect":
|
||||
options = getConnectionOptions()
|
||||
|
||||
port = None
|
||||
baudrate = None
|
||||
if "port" in data.keys():
|
||||
port = data["port"]
|
||||
if port not in options["ports"]:
|
||||
return make_response("Invalid port: %s" % port, 400)
|
||||
if "baudrate" in data.keys():
|
||||
baudrate = data["baudrate"]
|
||||
if baudrate not in options["baudrates"]:
|
||||
return make_response("Invalid baudrate: %d" % baudrate, 400)
|
||||
if "save" in data.keys() and data["save"]:
|
||||
settings().set(["serial", "port"], port)
|
||||
settings().setInt(["serial", "baudrate"], baudrate)
|
||||
if "autoconnect" in data.keys():
|
||||
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
|
||||
settings().save()
|
||||
printer.connect(port=port, baudrate=baudrate)
|
||||
elif command == "disconnect":
|
||||
printer.disconnect()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
# coding=utf-8
|
||||
from octoprint.events import Events
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
from flask import request, jsonify, make_response, url_for
|
||||
|
||||
import octoprint.gcodefiles as gcodefiles
|
||||
import octoprint.util as util
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, gcodeManager, eventManager, restricted_access, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
|
||||
|
||||
#~~ GCODE file handling
|
||||
|
||||
|
||||
@api.route("/files", methods=["GET"])
|
||||
def readGcodeFiles():
|
||||
files = _getFileList(FileDestinations.LOCAL)
|
||||
files.extend(_getFileList(FileDestinations.SDCARD))
|
||||
return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads")))
|
||||
|
||||
|
||||
@api.route("/files/<string:origin>", methods=["GET"])
|
||||
def readGcodeFilesForOrigin(origin):
|
||||
if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown origin: %s" % origin, 404)
|
||||
|
||||
files = _getFileList(origin)
|
||||
|
||||
if origin == FileDestinations.LOCAL:
|
||||
return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads")))
|
||||
else:
|
||||
return jsonify(files=files)
|
||||
|
||||
|
||||
def _getFileDetails(origin, filename):
|
||||
files = _getFileList(origin)
|
||||
for file in files:
|
||||
if file["name"] == filename:
|
||||
return file
|
||||
return None
|
||||
|
||||
|
||||
def _getFileList(origin):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
sdFileList = printer.getSdFiles()
|
||||
|
||||
files = []
|
||||
if sdFileList is not None:
|
||||
for sdFile in sdFileList:
|
||||
files.append({
|
||||
"name": sdFile,
|
||||
"origin": FileDestinations.SDCARD,
|
||||
"refs": {
|
||||
"resource": url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFile, _external=True)
|
||||
}
|
||||
})
|
||||
else:
|
||||
files = gcodeManager.getAllFileData()
|
||||
for file in files:
|
||||
file.update({
|
||||
"refs": {
|
||||
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file["name"], _external=True),
|
||||
"download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + file["name"]
|
||||
}
|
||||
})
|
||||
return files
|
||||
|
||||
|
||||
def _verifyFileExists(origin, filename):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
availableFiles = printer.getSdFiles()
|
||||
else:
|
||||
availableFiles = gcodeManager.getAllFilenames()
|
||||
|
||||
return filename in availableFiles
|
||||
|
||||
|
||||
@api.route("/files/<string:target>", methods=["POST"])
|
||||
@restricted_access
|
||||
def uploadGcodeFile(target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
|
||||
if not "file" in request.files.keys():
|
||||
return make_response("No file included", 400)
|
||||
|
||||
if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD card support is disabled", 404)
|
||||
|
||||
file = request.files["file"]
|
||||
sd = target == FileDestinations.SDCARD
|
||||
selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues
|
||||
printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues
|
||||
|
||||
if sd:
|
||||
# validate that all preconditions for SD upload are met before attempting it
|
||||
if not (printer.isOperational() and not (printer.isPrinting() or printer.isPaused())):
|
||||
return make_response("Can not upload to SD card, printer is either not operational or already busy", 409)
|
||||
if not printer.isSdReady():
|
||||
return make_response("Can not upload to SD card, not yet initialized", 409)
|
||||
|
||||
# determine current job
|
||||
currentFilename = None
|
||||
currentSd = None
|
||||
currentJob = printer.getCurrentJob()
|
||||
if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys():
|
||||
currentFilename = currentJob["filename"]
|
||||
currentSd = currentJob["sd"]
|
||||
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
futureFilename = gcodeManager.getFutureFilename(file)
|
||||
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)):
|
||||
return make_response("Can not upload file %s, wrong format?" % file.filename, 415)
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
if futureFilename == currentFilename and sd == currentSd and printer.isPrinting() or printer.isPaused():
|
||||
return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409)
|
||||
|
||||
filename = None
|
||||
|
||||
def fileProcessingFinished(filename, absFilename, destination):
|
||||
"""
|
||||
Callback for when the file processing (upload, optional slicing, addition to analysis queue) has
|
||||
finished.
|
||||
|
||||
Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint.
|
||||
"""
|
||||
if destination == FileDestinations.SDCARD:
|
||||
return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint)
|
||||
else:
|
||||
selectAndOrPrint(absFilename, destination)
|
||||
return filename
|
||||
|
||||
def selectAndOrPrint(nameToSelect, destination):
|
||||
"""
|
||||
Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only
|
||||
the case after they have finished streaming to the printer, which is why this callback is also used
|
||||
for the corresponding call to addSdFile.
|
||||
|
||||
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
|
||||
exact file is already selected, such reloading it.
|
||||
"""
|
||||
sd = destination == FileDestinations.SDCARD
|
||||
if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentSd == sd):
|
||||
printer.selectFile(nameToSelect, sd, printAfterSelect)
|
||||
|
||||
destination = FileDestinations.SDCARD if sd else FileDestinations.LOCAL
|
||||
filename, done = gcodeManager.addFile(file, destination, fileProcessingFinished)
|
||||
if filename is None:
|
||||
return make_response("Could not upload the file %s" % file.filename, 500)
|
||||
|
||||
sdFilename = None
|
||||
if isinstance(filename, tuple):
|
||||
filename, sdFilename = filename
|
||||
|
||||
eventManager.fire(Events.UPLOAD, {"file": filename, "target": target})
|
||||
|
||||
files = {}
|
||||
if done:
|
||||
files.update({
|
||||
FileDestinations.LOCAL: {
|
||||
"name": filename,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"refs": {
|
||||
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True),
|
||||
"download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if sd and sdFilename:
|
||||
files.update({
|
||||
FileDestinations.SDCARD: {
|
||||
"name": sdFilename,
|
||||
"origin": FileDestinations.SDCARD,
|
||||
"refs": {
|
||||
"resource": url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return make_response(jsonify(files=files, done=done), 201)
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["GET"])
|
||||
def readGcodeFile(target, filename):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
|
||||
file = _getFileDetails(target, filename)
|
||||
if not file:
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
return jsonify(file)
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["POST"])
|
||||
@restricted_access
|
||||
def gcodeFileCommand(filename, target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
# valid file commands, dict mapping command name to mandatory parameters
|
||||
valid_commands = {
|
||||
"select": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "select":
|
||||
# selects/loads a file
|
||||
printAfterLoading = False
|
||||
if "print" in data.keys() and data["print"]:
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||
printAfterLoading = True
|
||||
|
||||
sd = False
|
||||
if target == FileDestinations.SDCARD:
|
||||
filenameToSelect = filename
|
||||
sd = True
|
||||
else:
|
||||
filenameToSelect = gcodeManager.getAbsolutePath(filename)
|
||||
printer.selectFile(filenameToSelect, sd, printAfterLoading)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteGcodeFile(filename, target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
sd = target == FileDestinations.SDCARD
|
||||
|
||||
currentJob = printer.getCurrentJob()
|
||||
currentFilename = None
|
||||
currentSd = None
|
||||
if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys():
|
||||
currentFilename = currentJob["filename"]
|
||||
currentSd = currentJob["sd"]
|
||||
|
||||
# prohibit deleting the file that is currently being printed
|
||||
if currentFilename == filename and currentSd == sd and (printer.isPrinting() or printer.isPaused()):
|
||||
make_response("Trying to delete file that is currently being printed: %s" % filename, 409)
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
if currentFilename is not None and filename == currentFilename:
|
||||
printer.unselectFile()
|
||||
|
||||
# delete it
|
||||
if sd:
|
||||
printer.deleteSdFile(filename)
|
||||
else:
|
||||
gcodeManager.removeFile(filename)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
from flask import request, make_response, jsonify
|
||||
|
||||
from octoprint.server import printer, restricted_access, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
import octoprint.util as util
|
||||
|
||||
|
||||
@api.route("/job", methods=["POST"])
|
||||
@restricted_access
|
||||
def controlJob():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
"start": [],
|
||||
"restart": [],
|
||||
"pause": [],
|
||||
"cancel": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
activePrintjob = printer.isPrinting() or printer.isPaused()
|
||||
|
||||
if command == "start":
|
||||
if activePrintjob:
|
||||
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
|
||||
printer.startPrint()
|
||||
elif command == "restart":
|
||||
if not printer.isPaused():
|
||||
return make_response("Printer does not have an active print job or is not paused", 409)
|
||||
printer.startPrint()
|
||||
elif command == "pause":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
|
||||
printer.togglePausePrint()
|
||||
elif command == "cancel":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
|
||||
printer.cancelPrint()
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/job", methods=["GET"])
|
||||
def jobState():
|
||||
currentData = printer.getCurrentData()
|
||||
return jsonify({
|
||||
"job": currentData["job"],
|
||||
"progress": currentData["progress"],
|
||||
"state": currentData["state"]["stateString"]
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Marc Hannappel Salandora"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import os
|
||||
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
from octoprint.settings import settings
|
||||
|
||||
from octoprint.server import restricted_access, NO_CONTENT, admin_permission
|
||||
from octoprint.server.util import redirectToTornado
|
||||
from octoprint.server.api import api
|
||||
from octoprint.util import getFreeBytes
|
||||
|
||||
|
||||
@api.route("/logs", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def getLogFiles():
|
||||
files = _getLogFiles()
|
||||
return jsonify(files=files, free=getFreeBytes(settings().getBaseFolder("logs")))
|
||||
|
||||
|
||||
@api.route("/logs/<path:filename>", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def downloadLog(filename):
|
||||
return redirectToTornado(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 osFile in os.listdir(basedir):
|
||||
statResult = os.stat(os.path.join(basedir, osFile))
|
||||
files.append({
|
||||
"name": osFile,
|
||||
"date": int(statResult.st_mtime),
|
||||
"size": statResult.st_size,
|
||||
"refs": {
|
||||
"resource": url_for(".downloadLog", filename=osFile, _external=True),
|
||||
"download": url_for("index", _external=True) + "downloads/logs/" + osFile
|
||||
}
|
||||
})
|
||||
|
||||
return files
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
from flask import request, jsonify, make_response
|
||||
import re
|
||||
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, restricted_access, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
import octoprint.util as util
|
||||
|
||||
#~~ Printer
|
||||
|
||||
@api.route("/printer", methods=["GET"])
|
||||
def printerState():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
result = {}
|
||||
result.update(_getTemperatureData(lambda x: x))
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
#~~ Tool
|
||||
|
||||
|
||||
@api.route("/printer/tool", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerToolCommand():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
"select": ["tool"],
|
||||
"target": ["targets"],
|
||||
"offset": ["offsets"],
|
||||
"extrude": ["amount"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
validation_regex = re.compile("tool\d+")
|
||||
|
||||
##~~ tool selection
|
||||
if command == "select":
|
||||
tool = data["tool"]
|
||||
if re.match(validation_regex, tool) is None:
|
||||
return make_response("Invalid tool: %s" % tool, 400)
|
||||
if not tool.startswith("tool"):
|
||||
return make_response("Invalid tool for selection: %s" % tool, 400)
|
||||
|
||||
printer.changeTool(tool)
|
||||
|
||||
##~~ temperature
|
||||
elif command == "target":
|
||||
targets = data["targets"]
|
||||
|
||||
# make sure the targets are valid and the values are numbers
|
||||
validated_values = {}
|
||||
for tool, value in targets.iteritems():
|
||||
if re.match(validation_regex, tool) is None:
|
||||
return make_response("Invalid target for setting temperature: %s" % tool, 400)
|
||||
if not isinstance(value, (int, long, float)):
|
||||
return make_response("Not a number for %s: %r" % (tool, value), 400)
|
||||
validated_values[tool] = value
|
||||
|
||||
# perform the actual temperature commands
|
||||
for tool in validated_values.keys():
|
||||
printer.setTemperature(tool, validated_values[tool])
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
offsets = data["offsets"]
|
||||
|
||||
# make sure the targets are valid, the values are numbers and in the range [-50, 50]
|
||||
validated_values = {}
|
||||
for tool, value in offsets.iteritems():
|
||||
if re.match(validation_regex, tool) is None:
|
||||
return make_response("Invalid target for setting temperature: %s" % tool, 400)
|
||||
if not isinstance(value, (int, long, float)):
|
||||
return make_response("Not a number for %s: %r" % (tool, value), 400)
|
||||
if not -50 <= value <= 50:
|
||||
return make_response("Offset %s not in range [-50, 50]: %f" % (tool, value), 400)
|
||||
validated_values[tool] = value
|
||||
|
||||
# set the offsets
|
||||
printer.setTemperatureOffset(validated_values)
|
||||
|
||||
##~~ extrusion
|
||||
elif command == "extrude":
|
||||
if printer.isPrinting():
|
||||
# do not extrude when a print job is running
|
||||
return make_response("Printer is currently printing", 409)
|
||||
|
||||
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)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/tool", methods=["GET"])
|
||||
def printerToolState():
|
||||
def deleteBed(x):
|
||||
data = dict(x)
|
||||
|
||||
if "bed" in data.keys():
|
||||
del data["bed"]
|
||||
return data
|
||||
|
||||
return jsonify(_getTemperatureData(deleteBed))
|
||||
|
||||
|
||||
##~~ Heated bed
|
||||
|
||||
|
||||
@api.route("/printer/bed", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerBedCommand():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
"target": ["target"],
|
||||
"offset": ["offset"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
##~~ temperature
|
||||
if command == "target":
|
||||
target = data["target"]
|
||||
|
||||
# make sure the target is a number
|
||||
if not isinstance(target, (int, long, float)):
|
||||
return make_response("Not a number: %r" % target, 400)
|
||||
|
||||
# perform the actual temperature command
|
||||
printer.setTemperature("bed", target)
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
offset = data["offsets"]
|
||||
|
||||
# make sure the offset is valid
|
||||
if not isinstance(offset, (int, long, float)):
|
||||
return make_response("Not a number: %r" % offset, 400)
|
||||
if not -50 <= offset <= 50:
|
||||
return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
|
||||
|
||||
# set the offsets
|
||||
printer.setTemperatureOffset({"bed": offset})
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/bed", methods=["GET"])
|
||||
def printerBedState():
|
||||
def deleteTools(x):
|
||||
data = dict(x)
|
||||
|
||||
for k in data.keys():
|
||||
if k.startswith("tool"):
|
||||
del data[k]
|
||||
return data
|
||||
|
||||
return jsonify(_getTemperatureData(deleteTools))
|
||||
|
||||
|
||||
##~~ Print head
|
||||
|
||||
|
||||
@api.route("/printer/printhead", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerPrintheadCommand():
|
||||
if not printer.isOperational() or printer.isPrinting():
|
||||
# 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)
|
||||
|
||||
valid_commands = {
|
||||
"jog": [],
|
||||
"home": ["axes"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
valid_axes = ["x", "y", "z"]
|
||||
##~~ jog command
|
||||
if command == "jog":
|
||||
# validate all jog instructions, make sure that the values are numbers
|
||||
validated_values = {}
|
||||
for axis in valid_axes:
|
||||
if axis in data:
|
||||
value = data[axis]
|
||||
if not isinstance(value, (int, long, float)):
|
||||
return make_response("Not a number for axis %s: %r" % (axis, value), 400)
|
||||
validated_values[axis] = value
|
||||
|
||||
# execute the jog commands
|
||||
for axis, value in validated_values.iteritems():
|
||||
printer.jog(axis, value)
|
||||
|
||||
##~~ home command
|
||||
elif command == "home":
|
||||
validated_values = []
|
||||
axes = data["axes"]
|
||||
for axis in axes:
|
||||
if not axis in valid_axes:
|
||||
return make_response("Invalid axis: %s" % axis, 400)
|
||||
validated_values.append(axis)
|
||||
|
||||
# execute the home command
|
||||
printer.home(validated_values)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
##~~ SD Card
|
||||
|
||||
|
||||
@api.route("/printer/sd", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerSdCommand():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD support is disabled", 404)
|
||||
|
||||
if not printer.isOperational() or printer.isPrinting() or printer.isPaused():
|
||||
return make_response("Printer is not operational or currently busy", 409)
|
||||
|
||||
valid_commands = {
|
||||
"init": [],
|
||||
"refresh": [],
|
||||
"release": []
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "init":
|
||||
printer.initSdCard()
|
||||
elif command == "refresh":
|
||||
printer.refreshSdFiles()
|
||||
elif command == "release":
|
||||
printer.releaseSdCard()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/sd", methods=["GET"])
|
||||
def printerSdState():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD support is disabled", 404)
|
||||
|
||||
return jsonify(ready=printer.isSdReady())
|
||||
|
||||
|
||||
##~~ Commands
|
||||
|
||||
|
||||
@api.route("/printer/command", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerCommand():
|
||||
# TODO: document me
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
|
||||
parameters = {}
|
||||
if "parameters" in data.keys(): parameters = data["parameters"]
|
||||
|
||||
commands = []
|
||||
if "command" in data.keys(): commands = [data["command"]]
|
||||
elif "commands" in data.keys(): commands = data["commands"]
|
||||
|
||||
commandsToSend = []
|
||||
for command in commands:
|
||||
commandToSend = command
|
||||
if len(parameters) > 0:
|
||||
commandToSend = command % parameters
|
||||
commandsToSend.append(commandToSend)
|
||||
|
||||
printer.commands(commandsToSend)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/command/custom", methods=["GET"])
|
||||
def getCustomControls():
|
||||
# TODO: document me
|
||||
customControls = settings().get(["controls"])
|
||||
return jsonify(controls=customControls)
|
||||
|
||||
|
||||
def _getTemperatureData(filter):
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
tempData = printer.getCurrentTemperatures()
|
||||
result = {
|
||||
"temps": filter(tempData)
|
||||
}
|
||||
|
||||
if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues:
|
||||
tempHistory = printer.getTemperatureHistory()
|
||||
|
||||
limit = 300
|
||||
if "limit" in request.values.keys() and unicode(request.values["limit"]).isnumeric():
|
||||
limit = int(request.values["limit"])
|
||||
|
||||
history = list(tempHistory)
|
||||
limit = min(limit, len(history))
|
||||
|
||||
result.update({
|
||||
"history": map(lambda x: filter(x), history[-limit:])
|
||||
})
|
||||
|
||||
return result
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import logging
|
||||
|
||||
from flask import request, jsonify
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.printer import getConnectionOptions
|
||||
|
||||
from octoprint.server import restricted_access, admin_permission
|
||||
from octoprint.server.api import api
|
||||
|
||||
|
||||
#~~ settings
|
||||
|
||||
|
||||
@api.route("/settings", methods=["GET"])
|
||||
def getSettings():
|
||||
s = settings()
|
||||
|
||||
[movementSpeedX, movementSpeedY, movementSpeedZ, movementSpeedE] \
|
||||
= s.get(["printerParameters", "movementSpeed", ["x", "y", "z", "e"]])
|
||||
|
||||
connectionOptions = getConnectionOptions()
|
||||
|
||||
return jsonify({
|
||||
"api": {
|
||||
"enabled": s.getBoolean(["api", "enabled"]),
|
||||
"key": s.get(["api", "key"])
|
||||
},
|
||||
"appearance": {
|
||||
"name": s.get(["appearance", "name"]),
|
||||
"color": s.get(["appearance", "color"])
|
||||
},
|
||||
"printer": {
|
||||
"movementSpeedX": movementSpeedX,
|
||||
"movementSpeedY": movementSpeedY,
|
||||
"movementSpeedZ": movementSpeedZ,
|
||||
"movementSpeedE": movementSpeedE,
|
||||
"invertAxes": s.get(["printerParameters", "invertAxes"]),
|
||||
"numExtruders": s.get(["printerParameters", "numExtruders"]),
|
||||
"extruderOffsets": s.get(["printerParameters", "extruderOffsets"]),
|
||||
"bedDimensions": s.get(["printerParameters", "bedDimensions"])
|
||||
},
|
||||
"webcam": {
|
||||
"streamUrl": s.get(["webcam", "stream"]),
|
||||
"snapshotUrl": s.get(["webcam", "snapshot"]),
|
||||
"ffmpegPath": s.get(["webcam", "ffmpeg"]),
|
||||
"bitrate": s.get(["webcam", "bitrate"]),
|
||||
"watermark": s.getBoolean(["webcam", "watermark"]),
|
||||
"flipH": s.getBoolean(["webcam", "flipH"]),
|
||||
"flipV": s.getBoolean(["webcam", "flipV"])
|
||||
},
|
||||
"feature": {
|
||||
"gcodeViewer": s.getBoolean(["gcodeViewer", "enabled"]),
|
||||
"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
|
||||
"waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]),
|
||||
"alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]),
|
||||
"sdSupport": s.getBoolean(["feature", "sdSupport"]),
|
||||
"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
|
||||
"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
|
||||
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"])
|
||||
},
|
||||
"serial": {
|
||||
"port": connectionOptions["portPreference"],
|
||||
"baudrate": connectionOptions["baudratePreference"],
|
||||
"portOptions": connectionOptions["ports"],
|
||||
"baudrateOptions": connectionOptions["baudrates"],
|
||||
"autoconnect": s.getBoolean(["serial", "autoconnect"]),
|
||||
"timeoutConnection": s.getFloat(["serial", "timeout", "connection"]),
|
||||
"timeoutDetection": s.getFloat(["serial", "timeout", "detection"]),
|
||||
"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
|
||||
"timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]),
|
||||
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
|
||||
"log": s.getBoolean(["serial", "log"])
|
||||
},
|
||||
"folder": {
|
||||
"uploads": s.getBaseFolder("uploads"),
|
||||
"timelapse": s.getBaseFolder("timelapse"),
|
||||
"timelapseTmp": s.getBaseFolder("timelapse_tmp"),
|
||||
"logs": s.getBaseFolder("logs")
|
||||
},
|
||||
"temperature": {
|
||||
"profiles": s.get(["temperature", "profiles"])
|
||||
},
|
||||
"system": {
|
||||
"actions": s.get(["system", "actions"]),
|
||||
"events": s.get(["system", "events"])
|
||||
},
|
||||
"terminalFilters": s.get(["terminalFilters"]),
|
||||
"cura": {
|
||||
"enabled": s.getBoolean(["cura", "enabled"]),
|
||||
"path": s.get(["cura", "path"]),
|
||||
"config": s.get(["cura", "config"])
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@api.route("/settings", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def setSettings():
|
||||
if "application/json" in request.headers["Content-Type"]:
|
||||
data = request.json
|
||||
s = settings()
|
||||
|
||||
if "api" in data.keys():
|
||||
if "enabled" in data["api"].keys(): s.set(["api", "enabled"], data["api"]["enabled"])
|
||||
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
|
||||
|
||||
if "appearance" in data.keys():
|
||||
if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"])
|
||||
if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"])
|
||||
|
||||
if "printer" in data.keys():
|
||||
if "movementSpeedX" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "x"], data["printer"]["movementSpeedX"])
|
||||
if "movementSpeedY" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "y"], data["printer"]["movementSpeedY"])
|
||||
if "movementSpeedZ" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "z"], data["printer"]["movementSpeedZ"])
|
||||
if "movementSpeedE" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "e"], data["printer"]["movementSpeedE"])
|
||||
if "invertAxes" in data["printer"].keys(): s.set(["printerParameters", "invertAxes"], data["printer"]["invertAxes"])
|
||||
if "numExtruders" in data["printer"].keys(): s.setInt(["printerParameters", "numExtruders"], data["printer"]["numExtruders"])
|
||||
if "extruderOffsets" in data["printer"].keys(): s.set(["printerParameters", "extruderOffsets"], data["printer"]["extruderOffsets"])
|
||||
if "bedDimensions" in data["printer"].keys(): s.set(["printerParameters", "bedDimensions"], data["printer"]["bedDimensions"])
|
||||
|
||||
if "webcam" in data.keys():
|
||||
if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
|
||||
if "snapshotUrl" in data["webcam"].keys(): s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
|
||||
if "ffmpegPath" in data["webcam"].keys(): s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
|
||||
if "bitrate" in data["webcam"].keys(): s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
|
||||
if "watermark" in data["webcam"].keys(): s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
|
||||
if "flipH" in data["webcam"].keys(): s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
|
||||
if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
|
||||
|
||||
if "feature" in data.keys():
|
||||
if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"])
|
||||
if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
|
||||
if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
|
||||
if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
|
||||
if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
|
||||
if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
|
||||
if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
|
||||
if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
|
||||
|
||||
if "serial" in data.keys():
|
||||
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"])
|
||||
if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
|
||||
if "timeoutConnection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
|
||||
if "timeoutDetection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
|
||||
if "timeoutCommunication" in data["serial"].keys(): s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
|
||||
if "timeoutTemperature" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
|
||||
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
|
||||
|
||||
oldLog = s.getBoolean(["serial", "log"])
|
||||
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||
if oldLog and not s.getBoolean(["serial", "log"]):
|
||||
# disable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").debug("Disabling serial logging")
|
||||
logging.getLogger("SERIAL").setLevel(logging.CRITICAL)
|
||||
elif not oldLog and s.getBoolean(["serial", "log"]):
|
||||
# enable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
|
||||
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
||||
|
||||
if "folder" in data.keys():
|
||||
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
|
||||
if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"])
|
||||
if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
|
||||
if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"])
|
||||
|
||||
if "temperature" in data.keys():
|
||||
if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"])
|
||||
|
||||
if "terminalFilters" in data.keys():
|
||||
s.set(["terminalFilters"], data["terminalFilters"])
|
||||
|
||||
if "system" in data.keys():
|
||||
if "actions" in data["system"].keys(): s.set(["system", "actions"], data["system"]["actions"])
|
||||
if "events" in data["system"].keys(): s.set(["system", "events"], data["system"]["events"])
|
||||
|
||||
cura = data.get("cura", None)
|
||||
if cura:
|
||||
path = cura.get("path")
|
||||
if path:
|
||||
s.set(["cura", "path"], path)
|
||||
|
||||
config = cura.get("config")
|
||||
if config:
|
||||
s.set(["cura", "config"], config)
|
||||
|
||||
# Enabled is a boolean so we cannot check that we have a result
|
||||
enabled = cura.get("enabled")
|
||||
s.setBoolean(["cura", "enabled"], enabled)
|
||||
|
||||
s.save()
|
||||
|
||||
return getSettings()
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import os
|
||||
|
||||
from flask import request, jsonify, url_for
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
import octoprint.timelapse
|
||||
import octoprint.util as util
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
from octoprint.server import restricted_access, admin_permission
|
||||
from octoprint.server.util import redirectToTornado
|
||||
from octoprint.server.api import api
|
||||
|
||||
|
||||
#~~ timelapse handling
|
||||
|
||||
|
||||
@api.route("/timelapse", methods=["GET"])
|
||||
def getTimelapseData():
|
||||
timelapse = octoprint.timelapse.current
|
||||
|
||||
config = {"type": "off"}
|
||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||
config["type"] = "zchange"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||
config["type"] = "timed"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config.update({
|
||||
"interval": timelapse.interval()
|
||||
})
|
||||
|
||||
files = octoprint.timelapse.getFinishedTimelapses()
|
||||
for file in files:
|
||||
file["url"] = url_for("index") + "downloads/timelapse/" + file["name"]
|
||||
|
||||
return jsonify({
|
||||
"config": config,
|
||||
"files": files
|
||||
})
|
||||
|
||||
|
||||
@api.route("/timelapse/<filename>", methods=["GET"])
|
||||
def downloadTimelapse(filename):
|
||||
return redirectToTornado(request, url_for("index") + "downloads/timelapse/" + filename)
|
||||
|
||||
|
||||
@api.route("/timelapse/<filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteTimelapse(filename):
|
||||
if util.isAllowedFile(filename, {"mpg"}):
|
||||
secure = os.path.join(settings().getBaseFolder("timelapse"), secure_filename(filename))
|
||||
if os.path.exists(secure):
|
||||
os.remove(secure)
|
||||
return getTimelapseData()
|
||||
|
||||
|
||||
@api.route("/timelapse", methods=["POST"])
|
||||
@restricted_access
|
||||
def setTimelapseConfig():
|
||||
if "type" in request.values:
|
||||
config = {
|
||||
"type": request.values["type"],
|
||||
"postRoll": 0,
|
||||
"options": {}
|
||||
}
|
||||
|
||||
|
||||
if "postRoll" in request.values:
|
||||
try:
|
||||
config["postRoll"] = int(request.values["postRoll"])
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if "interval" in request.values:
|
||||
interval = 10
|
||||
try:
|
||||
interval = int(request.values["interval"])
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
config["options"] = {
|
||||
"interval": interval
|
||||
}
|
||||
|
||||
if admin_permission.can() and "save" in request.values and request.values["save"] in valid_boolean_trues:
|
||||
octoprint.timelapse.configureTimelapse(config, True)
|
||||
else:
|
||||
octoprint.timelapse.configureTimelapse(config)
|
||||
|
||||
return getTimelapseData()
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
from flask import request, jsonify, abort, make_response
|
||||
from flask.ext.login import current_user
|
||||
|
||||
import octoprint.users as users
|
||||
|
||||
from octoprint.server import restricted_access, SUCCESS, admin_permission, userManager
|
||||
from octoprint.server.api import api
|
||||
|
||||
|
||||
#~~ user settings
|
||||
|
||||
|
||||
@api.route("/users", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def getUsers():
|
||||
if userManager is None:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
return jsonify({"users": userManager.getAllUsers()})
|
||||
|
||||
|
||||
@api.route("/users", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def addUser():
|
||||
if userManager is None:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if "application/json" in request.headers["Content-Type"]:
|
||||
data = request.json
|
||||
|
||||
name = data["name"]
|
||||
password = data["password"]
|
||||
active = data["active"]
|
||||
|
||||
roles = ["user"]
|
||||
if "admin" in data.keys() and data["admin"]:
|
||||
roles.append("admin")
|
||||
|
||||
try:
|
||||
userManager.addUser(name, password, active, roles)
|
||||
except users.UserAlreadyExists:
|
||||
abort(409)
|
||||
return getUsers()
|
||||
|
||||
|
||||
@api.route("/users/<username>", methods=["GET"])
|
||||
@restricted_access
|
||||
def getUser(username):
|
||||
if userManager is None:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
user = userManager.findUser(username)
|
||||
if user is not None:
|
||||
return jsonify(user.asDict())
|
||||
else:
|
||||
abort(404)
|
||||
else:
|
||||
abort(403)
|
||||
|
||||
|
||||
@api.route("/users/<username>", methods=["PUT"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def updateUser(username):
|
||||
if userManager is None:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
user = userManager.findUser(username)
|
||||
if user is not None:
|
||||
if "application/json" in request.headers["Content-Type"]:
|
||||
data = request.json
|
||||
|
||||
# change roles
|
||||
roles = ["user"]
|
||||
if "admin" in data.keys() and data["admin"]:
|
||||
roles.append("admin")
|
||||
userManager.changeUserRoles(username, roles)
|
||||
|
||||
# change activation
|
||||
if "active" in data.keys():
|
||||
userManager.changeUserActivation(username, data["active"])
|
||||
return getUsers()
|
||||
else:
|
||||
abort(404)
|
||||
|
||||
|
||||
@api.route("/users/<username>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@admin_permission.require(http_exception=403)
|
||||
def removeUser(username):
|
||||
if userManager is None:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
try:
|
||||
userManager.removeUser(username)
|
||||
return getUsers()
|
||||
except users.UnknownUser:
|
||||
abort(404)
|
||||
|
||||
|
||||
@api.route("/users/<username>/password", methods=["PUT"])
|
||||
@restricted_access
|
||||
def changePasswordForUser(username):
|
||||
if userManager is None:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
if "application/json" in request.headers["Content-Type"]:
|
||||
data = request.json
|
||||
if "password" in data.keys() and data["password"]:
|
||||
try:
|
||||
userManager.changeUserPassword(username, data["password"])
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
return jsonify(SUCCESS)
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
|
||||
|
||||
@api.route("/users/<username>/apikey", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteApikeyForUser(username):
|
||||
if userManager is None:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
try:
|
||||
userManager.deleteApikey(username)
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
return jsonify(SUCCESS)
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
|
||||
|
||||
@api.route("/users/<username>/apikey", methods=["POST"])
|
||||
@restricted_access
|
||||
def generateApikeyForUser(username):
|
||||
if userManager is None:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
try:
|
||||
apikey = userManager.generateApiKey(username)
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
return jsonify({"apikey": apikey})
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
@@ -0,0 +1,388 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
from flask.ext.principal import identity_changed, Identity
|
||||
from tornado.web import StaticFileHandler, HTTPError
|
||||
from flask import url_for, make_response, request, current_app
|
||||
from flask.ext.login import login_required, login_user, current_user
|
||||
from werkzeug.utils import redirect
|
||||
from sockjs.tornado import SockJSConnection
|
||||
|
||||
import datetime
|
||||
import stat
|
||||
import mimetypes
|
||||
import email
|
||||
import time
|
||||
import os
|
||||
import threading
|
||||
import logging
|
||||
from functools import wraps
|
||||
|
||||
from octoprint.settings import settings
|
||||
import octoprint.timelapse
|
||||
import octoprint.server
|
||||
from octoprint.users import ApiUser
|
||||
from octoprint.events import Events
|
||||
|
||||
|
||||
def restricted_access(func, apiEnabled=True):
|
||||
"""
|
||||
If you decorate a view with this, it will ensure that first setup has been
|
||||
done for OctoPrint's Access Control plus that any conditions of the
|
||||
login_required decorator are met. It also allows to login using the masterkey or any
|
||||
of the user's apikeys if API access is enabled globally and for the decorated view.
|
||||
|
||||
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
|
||||
flag from the settings being set to True and the userManager not indicating
|
||||
that it's user database has been customized from default), the decorator
|
||||
will cause a HTTP 403 status code to be returned by the decorated resource.
|
||||
|
||||
If an API key is provided and it matches a known key, the user will be logged in and
|
||||
the view will be called directly. If the provided key doesn't match any known key,
|
||||
a HTTP 403 status code will be returned by the decorated resource.
|
||||
|
||||
Otherwise the result of calling login_required will be returned.
|
||||
"""
|
||||
@wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
# if OctoPrint hasn't been set up yet, abort
|
||||
if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
|
||||
return make_response("OctoPrint isn't setup yet", 403)
|
||||
|
||||
# if API is globally enabled, enabled for this request and an api key is provided, try to use that
|
||||
apikey = _getApiKey(request)
|
||||
if settings().get(["api", "enabled"]) and apiEnabled and apikey is not None:
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# master key was used
|
||||
user = ApiUser()
|
||||
else:
|
||||
# user key might have been used
|
||||
user = octoprint.server.userManager.findUser(apikey=apikey)
|
||||
|
||||
if user is None:
|
||||
make_response("Invalid API key", 401)
|
||||
if login_user(user, remember=False):
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return func(*args, **kwargs)
|
||||
|
||||
# call regular login_required decorator
|
||||
return login_required(func)(*args, **kwargs)
|
||||
return decorated_view
|
||||
|
||||
|
||||
def api_access(func):
|
||||
@wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
if not settings().get(["api", "enabled"]):
|
||||
make_response("API disabled", 401)
|
||||
apikey = _getApiKey(request)
|
||||
if apikey is None:
|
||||
make_response("No API key provided", 401)
|
||||
if apikey != settings().get(["api", "key"]):
|
||||
make_response("Invalid API key", 403)
|
||||
return func(*args, **kwargs)
|
||||
return decorated_view
|
||||
|
||||
|
||||
def _getUserForApiKey(apikey):
|
||||
if settings().get(["api", "enabled"]) and apikey is not None:
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# master key was used
|
||||
return ApiUser()
|
||||
else:
|
||||
# user key might have been used
|
||||
return octoprint.server.userManager.findUser(apikey=apikey)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def _getApiKey(request):
|
||||
# Check Flask GET/POST arguments
|
||||
if hasattr(request, "values") and "apikey" in request.values:
|
||||
return request.values["apikey"]
|
||||
|
||||
# Check Tornado GET/POST arguments
|
||||
if hasattr(request, "arguments") and "apikey" in request.arguments \
|
||||
and len(request.arguments["apikey"]) > 0 and len(request.arguments["apikey"].strip()) > 0:
|
||||
return request.arguments["apikey"]
|
||||
|
||||
# Check Tornado and Flask headers
|
||||
if "X-Api-Key" in request.headers.keys():
|
||||
return request.headers.get("X-Api-Key")
|
||||
|
||||
return None
|
||||
|
||||
|
||||
#~~ Printer state
|
||||
|
||||
|
||||
class PrinterStateConnection(SockJSConnection):
|
||||
EVENTS = [Events.UPDATED_FILES, Events.METADATA_ANALYSIS_FINISHED, Events.MOVIE_RENDERING, Events.MOVIE_DONE,
|
||||
Events.MOVIE_FAILED, Events.SLICING_STARTED, Events.SLICING_DONE, Events.SLICING_FAILED,
|
||||
Events.TRANSFER_STARTED, Events.TRANSFER_DONE]
|
||||
|
||||
def __init__(self, printer, gcodeManager, userManager, eventManager, session):
|
||||
SockJSConnection.__init__(self, session)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._temperatureBacklog = []
|
||||
self._temperatureBacklogMutex = threading.Lock()
|
||||
self._logBacklog = []
|
||||
self._logBacklogMutex = threading.Lock()
|
||||
self._messageBacklog = []
|
||||
self._messageBacklogMutex = threading.Lock()
|
||||
|
||||
self._printer = printer
|
||||
self._gcodeManager = gcodeManager
|
||||
self._userManager = userManager
|
||||
self._eventManager = eventManager
|
||||
|
||||
def _getRemoteAddress(self, info):
|
||||
forwardedFor = info.headers.get("X-Forwarded-For")
|
||||
if forwardedFor is not None:
|
||||
return forwardedFor.split(",")[0]
|
||||
return info.ip
|
||||
|
||||
def on_open(self, info):
|
||||
remoteAddress = self._getRemoteAddress(info)
|
||||
self._logger.info("New connection from client: %s" % remoteAddress)
|
||||
self._printer.registerCallback(self)
|
||||
self._gcodeManager.registerCallback(self)
|
||||
octoprint.timelapse.registerCallback(self)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
|
||||
for event in PrinterStateConnection.EVENTS:
|
||||
self._eventManager.subscribe(event, self._onEvent)
|
||||
|
||||
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
|
||||
|
||||
def on_close(self):
|
||||
self._logger.info("Client connection closed")
|
||||
self._printer.unregisterCallback(self)
|
||||
self._gcodeManager.unregisterCallback(self)
|
||||
octoprint.timelapse.unregisterCallback(self)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_CLOSED)
|
||||
for event in PrinterStateConnection.EVENTS:
|
||||
self._eventManager.unsubscribe(event, self._onEvent)
|
||||
|
||||
def on_message(self, message):
|
||||
pass
|
||||
|
||||
def sendCurrentData(self, data):
|
||||
# add current temperature, log and message backlogs to sent data
|
||||
with self._temperatureBacklogMutex:
|
||||
temperatures = self._temperatureBacklog
|
||||
self._temperatureBacklog = []
|
||||
|
||||
with self._logBacklogMutex:
|
||||
logs = self._logBacklog
|
||||
self._logBacklog = []
|
||||
|
||||
with self._messageBacklogMutex:
|
||||
messages = self._messageBacklog
|
||||
self._messageBacklog = []
|
||||
|
||||
data.update({
|
||||
"temps": temperatures,
|
||||
"logs": logs,
|
||||
"messages": messages
|
||||
})
|
||||
self._emit("current", data)
|
||||
|
||||
def sendHistoryData(self, data):
|
||||
self._emit("history", data)
|
||||
|
||||
def sendEvent(self, type, payload=None):
|
||||
self._emit("event", {"type": type, "payload": payload})
|
||||
|
||||
def sendFeedbackCommandOutput(self, name, output):
|
||||
self._emit("feedbackCommandOutput", {"name": name, "output": output})
|
||||
|
||||
def sendTimelapseConfig(self, timelapseConfig):
|
||||
self._emit("timelapse", timelapseConfig)
|
||||
|
||||
def addLog(self, data):
|
||||
with self._logBacklogMutex:
|
||||
self._logBacklog.append(data)
|
||||
|
||||
def addMessage(self, data):
|
||||
with self._messageBacklogMutex:
|
||||
self._messageBacklog.append(data)
|
||||
|
||||
def addTemperature(self, data):
|
||||
with self._temperatureBacklogMutex:
|
||||
self._temperatureBacklog.append(data)
|
||||
|
||||
def _onEvent(self, event, payload):
|
||||
self.sendEvent(event, payload)
|
||||
|
||||
def _emit(self, type, payload):
|
||||
self.send({type: payload})
|
||||
|
||||
|
||||
#~~ customized large response handler
|
||||
|
||||
|
||||
class LargeResponseHandler(StaticFileHandler):
|
||||
|
||||
CHUNK_SIZE = 16 * 1024
|
||||
|
||||
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None):
|
||||
StaticFileHandler.initialize(self, path, default_filename)
|
||||
self._as_attachment = as_attachment
|
||||
self._access_validation = access_validation
|
||||
|
||||
def get(self, path, include_body=True):
|
||||
if self._access_validation is not None:
|
||||
self._access_validation(self.request)
|
||||
|
||||
path = self.parse_url_path(path)
|
||||
abspath = os.path.abspath(os.path.join(self.root, path))
|
||||
# os.path.abspath strips a trailing /
|
||||
# it needs to be temporarily added back for requests to root/
|
||||
if not (abspath + os.path.sep).startswith(self.root):
|
||||
raise HTTPError(403, "%s is not in root static directory", path)
|
||||
if os.path.isdir(abspath) and self.default_filename is not None:
|
||||
# need to look at the request.path here for when path is empty
|
||||
# but there is some prefix to the path that was already
|
||||
# trimmed by the routing
|
||||
if not self.request.path.endswith("/"):
|
||||
self.redirect(self.request.path + "/")
|
||||
return
|
||||
abspath = os.path.join(abspath, self.default_filename)
|
||||
if not os.path.exists(abspath):
|
||||
raise HTTPError(404)
|
||||
if not os.path.isfile(abspath):
|
||||
raise HTTPError(403, "%s is not a file", path)
|
||||
|
||||
stat_result = os.stat(abspath)
|
||||
modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])
|
||||
|
||||
self.set_header("Last-Modified", modified)
|
||||
|
||||
mime_type, encoding = mimetypes.guess_type(abspath)
|
||||
if mime_type:
|
||||
self.set_header("Content-Type", mime_type)
|
||||
|
||||
cache_time = self.get_cache_time(path, modified, mime_type)
|
||||
|
||||
if cache_time > 0:
|
||||
self.set_header("Expires", datetime.datetime.utcnow() +
|
||||
datetime.timedelta(seconds=cache_time))
|
||||
self.set_header("Cache-Control", "max-age=" + str(cache_time))
|
||||
|
||||
self.set_extra_headers(path)
|
||||
|
||||
# Check the If-Modified-Since, and don't send the result if the
|
||||
# content has not been modified
|
||||
ims_value = self.request.headers.get("If-Modified-Since")
|
||||
if ims_value is not None:
|
||||
date_tuple = email.utils.parsedate(ims_value)
|
||||
if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
|
||||
if if_since >= modified:
|
||||
self.set_status(304)
|
||||
return
|
||||
|
||||
if not include_body:
|
||||
assert self.request.method == "HEAD"
|
||||
self.set_header("Content-Length", stat_result[stat.ST_SIZE])
|
||||
else:
|
||||
with open(abspath, "rb") as file:
|
||||
while True:
|
||||
data = file.read(LargeResponseHandler.CHUNK_SIZE)
|
||||
if not data:
|
||||
break
|
||||
self.write(data)
|
||||
self.flush()
|
||||
|
||||
def set_extra_headers(self, path):
|
||||
if self._as_attachment:
|
||||
self.set_header("Content-Disposition", "attachment")
|
||||
|
||||
|
||||
#~~ admin access validator for use with tornado
|
||||
|
||||
|
||||
def admin_validator(request):
|
||||
"""
|
||||
Validates that the given request is made by an admin user, identified either by API key or existing Flask
|
||||
session.
|
||||
|
||||
Must be executed in an existing Flask request context!
|
||||
|
||||
:param request: The Flask request object
|
||||
"""
|
||||
|
||||
apikey = _getApiKey(request)
|
||||
if settings().get(["api", "enabled"]) and apikey is not None:
|
||||
user = _getUserForApiKey(apikey)
|
||||
else:
|
||||
user = current_user
|
||||
|
||||
if user is None or not user.is_authenticated() or not user.is_admin():
|
||||
raise HTTPError(403)
|
||||
|
||||
|
||||
#~~ reverse proxy compatible wsgi middleware
|
||||
|
||||
|
||||
class ReverseProxied(object):
|
||||
"""
|
||||
Wrap the application in this middleware and configure the
|
||||
front-end server to add these headers, to let you quietly bind
|
||||
this to a URL other than / and to an HTTP scheme that is
|
||||
different than what is used locally.
|
||||
|
||||
In nginx:
|
||||
location /myprefix {
|
||||
proxy_pass http://192.168.0.1:5001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Scheme $scheme;
|
||||
proxy_set_header X-Script-Name /myprefix;
|
||||
}
|
||||
|
||||
Alternatively define prefix and scheme via config.yaml:
|
||||
server:
|
||||
baseUrl: /myprefix
|
||||
scheme: http
|
||||
|
||||
:param app: the WSGI application
|
||||
"""
|
||||
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
|
||||
if not script_name:
|
||||
script_name = settings().get(["server", "baseUrl"])
|
||||
|
||||
if script_name:
|
||||
environ['SCRIPT_NAME'] = script_name
|
||||
path_info = environ['PATH_INFO']
|
||||
if path_info.startswith(script_name):
|
||||
environ['PATH_INFO'] = path_info[len(script_name):]
|
||||
|
||||
scheme = environ.get('HTTP_X_SCHEME', '')
|
||||
if not scheme:
|
||||
scheme = settings().get(["server", "scheme"])
|
||||
|
||||
if scheme:
|
||||
environ['wsgi.url_scheme'] = scheme
|
||||
return self.app(environ, start_response)
|
||||
|
||||
|
||||
def redirectToTornado(request, target):
|
||||
requestUrl = request.url
|
||||
appBaseUrl = requestUrl[:requestUrl.find(url_for("index") + "api")]
|
||||
|
||||
redirectUrl = appBaseUrl + target
|
||||
if "?" in requestUrl:
|
||||
fragment = requestUrl[requestUrl.rfind("?"):]
|
||||
redirectUrl += fragment
|
||||
return redirect(redirectUrl)
|
||||
|
||||
@@ -31,14 +31,18 @@ default_settings = {
|
||||
"timeout": {
|
||||
"detection": 0.5,
|
||||
"connection": 2,
|
||||
"communication": 5
|
||||
"communication": 5,
|
||||
"temperature": 5,
|
||||
"sdStatus": 1
|
||||
},
|
||||
"additionalPorts": []
|
||||
},
|
||||
"server": {
|
||||
"host": "0.0.0.0",
|
||||
"port": 5000,
|
||||
"firstRun": True
|
||||
"firstRun": True,
|
||||
"baseUrl": "",
|
||||
"scheme": ""
|
||||
},
|
||||
"webcam": {
|
||||
"stream": None,
|
||||
@@ -50,16 +54,23 @@ default_settings = {
|
||||
"flipV": False,
|
||||
"timelapse": {
|
||||
"type": "off",
|
||||
"options": {}
|
||||
"options": {},
|
||||
"postRoll": 0
|
||||
}
|
||||
},
|
||||
"gcodeViewer": {
|
||||
"enabled": True,
|
||||
"mobileSizeThreshold": 2 * 1024 * 1024, # 2MB
|
||||
"sizeThreshold": 20 * 1024 * 1024, # 20MB
|
||||
},
|
||||
"feature": {
|
||||
"gCodeVisualizer": True,
|
||||
"temperatureGraph": True,
|
||||
"waitForStartOnConnect": False,
|
||||
"alwaysSendChecksum": False,
|
||||
"sdSupport": True,
|
||||
"swallowOkAfterResend": True
|
||||
"sdAlwaysAvailable": False,
|
||||
"swallowOkAfterResend": True,
|
||||
"repetierTargetTemp": False
|
||||
},
|
||||
"folder": {
|
||||
"uploads": None,
|
||||
@@ -82,7 +93,15 @@ default_settings = {
|
||||
"z": 200,
|
||||
"e": 300
|
||||
},
|
||||
"pauseTriggers": []
|
||||
"pauseTriggers": [],
|
||||
"invertAxes": [],
|
||||
"numExtruders": 1,
|
||||
"extruderOffsets": [
|
||||
{"x": 0.0, "y": 0.0}
|
||||
],
|
||||
"bedDimensions": {
|
||||
"x": 200.0, "y": 200.0
|
||||
}
|
||||
},
|
||||
"appearance": {
|
||||
"name": "",
|
||||
@@ -100,33 +119,39 @@ default_settings = {
|
||||
"localNetworks": ["127.0.0.0/8"],
|
||||
"autologinAs": None
|
||||
},
|
||||
"cura": {
|
||||
"enabled": False,
|
||||
"path": "/default/path/to/cura",
|
||||
"config": "/default/path/to/your/cura/config.ini"
|
||||
},
|
||||
"events": {
|
||||
"systemCommandTrigger": {
|
||||
"enabled": False
|
||||
},
|
||||
"gcodeCommandTrigger": {
|
||||
"enabled": False
|
||||
}
|
||||
"enabled": False,
|
||||
"subscriptions": []
|
||||
},
|
||||
"api": {
|
||||
"enabled": False,
|
||||
"key": ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
|
||||
},
|
||||
"terminalFilters": [
|
||||
{ "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok T:)" },
|
||||
{ "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok T\d*:)" },
|
||||
{ "name": "Suppress M27 requests/responses", "regex": "(Send: M27)|(Recv: SD printing byte)" }
|
||||
],
|
||||
"devel": {
|
||||
"stylesheet": "css",
|
||||
"virtualPrinter": {
|
||||
"enabled": False,
|
||||
"okAfterResend": False,
|
||||
"forceChecksum": False,
|
||||
"okWithLinenumber": False
|
||||
"okWithLinenumber": False,
|
||||
"numExtruders": 1,
|
||||
"includeCurrentToolInTemps": True,
|
||||
"hasBed": True,
|
||||
"repetierStyleTargetTemperature": False
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
valid_boolean_trues = ["true", "yes", "y", "1"]
|
||||
valid_boolean_trues = [True, "true", "yes", "y", "1"]
|
||||
|
||||
class Settings(object):
|
||||
|
||||
@@ -144,7 +169,7 @@ class Settings(object):
|
||||
self._configfile = configfile
|
||||
else:
|
||||
self._configfile = os.path.join(self.settings_dir, "config.yaml")
|
||||
self.load()
|
||||
self.load(migrate=True)
|
||||
|
||||
def _init_settings_dir(self, basedir):
|
||||
if basedir is not None:
|
||||
@@ -160,7 +185,7 @@ class Settings(object):
|
||||
|
||||
#~~ load and save
|
||||
|
||||
def load(self):
|
||||
def load(self, migrate=False):
|
||||
if os.path.exists(self._configfile) and os.path.isfile(self._configfile):
|
||||
with open(self._configfile, "r") as f:
|
||||
self._config = yaml.safe_load(f)
|
||||
@@ -168,6 +193,97 @@ class Settings(object):
|
||||
if not self._config:
|
||||
self._config = {}
|
||||
|
||||
if migrate:
|
||||
self._migrateConfig()
|
||||
|
||||
def _migrateConfig(self):
|
||||
if not self._config:
|
||||
return
|
||||
|
||||
if "events" in self._config.keys() and ("gcodeCommandTrigger" in self._config["events"] or "systemCommandTrigger" in self._config["events"]):
|
||||
self._logger.info("Migrating config (event subscriptions)...")
|
||||
|
||||
# migrate event hooks to new format
|
||||
placeholderRe = re.compile("%\((.*?)\)s")
|
||||
|
||||
eventNameReplacements = {
|
||||
"ClientOpen": "ClientOpened",
|
||||
"TransferStart": "TransferStarted"
|
||||
}
|
||||
payloadDataReplacements = {
|
||||
"Upload": {"data": "{file}", "filename": "{file}"},
|
||||
"Connected": {"data": "{port} at {baudrate} baud"},
|
||||
"FileSelected": {"data": "{file}", "filename": "{file}"},
|
||||
"TransferStarted": {"data": "{remote}", "filename": "{remote}"},
|
||||
"TransferDone": {"data": "{remote}", "filename": "{remote}"},
|
||||
"ZChange": {"data": "{new}"},
|
||||
"CaptureStart": {"data": "{file}"},
|
||||
"CaptureDone": {"data": "{file}"},
|
||||
"MovieDone": {"data": "{movie}", "filename": "{gcode}"},
|
||||
"Error": {"data": "{error}"},
|
||||
"PrintStarted": {"data": "{file}", "filename": "{file}"},
|
||||
"PrintDone": {"data": "{file}", "filename": "{file}"},
|
||||
}
|
||||
|
||||
def migrateEventHook(event, command):
|
||||
# migrate placeholders
|
||||
command = placeholderRe.sub("{__\\1}", command)
|
||||
|
||||
# migrate event names
|
||||
if event in eventNameReplacements:
|
||||
event = eventNameReplacements["event"]
|
||||
|
||||
# migrate payloads to more specific placeholders
|
||||
if event in payloadDataReplacements:
|
||||
for key in payloadDataReplacements[event]:
|
||||
command = command.replace("{__%s}" % key, payloadDataReplacements[event][key])
|
||||
|
||||
# return processed tuple
|
||||
return event, command
|
||||
|
||||
disableSystemCommands = False
|
||||
if "systemCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["systemCommandTrigger"]:
|
||||
disableSystemCommands = not self._config["events"]["systemCommandTrigger"]["enabled"]
|
||||
|
||||
disableGcodeCommands = False
|
||||
if "gcodeCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["gcodeCommandTrigger"]:
|
||||
disableGcodeCommands = not self._config["events"]["gcodeCommandTrigger"]["enabled"]
|
||||
|
||||
disableAllCommands = disableSystemCommands and disableGcodeCommands
|
||||
newEvents = {
|
||||
"enabled": not disableAllCommands,
|
||||
"subscriptions": []
|
||||
}
|
||||
|
||||
if "systemCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["systemCommandTrigger"]:
|
||||
for trigger in self._config["events"]["systemCommandTrigger"]["subscriptions"]:
|
||||
if not ("event" in trigger and "command" in trigger):
|
||||
continue
|
||||
|
||||
newTrigger = {"type": "system"}
|
||||
if disableSystemCommands and not disableAllCommands:
|
||||
newTrigger["enabled"] = False
|
||||
|
||||
newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"])
|
||||
newEvents["subscriptions"].append(newTrigger)
|
||||
|
||||
if "gcodeCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["gcodeCommandTrigger"]:
|
||||
for trigger in self._config["events"]["gcodeCommandTrigger"]["subscriptions"]:
|
||||
if not ("event" in trigger and "command" in trigger):
|
||||
continue
|
||||
|
||||
newTrigger = {"type": "gcode"}
|
||||
if disableGcodeCommands and not disableAllCommands:
|
||||
newTrigger["enabled"] = False
|
||||
|
||||
newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"])
|
||||
newTrigger["command"] = newTrigger["command"].split(",")
|
||||
newEvents["subscriptions"].append(newTrigger)
|
||||
|
||||
self._config["events"] = newEvents
|
||||
self.save(force=True)
|
||||
self._logger.info("Migrated %d event subscriptions to new format and structure" % len(newEvents["subscriptions"]))
|
||||
|
||||
def save(self, force=False):
|
||||
if not self._dirty and not force:
|
||||
return
|
||||
@@ -179,7 +295,7 @@ class Settings(object):
|
||||
|
||||
#~~ getter
|
||||
|
||||
def get(self, path):
|
||||
def get(self, path, asdict=False):
|
||||
if len(path) == 0:
|
||||
return None
|
||||
|
||||
@@ -203,17 +319,28 @@ class Settings(object):
|
||||
else:
|
||||
keys = k
|
||||
|
||||
results = []
|
||||
if asdict:
|
||||
results = {}
|
||||
else:
|
||||
results = []
|
||||
for key in keys:
|
||||
if key in config.keys():
|
||||
results.append(config[key])
|
||||
value = config[key]
|
||||
elif key in defaults:
|
||||
results.append(defaults[key])
|
||||
value = defaults[key]
|
||||
else:
|
||||
results.append(None)
|
||||
value = None
|
||||
|
||||
if asdict:
|
||||
results[key] = value
|
||||
else:
|
||||
results.append(value)
|
||||
|
||||
if not isinstance(k, (list, tuple)):
|
||||
return results.pop()
|
||||
if asdict:
|
||||
return results.values().pop()
|
||||
else:
|
||||
return results.pop()
|
||||
else:
|
||||
return results
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
__author__ = "Ross Hendrickson savorywatt"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from octoprint.settings import settings
|
||||
|
||||
class CuraFactory(object):
|
||||
|
||||
@staticmethod
|
||||
def create_slicer(path=None):
|
||||
"""Utilizes the factory pattern to setup a CuraEngine object
|
||||
|
||||
:param path: :class: `str`
|
||||
"""
|
||||
if path:
|
||||
return Cura(path)
|
||||
|
||||
current_settings = settings(init=True)
|
||||
path = current_settings.get(["cura", "path"])
|
||||
|
||||
return Cura(path)
|
||||
|
||||
|
||||
class Cura(object):
|
||||
|
||||
def __init__(self, cura_path):
|
||||
|
||||
if not cura_path:
|
||||
raise Exception("Unable to create CuraEngine - no path specified")
|
||||
|
||||
self.cura_path = cura_path
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def process_file(
|
||||
self, config, gcode, file_path, call_back=None,
|
||||
call_back_args=None):
|
||||
|
||||
"""Wraps around the main.cpp processFile method.
|
||||
|
||||
:param config: :class: `string` :path to a cura config file:
|
||||
:param gcode: :class: `string :path to write out the gcode generated:
|
||||
:param file_path: :class: `string :path to the STL to be sliced:
|
||||
:note: This will spawn a thread to handle the subprocess call and allow
|
||||
us to be able to have a call back
|
||||
"""
|
||||
import threading
|
||||
|
||||
def start_thread(call_back, call_back_args, call_args, cwd):
|
||||
import subprocess
|
||||
self._logger.info("Running %r in %s" % (call_args, cwd))
|
||||
try:
|
||||
subprocess.check_call(call_args, cwd=cwd)
|
||||
call_back(*call_back_args)
|
||||
except subprocess.CalledProcessError as (e):
|
||||
self._logger.warn("Could not slice via Cura, got return code %r" % e.returncode)
|
||||
call_back_args.append("Got returncode %r" % e.returncode)
|
||||
call_back(*call_back_args)
|
||||
|
||||
executable = self.cura_path
|
||||
(workingDir, ignored) = os.path.split(executable)
|
||||
args = [executable, '-i', config, '-s', file_path, '-o', gcode]
|
||||
|
||||
thread = threading.Thread(target=start_thread, args=(call_back,
|
||||
call_back_args, args, workingDir))
|
||||
|
||||
thread.start()
|
||||
@@ -0,0 +1,31 @@
|
||||
|
||||
|
||||
import unittest
|
||||
from mock import patch
|
||||
|
||||
from octoprint.slicers.cura import CuraFactory
|
||||
from octoprint.slicers.cura import Cura
|
||||
|
||||
class CuraFactoryTestCase(unittest.TestCase):
|
||||
|
||||
|
||||
def test_cura_factory(self):
|
||||
|
||||
fake_path = 'my/temp/path'
|
||||
result = CuraFactory.create_slicer(fake_path)
|
||||
|
||||
self.assertEqual(fake_path, result.cura_path)
|
||||
|
||||
|
||||
@patch('threading.Thread')
|
||||
def test_cura_engine_process_file(self, thread):
|
||||
path = 'rosshendrickson/workspaces/opensource/CuraEngine/'
|
||||
|
||||
cura = CuraFactory.create_slicer(path)
|
||||
file_path = './cura/tests/test.stl'
|
||||
config_path = './cura/tests/config'
|
||||
gcode_filename = './cura/tests/output.gcode'
|
||||
|
||||
cura.process_file(config_path, gcode_filename, file_path)
|
||||
self.assertTrue(thread.called)
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
/*!
|
||||
* Slider for Bootstrap
|
||||
*
|
||||
* Copyright 2012 Stefan Petre
|
||||
* Licensed under the Apache License v2.0
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
*/
|
||||
.slider {
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
position: relative;
|
||||
}
|
||||
.slider.slider-horizontal {
|
||||
width: 210px;
|
||||
height: 20px;
|
||||
}
|
||||
.slider.slider-horizontal .slider-track {
|
||||
height: 10px;
|
||||
width: 100%;
|
||||
margin-top: -5px;
|
||||
top: 50%;
|
||||
left: 0;
|
||||
}
|
||||
.slider.slider-horizontal .slider-selection {
|
||||
height: 100%;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
}
|
||||
.slider.slider-horizontal .slider-handle {
|
||||
margin-left: -10px;
|
||||
margin-top: -5px;
|
||||
}
|
||||
.slider.slider-horizontal .slider-handle.triangle {
|
||||
border-width: 0 10px 10px 10px;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-bottom-color: #0480be;
|
||||
margin-top: 0;
|
||||
}
|
||||
.slider.slider-vertical {
|
||||
height: 210px;
|
||||
width: 20px;
|
||||
}
|
||||
.slider.slider-vertical .slider-track {
|
||||
width: 10px;
|
||||
height: 100%;
|
||||
margin-left: -5px;
|
||||
left: 50%;
|
||||
top: 0;
|
||||
}
|
||||
.slider.slider-vertical .slider-selection {
|
||||
width: 100%;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
}
|
||||
.slider.slider-vertical .slider-handle {
|
||||
margin-left: -5px;
|
||||
margin-top: -10px;
|
||||
}
|
||||
.slider.slider-vertical .slider-handle.triangle {
|
||||
border-width: 10px 0 10px 10px;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
border-left-color: #0480be;
|
||||
margin-left: 0;
|
||||
}
|
||||
.slider.slider-disabled .slider-handle {
|
||||
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#dfdfdf), to(#bebebe));
|
||||
background-image: -webkit-linear-gradient(top, #dfdfdf, 0%, #bebebe, 100%);
|
||||
background-image: -moz-linear-gradient(top, #dfdfdf 0%, #bebebe 100%);
|
||||
background-image: linear-gradient(to bottom, #dfdfdf 0%, #bebebe 100%);
|
||||
background-repeat: repeat-x;
|
||||
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdfdfdf', endColorstr='#ffbebebe', GradientType=0);
|
||||
}
|
||||
.slider.slider-disabled .slider-track {
|
||||
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#e5e5e5), to(#e9e9e9));
|
||||
background-image: -webkit-linear-gradient(top, #e5e5e5, 0%, #e9e9e9, 100%);
|
||||
background-image: -moz-linear-gradient(top, #e5e5e5 0%, #e9e9e9 100%);
|
||||
background-image: linear-gradient(to bottom, #e5e5e5 0%, #e9e9e9 100%);
|
||||
background-repeat: repeat-x;
|
||||
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe5e5e5', endColorstr='#ffe9e9e9', GradientType=0);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.slider input {
|
||||
display: none;
|
||||
}
|
||||
.slider .tooltip-inner {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.slider-track {
|
||||
position: absolute;
|
||||
cursor: pointer;
|
||||
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f5f5f5), to(#f9f9f9));
|
||||
background-image: -webkit-linear-gradient(top, #f5f5f5, 0%, #f9f9f9, 100%);
|
||||
background-image: -moz-linear-gradient(top, #f5f5f5 0%, #f9f9f9 100%);
|
||||
background-image: linear-gradient(to bottom, #f5f5f5 0%, #f9f9f9 100%);
|
||||
background-repeat: repeat-x;
|
||||
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0);
|
||||
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
|
||||
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.slider-selection {
|
||||
position: absolute;
|
||||
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f9f9f9), to(#f5f5f5));
|
||||
background-image: -webkit-linear-gradient(top, #f9f9f9, 0%, #f5f5f5, 100%);
|
||||
background-image: -moz-linear-gradient(top, #f9f9f9 0%, #f5f5f5 100%);
|
||||
background-image: linear-gradient(to bottom, #f9f9f9 0%, #f5f5f5 100%);
|
||||
background-repeat: repeat-x;
|
||||
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9f9f9', endColorstr='#fff5f5f5', GradientType=0);
|
||||
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
|
||||
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
|
||||
-webkit-box-sizing: border-box;
|
||||
-moz-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.slider-handle {
|
||||
position: absolute;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#149bdf), to(#0480be));
|
||||
background-image: -webkit-linear-gradient(top, #149bdf, 0%, #0480be, 100%);
|
||||
background-image: -moz-linear-gradient(top, #149bdf 0%, #0480be 100%);
|
||||
background-image: linear-gradient(to bottom, #149bdf 0%, #0480be 100%);
|
||||
background-repeat: repeat-x;
|
||||
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0);
|
||||
-webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);
|
||||
box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);
|
||||
opacity: 0.8;
|
||||
border: 0px solid transparent;
|
||||
}
|
||||
.slider-handle.round {
|
||||
border-radius: 50%;
|
||||
}
|
||||
.slider-handle.triangle {
|
||||
background: transparent none;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
|
||||
|
Before Width: | Height: | Size: 135 KiB After Width: | Height: | Size: 135 KiB |
@@ -0,0 +1,571 @@
|
||||
/**
|
||||
* User: hudbrog (hudbrog@gmail.com)
|
||||
* Date: 10/24/12
|
||||
* Time: 12:18 PM
|
||||
*/
|
||||
|
||||
var gcode;
|
||||
var firstReport;
|
||||
var toolOffsets = [
|
||||
{x: 0, y: 0}
|
||||
];
|
||||
var z_heights = {};
|
||||
var model = [];
|
||||
var max = {x: undefined, y: undefined, z: undefined};
|
||||
var min = {x: undefined, y: undefined, z: undefined};
|
||||
var modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
var filamentByLayer = {};
|
||||
var totalFilament = [0];
|
||||
var printTime = 0;
|
||||
var printTimeByLayer = {};
|
||||
var layerHeight = 0;
|
||||
var layerCnt = 0;
|
||||
var speeds = {extrude: [], retract: [], move: []};
|
||||
var speedsByLayer = {extrude: {}, retract: {}, move: {}};
|
||||
|
||||
var sendLayerToParent = function(layerNum, z, progress){
|
||||
self.postMessage({
|
||||
"cmd": "returnLayer",
|
||||
"msg": {
|
||||
cmds: model[layerNum],
|
||||
layerNum: layerNum,
|
||||
zHeightObject: {zValue: z, layer: z_heights[z]},
|
||||
isEmpty: false,
|
||||
progress: progress
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var sendMultiLayerToParent = function(layerNum, z, progress){
|
||||
var tmpModel = [];
|
||||
var tmpZHeight = {};
|
||||
|
||||
for(var i=0;i<layerNum.length;i++){
|
||||
tmpModel[layerNum[i]] = model[layerNum[i]];
|
||||
tmpZHeight[layerNum[i]] = z_heights[z[i]];
|
||||
}
|
||||
|
||||
self.postMessage({
|
||||
"cmd": "returnMultiLayer",
|
||||
"msg": {
|
||||
model: tmpModel,
|
||||
layerNum: layerNum,
|
||||
zHeightObject: {zValue: z, layer: tmpZHeight},
|
||||
isEmpty: false,
|
||||
progress: progress
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
var sendSizeProgress = function(progress){
|
||||
self.postMessage({
|
||||
"cmd": "analyzeProgress",
|
||||
"msg": {
|
||||
progress: progress,
|
||||
printTime: printTime
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var sendAnalyzeDone = function(){
|
||||
self.postMessage({
|
||||
"cmd": "analyzeDone",
|
||||
"msg": {
|
||||
max: max,
|
||||
min: min,
|
||||
modelSize: modelSize,
|
||||
totalFilament: totalFilament,
|
||||
filamentByLayer: filamentByLayer,
|
||||
printTime: printTime,
|
||||
layerHeight: layerHeight,
|
||||
layerCnt: layerCnt,
|
||||
layerTotal: model.length,
|
||||
speeds: speeds,
|
||||
speedsByLayer: speedsByLayer,
|
||||
printTimeByLayer: printTimeByLayer
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var purgeLayers = function () {
|
||||
var purge = true;
|
||||
for (var i = 0; i < model.length; i++) {
|
||||
purge = true;
|
||||
if (!model[i]) {
|
||||
purge = true;
|
||||
} else {
|
||||
for (var j = 0; j < model[i].length; j++) {
|
||||
if (model[i][j].extrude)purge = false;
|
||||
}
|
||||
}
|
||||
if (!purge) {
|
||||
layerCnt += 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
var analyzeModel = function() {
|
||||
var tmp1 = 0, tmp2 = 0;
|
||||
var speedIndex = 0;
|
||||
var type;
|
||||
var printTimeAdd = 0;
|
||||
|
||||
for (var i = 0; i < model.length; i++) {
|
||||
var cmds = model[i];
|
||||
if(!cmds) continue;
|
||||
|
||||
for (var j = 0; j < cmds.length; j++) {
|
||||
var tool = cmds[j].tool;
|
||||
|
||||
var x_ok = false;
|
||||
var y_ok = false;
|
||||
|
||||
if (typeof(cmds[j].x) !== 'undefined'
|
||||
&& typeof(cmds[j].prevX) !== 'undefined'
|
||||
&& typeof(cmds[j].extrude) !== 'undefined'
|
||||
&& cmds[j].extrude
|
||||
&& !isNaN(cmds[j].x)) {
|
||||
var x = cmds[j].x;
|
||||
max.x = max.x !== undefined ? Math.max(max.x, x) : x;
|
||||
min.x = min.x !== undefined ? Math.min(min.x, x) : x;
|
||||
|
||||
x_ok = true;
|
||||
}
|
||||
|
||||
if (typeof(cmds[j].y) !== 'undefined'
|
||||
&& typeof(cmds[j].prevY) !== 'undefined'
|
||||
&& typeof(cmds[j].extrude) !== 'undefined'
|
||||
&& cmds[j].extrude
|
||||
&& !isNaN(cmds[j].y)){
|
||||
var y = cmds[j].y;
|
||||
|
||||
max.y = max.y !== undefined ? Math.max(max.y, y) : y;
|
||||
min.y = min.y !== undefined ? Math.min(min.y, y) : y;
|
||||
|
||||
y_ok = true;
|
||||
}
|
||||
|
||||
if (typeof(cmds[j].prevZ) !== 'undefined'
|
||||
&& typeof(cmds[j].extrude) !== 'undefined'
|
||||
&& cmds[j].extrude
|
||||
&& !isNaN(cmds[j].prevZ)) {
|
||||
var z = cmds[j].prevZ;
|
||||
max.z = max.z !== undefined ? Math.max(max.z, z) : z;
|
||||
min.z = min.z !== undefined ? Math.min(min.z, z) : z;
|
||||
}
|
||||
|
||||
if (!totalFilament[tool]) totalFilament[tool] = 0;
|
||||
if (!filamentByLayer[cmds[j].prevZ]) filamentByLayer[cmds[j].prevZ] = [0];
|
||||
if (!filamentByLayer[cmds[j].prevZ][tool]) filamentByLayer[cmds[j].prevZ][tool] = 0;
|
||||
if (cmds[j].extrusion) {
|
||||
totalFilament[tool] += cmds[j].extrusion;
|
||||
filamentByLayer[cmds[j].prevZ][tool] += cmds[j].extrusion;
|
||||
}
|
||||
|
||||
var diffX = cmds[j].x - cmds[j].prevX;
|
||||
var diffY = cmds[j].y - cmds[j].prevY;
|
||||
if (x_ok && y_ok) {
|
||||
printTimeAdd = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
} else if (cmds[j].retract === 0 && cmds[j].extrusion !== 0) {
|
||||
tmp1 = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
tmp2 = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
|
||||
printTimeAdd = Math.max(tmp1, tmp2);
|
||||
} else if (cmds[j].retract !== 0) {
|
||||
printTimeAdd = Math.abs(cmds[j].extrusion / (cmds[j].speed/60));
|
||||
}
|
||||
|
||||
printTime += printTimeAdd;
|
||||
if (typeof(printTimeByLayer[cmds[j].prevZ]) === 'undefined') {
|
||||
printTimeByLayer[cmds[j].prevZ] = 0;
|
||||
}
|
||||
printTimeByLayer[cmds[j].prevZ] += printTimeAdd;
|
||||
|
||||
if (cmds[j].extrude && cmds[j].retract === 0){
|
||||
type = 'extrude';
|
||||
} else if (cmds[j].retract !== 0) {
|
||||
type = 'retract';
|
||||
} else if (!cmds[j].extrude && cmds[j].retract === 0) {
|
||||
type = 'move';
|
||||
} else {
|
||||
self.postMessage({cmd: 'unknown type of move'});
|
||||
type = 'unknown';
|
||||
}
|
||||
|
||||
speedIndex = speeds[type].indexOf(cmds[j].speed);
|
||||
if (speedIndex === -1) {
|
||||
speeds[type].push(cmds[j].speed);
|
||||
speedIndex = speeds[type].indexOf(cmds[j].speed);
|
||||
}
|
||||
if (typeof(speedsByLayer[type][cmds[j].prevZ]) === 'undefined'){
|
||||
speedsByLayer[type][cmds[j].prevZ] = [];
|
||||
}
|
||||
if (speedsByLayer[type][cmds[j].prevZ].indexOf(cmds[j].speed) === -1){
|
||||
speedsByLayer[type][cmds[j].prevZ][speedIndex] = cmds[j].speed;
|
||||
}
|
||||
|
||||
}
|
||||
sendSizeProgress(i / model.length * 100);
|
||||
|
||||
}
|
||||
purgeLayers();
|
||||
|
||||
modelSize.x = Math.abs(max.x - min.x);
|
||||
modelSize.y = Math.abs(max.y - min.y);
|
||||
modelSize.z = Math.abs(max.z - min.z);
|
||||
layerHeight = (max.z-min.z) / (layerCnt - 1);
|
||||
|
||||
sendAnalyzeDone();
|
||||
};
|
||||
|
||||
var doParse = function(){
|
||||
var argChar, numSlice;
|
||||
var sendLayer = undefined;
|
||||
var sendLayerZ = 0;
|
||||
var sendMultiLayer = [];
|
||||
var sendMultiLayerZ = [];
|
||||
var lastSend = 0;
|
||||
|
||||
var layer = 0;
|
||||
var x, y, z = 0;
|
||||
var prevX = 0, prevY = 0, prevZ = 0;
|
||||
var f, lastF = 4000;
|
||||
var extrude = false, extrudeRelative = false, retract = 0;
|
||||
var positionRelative = false;
|
||||
|
||||
var dcExtrude=false;
|
||||
var assumeNonDC = false;
|
||||
|
||||
var tool = 0;
|
||||
var prev_extrude = [{a: 0, b: 0, c: 0, e: 0, abs: 0}];
|
||||
var prev_retract = [0];
|
||||
var offset = toolOffsets[0];
|
||||
|
||||
model = [];
|
||||
for (var i=0; i < gcode.length; i++) {
|
||||
x = undefined;
|
||||
y = undefined;
|
||||
z = undefined;
|
||||
retract = 0;
|
||||
|
||||
var line = gcode[i].line;
|
||||
var percentage = gcode[i].percentage;
|
||||
|
||||
extrude=false;
|
||||
line = line.split(/[\(;]/)[0];
|
||||
|
||||
var addToModel = false;
|
||||
var move = false;
|
||||
|
||||
var log = false;
|
||||
|
||||
if (/^(?:G0|G1)\s/i.test(line)) {
|
||||
var args = line.split(/\s/);
|
||||
|
||||
for (var j = 0; j < args.length; j++) {
|
||||
switch(argChar = args[j].charAt(0).toLowerCase()){
|
||||
case 'x':
|
||||
if (positionRelative) {
|
||||
x = prevX + Number(args[j].slice(1)) + offset.x;
|
||||
} else {
|
||||
x = Number(args[j].slice(1)) + offset.x;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'y':
|
||||
if (positionRelative) {
|
||||
y = prevY + Number(args[j].slice(1)) + offset.y;
|
||||
} else {
|
||||
y = Number(args[j].slice(1)) + offset.y;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'z':
|
||||
if (positionRelative) {
|
||||
z = prevZ + Number(args[j].slice(1));
|
||||
} else {
|
||||
z = Number(args[j].slice(1));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'e':
|
||||
case 'a':
|
||||
case 'b':
|
||||
case 'c':
|
||||
assumeNonDC = true;
|
||||
numSlice = Number(args[j].slice(1));
|
||||
|
||||
if (!extrudeRelative) {
|
||||
// absolute extrusion positioning
|
||||
prev_extrude[tool]["abs"] = numSlice - prev_extrude[tool][argChar];
|
||||
prev_extrude[tool][argChar] = numSlice;
|
||||
} else {
|
||||
prev_extrude[tool]["abs"] = numSlice;
|
||||
prev_extrude[tool][argChar] += numSlice;
|
||||
}
|
||||
|
||||
extrude = prev_extrude[tool]["abs"] > 0;
|
||||
if (prev_extrude[tool]["abs"] < 0) {
|
||||
prev_retract[tool] = -1;
|
||||
retract = -1;
|
||||
} else if (prev_extrude[tool]["abs"] == 0) {
|
||||
retract = 0;
|
||||
} else if (prev_extrude[tool]["abs"] > 0 && prev_retract[tool] < 0) {
|
||||
prev_retract[tool] = 0;
|
||||
retract = 1;
|
||||
} else {
|
||||
retract = 0;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'f':
|
||||
numSlice = parseFloat(args[j].slice(1));
|
||||
lastF = numSlice;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (dcExtrude && !assumeNonDC) {
|
||||
extrude = true;
|
||||
prev_extrude[tool]["abs"] = Math.sqrt((prevX - x) * (prevX - x) + (prevY - y) * (prevY - y));
|
||||
}
|
||||
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) {
|
||||
addToModel = true;
|
||||
move = true;
|
||||
}
|
||||
} else if (/^(?:M82)/i.test(line)) {
|
||||
extrudeRelative = false;
|
||||
} else if (/^(?:G91)/i.test(line)) {
|
||||
positionRelative = true;
|
||||
extrudeRelative = true;
|
||||
} else if (/^(?:G90)/i.test(line)) {
|
||||
positionRelative = false;
|
||||
extrudeRelative = false;
|
||||
} else if (/^(?:M83)/i.test(line)) {
|
||||
extrudeRelative = true;
|
||||
} else if (/^(?:M101)/i.test(line)) {
|
||||
dcExtrude = true;
|
||||
} else if (/^(?:M103)/i.test(line)) {
|
||||
dcExtrude = false;
|
||||
} else if (/^(?:G92)/i.test(line)) {
|
||||
var args = line.split(/\s/);
|
||||
|
||||
for (var j=0; j < args.length; j++) {
|
||||
if (!args[j]) continue;
|
||||
|
||||
if (args.length == 1) {
|
||||
// G92 without coordinates => reset all axes to 0
|
||||
x = 0;
|
||||
y = 0;
|
||||
z = 0;
|
||||
prev_extrude[tool]["e"] = 0;
|
||||
prev_extrude[tool]["a"] = 0;
|
||||
prev_extrude[tool]["b"] = 0;
|
||||
prev_extrude[tool]["c"] = 0;
|
||||
} else {
|
||||
switch (argChar = args[j].charAt(0).toLowerCase()) {
|
||||
case 'x':
|
||||
x = Number(args[j].slice(1)) + offset.x;
|
||||
break;
|
||||
|
||||
case 'y':
|
||||
y = Number(args[j].slice(1)) + offset.y;
|
||||
break;
|
||||
|
||||
case 'z':
|
||||
z = Number(args[j].slice(1));
|
||||
prevZ = z;
|
||||
break;
|
||||
|
||||
case 'e':
|
||||
case 'a':
|
||||
case 'b':
|
||||
case 'c':
|
||||
numSlice = Number(args[j].slice(1));
|
||||
if(!extrudeRelative)
|
||||
prev_extrude[tool][argChar] = 0;
|
||||
else {
|
||||
prev_extrude[tool][argChar] = numSlice;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined') {
|
||||
addToModel = true;
|
||||
move = false;
|
||||
}
|
||||
|
||||
} else if (/^(?:G28)/i.test(line)) {
|
||||
var args = line.split(/\s/);
|
||||
|
||||
if (args.length == 1) {
|
||||
// G28 with no arguments => home all axis
|
||||
x = 0;
|
||||
y = 0;
|
||||
z = 0;
|
||||
} else {
|
||||
for(j = 0; j < args.length; j++){
|
||||
switch(argChar = args[j].charAt(0).toLowerCase()){
|
||||
case 'x':
|
||||
x = 0;
|
||||
break;
|
||||
case 'y':
|
||||
y = 0;
|
||||
break;
|
||||
case 'z':
|
||||
z = 0;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if it's the first layer and G28 was without z
|
||||
if (layer == 0 && typeof(z) === 'undefined') {
|
||||
z = 0;
|
||||
}
|
||||
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) {
|
||||
addToModel = true;
|
||||
move = true;
|
||||
}
|
||||
} else if (/^(?:T\d+)/i.test(line)) {
|
||||
tool = Number(line.split(/\s/)[0].slice(1));
|
||||
if (!prev_extrude[tool]) prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0};
|
||||
if (!prev_retract[tool]) prev_retract[tool] = 0;
|
||||
|
||||
offset = toolOffsets[tool];
|
||||
if (!offset) offset = {x: 0, y: 0};
|
||||
}
|
||||
|
||||
if (typeof(z) !== 'undefined' && z != prevZ) {
|
||||
if (z_heights[z]) {
|
||||
layer = z_heights[z];
|
||||
} else {
|
||||
layer = model.length;
|
||||
z_heights[z] = layer;
|
||||
}
|
||||
|
||||
sendLayer = layer;
|
||||
sendLayerZ = z;
|
||||
prevZ = z;
|
||||
} else if (typeof(z) == 'undefined' && typeof(prevZ) != 'undefined') {
|
||||
if (z_heights.hasOwnProperty(prevZ)) {
|
||||
layer = z_heights[prevZ];
|
||||
} else {
|
||||
layer = model.length;
|
||||
z_heights[prevZ] = layer;
|
||||
}
|
||||
}
|
||||
|
||||
if (addToModel) {
|
||||
if (!model[layer]) model[layer] = [];
|
||||
model[layer].push({
|
||||
x: x,
|
||||
y: y,
|
||||
z: z,
|
||||
extrude: extrude,
|
||||
retract: retract,
|
||||
noMove: !move,
|
||||
extrusion: (extrude || retract) && prev_extrude[tool]["abs"] ? prev_extrude[tool]["abs"] : 0,
|
||||
prevX: prevX,
|
||||
prevY: prevY,
|
||||
prevZ: prevZ,
|
||||
speed: lastF,
|
||||
gcodeLine: i,
|
||||
percentage: percentage,
|
||||
tool: tool
|
||||
});
|
||||
}
|
||||
|
||||
if (move) {
|
||||
if (typeof(x) !== 'undefined') prevX = x;
|
||||
if (typeof(y) !== 'undefined') prevY = y;
|
||||
}
|
||||
|
||||
if (typeof(sendLayer) !== "undefined") {
|
||||
if (i - lastSend > gcode.length*0.02 && sendMultiLayer.length != 0){
|
||||
lastSend = i;
|
||||
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100);
|
||||
sendMultiLayer = [];
|
||||
sendMultiLayerZ = [];
|
||||
}
|
||||
sendMultiLayer[sendMultiLayer.length] = sendLayer;
|
||||
sendMultiLayerZ[sendMultiLayerZ.length] = sendLayerZ;
|
||||
sendLayer = undefined;
|
||||
sendLayerZ = undefined;
|
||||
}
|
||||
}
|
||||
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length*100);
|
||||
};
|
||||
|
||||
|
||||
var parseGCode = function(message){
|
||||
gcode = message.gcode;
|
||||
firstReport = message.options.firstReport;
|
||||
toolOffsets = message.options.toolOffsets;
|
||||
if (!toolOffsets || toolOffsets.length == 0) toolOffsets = [{x: 0, y: 0}]
|
||||
|
||||
doParse();
|
||||
gcode = [];
|
||||
self.postMessage({
|
||||
"cmd": "returnModel",
|
||||
"msg": {}
|
||||
});
|
||||
};
|
||||
|
||||
var runAnalyze = function(message){
|
||||
analyzeModel();
|
||||
model = [];
|
||||
z_heights = [];
|
||||
gcode = undefined;
|
||||
firstReport = undefined;
|
||||
z_heights = {};
|
||||
model = [];
|
||||
max = {x: undefined, y: undefined, z: undefined};
|
||||
min = {x: undefined, y: undefined, z: undefined};
|
||||
modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
filamentByLayer = {};
|
||||
totalFilament=0;
|
||||
printTime=0;
|
||||
printTimeByLayer = {};
|
||||
layerHeight=0;
|
||||
layerCnt = 0;
|
||||
speeds = {extrude: [], retract: [], move: []};
|
||||
speedsByLayer = {extrude: {}, retract: {}, move: {}};
|
||||
};
|
||||
|
||||
var setOption = function(options){
|
||||
for(var opt in options){
|
||||
gCodeOptions[opt] = options[opt];
|
||||
}
|
||||
};
|
||||
|
||||
onmessage = function (e){
|
||||
var data = e.data;
|
||||
// for some reason firefox doesn't garbage collect when something inside closures is deleted, so we delete and recreate whole object eaech time
|
||||
switch (data.cmd) {
|
||||
case 'parseGCode':
|
||||
parseGCode(data.msg);
|
||||
break;
|
||||
case 'setOption':
|
||||
setOption(data.msg);
|
||||
break;
|
||||
case 'analyzeModel':
|
||||
runAnalyze(data.msg);
|
||||
break;
|
||||
|
||||
default:
|
||||
self.postMessage('Unknown command: ' + data.msg);
|
||||
}
|
||||
|
||||
};
|
||||