Merge branch 'devel' into dev/userlanguage
Conflicts: src/octoprint/users.py
No files matched your search
@@ -4,7 +4,6 @@
|
||||
*.pyc
|
||||
*.zip
|
||||
*.exe
|
||||
*.gcode
|
||||
*.swp
|
||||
darwin-Cura-*
|
||||
win32-Cura-*
|
||||
@@ -21,3 +20,5 @@ dist
|
||||
pypy
|
||||
OctoPrint.egg-info
|
||||
*.orig
|
||||
|
||||
*.codekit
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
language: python
|
||||
python:
|
||||
- "2.7"
|
||||
- "2.7"
|
||||
install:
|
||||
- pip install -r requirements.txt
|
||||
- pip install -e .[develop]
|
||||
script:
|
||||
- nosetests
|
||||
- nosetests tests/
|
||||
@@ -1,6 +1,6 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.2.0 - Unreleased
|
||||
## 1.2.0 (Unreleased)
|
||||
|
||||
### New Features
|
||||
|
||||
@@ -16,6 +16,28 @@
|
||||
search
|
||||
* You can now define a folder (default: `~/.octoprint/watched`) to be watched for newly added GCODE (or -- if slicing
|
||||
support is enabled -- STL) files to automatically add.
|
||||
* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/devel/plugins/index.html) which allows extending its
|
||||
core functionality.
|
||||
* New type of API key: [App Session Keys](http://docs.octoprint.org/en/devel/api/apps.html) for trusted applications
|
||||
* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A
|
||||
connection to a printer will always have a printer profile associated.
|
||||
* OctoPrint now supports `action:...` commands received via debug messages (`// action:...`) from the printer. Currently supported are
|
||||
- `action:pause`: Pauses the current job in OctoPrint
|
||||
- `action:resume`: Resumes the current job in OctoPrint
|
||||
- `action:disconnect`: Disconnects OctoPrint from the printer
|
||||
Plugins can add supported commands by [hooking](http://docs.octoprint.org/en/devel/plugins/hooks.html) into the
|
||||
``octoprint.comm.protocol.action`` hook
|
||||
* Mousing over the webcam image in the control tab enables key control mode, allowing you to quickly move the axis of your
|
||||
printer with your computer's keyboard ([#610](https://github.com/foosel/OctoPrint/pull/610)):
|
||||
- arrow keys: X and Y axes
|
||||
- W, S / PageUp, PageDown: Y axes
|
||||
- Home: Home X and Y axes
|
||||
- End: Home Z axes
|
||||
- 1, 2, 3, 4: change step size used (0.1, 1, 10, 100mm)
|
||||
* Controls for adjusting feed and flow rate factor added to Controls ([#362](https://github.com/foosel/OctoPrint/issues/362))
|
||||
* Custom controls now also support slider controls
|
||||
* Custom controls now support a row layout
|
||||
* Users can now define custom GCODE scripts to run upon starting/pausing/resuming/success/failure of a print
|
||||
|
||||
### Improvements
|
||||
|
||||
@@ -26,14 +48,181 @@
|
||||
* Start counting the layers at 1 instead of 0 in the GCODE viewer
|
||||
* Upgraded [Font Awesome](https://fortawesome.github.io/Font-Awesome/) to version 3.2.1
|
||||
* Better error reporting for timelapse rendering and system commands
|
||||
* Supports
|
||||
* Custom control can now be defined so that they show a Confirm dialog with configurable text before executing
|
||||
([#532](https://github.com/foosel/OctoPrint/issues/532) and [#590](https://github.com/foosel/OctoPrint/pull/590))
|
||||
* Slicing has been greatly improved:
|
||||
* It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing
|
||||
job (defining overrides is not yet part of the UI but it's on the roadmap).
|
||||
* A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list
|
||||
as well). This dialog also allows specifying which action to take after slicing has been completed (none, selecting the
|
||||
sliced GCODE for printing or starting to print it directly)
|
||||
* Slicers themselves are integrated into the system via ``SlicingPlugins``.
|
||||
* The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the
|
||||
[CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See
|
||||
[the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to
|
||||
accommodate the new integration.
|
||||
* The "Slicing done" notification is now colored green ([#558](https://github.com/foosel/OctoPrint/issues/558)).
|
||||
* The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI).
|
||||
* File management now supports STL files as first class citizens (including UI adjustments to allow management of
|
||||
uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI). STL files
|
||||
can be downloaded like GCODE files.
|
||||
* Also interpret lines starting with "!!" as errors
|
||||
* Added deletion of pyc files to the `python setup.py clean` command
|
||||
* Settings now show a QRCode for the API Key ([#637](https://github.com/foosel/OctoPrint/pull/637))
|
||||
* Username in UI is no longer enclosed in scare quotes ([#595](https://github.com/foosel/OctoPrint/pull/595))
|
||||
* Username in login dialog is not automatically capitalized on mobile devices anymore ([#639](https://github.com/foosel/OctoPrint/pull/639))
|
||||
* "Slicing Done" and "Streaming Done" notifications now have a green background ([#558](https://github.com/foosel/OctoPrint/issues/558))
|
||||
* Files that are currently in use, be it for slicing, printing or whatever, are now tracked and can not be deleted as
|
||||
long as they are in use
|
||||
* Settings in UI get refreshed when opening settings dialog
|
||||
* New event "SettingsUpdated"
|
||||
* "Print time left" is now not displayed until it becomes somewhat stable. Display in web interface now also happens
|
||||
in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one. Additionally
|
||||
OctoPrint will use data from prior prints to enhance the initial print time estimation.
|
||||
* Added handler for uncaught exceptions to make sure those get logged, should make the logs even more useful for analysing
|
||||
bug reports
|
||||
* The server now tracks the modification date of the configuration file and reloads it prior to saving the config if
|
||||
it has been changed during runtime by external editing, hence no config settings added manually while the server
|
||||
was running should be overwritten anymore.
|
||||
* Automatically hard-reload the UI if upon reconnecting to the server a new version is detected.
|
||||
* Better handling of errors on the websocket - no more logging of the full stack trace to the log, only a warning
|
||||
message for now.
|
||||
* Daemonized OctoPrint now cleans up its pidfile when receiving a TERM signal ([#711](https://github.com/foosel/OctoPrint/issues/711))
|
||||
* Added serial types for OpenBSD ([#551](https://github.com/foosel/OctoPrint/pull/551))
|
||||
* Improved behaviour of terminal:
|
||||
* Disabling autoscrolling now also stops cutting of the log while it's enabled, effectively preventing log lines from
|
||||
being modified at all ([#735](https://github.com/foosel/OctoPrint/issues/735))
|
||||
* Applying filters displays ``[...]`` where lines where removed
|
||||
* Added a link to scroll to the end of the terminal log (useful for when autoscroll is disabled)
|
||||
* Added a link to select all current contents of the terminal log for easy copy-pasting
|
||||
* Added a display of how many lines are displayed, how many are filtered and how many are available in total
|
||||
* Frame rate for timelapses can now be configured per timelapse ([#782](https://github.com/foosel/OctoPrint/pull/782))
|
||||
* Added an option to specify the amount of encoding threads for FFMPEG ([#785](https://github.com/foosel/OctoPrint/pull/785))
|
||||
* "Disconnected" screen now is not shown directly after a close of the socket, instead the client first tries to
|
||||
directly reconnect once, and only if that doesn't work displays the dialog. Should reduce short popups of the dialog
|
||||
due to shaky network connections and/or weird browser behaviour when downloading things from the UI.
|
||||
* Development dependencies can now be installed with ``pip -e .[develop]``
|
||||
* White and transparent colors ;) are supported for the navigation bar ([#789](https://github.com/foosel/OctoPrint/pull/789))
|
||||
* Drag-n-drop overlay for file uploads now uses the full available screen space, improving usability on high resolution
|
||||
displays ([#187](https://github.com/foosel/OctoPrint/issues/187))
|
||||
* OctoPrint server should no longer hang when big changes in the system time happen, e.g. after first contact to an
|
||||
NTP server on a Raspberry Pi image. Achieved through monkey patching Tornado with
|
||||
[this PR](https://github.com/tornadoweb/tornado/pull/1290).
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#435](https://github.com/foosel/OctoPrint/issues/435) - Always interpret negative duration (e.g. for print time left)
|
||||
as 0
|
||||
* [#633](https://github.com/foosel/OctoPrint/issues/633) - Correctly interpret temperature lines from multi extruder
|
||||
setups under Smoothieware
|
||||
* [#556](https://github.com/foosel/OctoPrint/issues/556) - Allow login of the same user from multiple browsers without
|
||||
side effects
|
||||
* [#680](https://github.com/foosel/OctoPrint/issues/680) - Don't accidentally include a newline from the MIME headers
|
||||
in the parsed multipart data from file uploads
|
||||
* [#709](https://github.com/foosel/OctoPrint/issues/709) - Properly initialize time estimation for SD card transfers too
|
||||
* [#715](https://github.com/foosel/OctoPrint/issues/715) - Fixed an error where Event Triggers of type command caused
|
||||
and exception to be raised due to a misnamed attribute in the code
|
||||
* [#717](https://github.com/foosel/OctoPrint/issues/717) - Use ``shutil.move`` instead of ``os.rename`` to avoid cross
|
||||
device renaming issues
|
||||
* [#752](https://github.com/foosel/OctoPrint/pull/752) - Fix error in event handlers sending multiple gcode commands.
|
||||
* [#780](https://github.com/foosel/OctoPrint/issues/780) - Always (re)set file position in SD files to 0 so that reprints
|
||||
work correctly
|
||||
* [#784](https://github.com/foosel/OctoPrint/pull/784) - Also include ``requirements.txt`` in files packed up for
|
||||
``python setup.py sdist``
|
||||
* [#330](https://github.com/foosel/OctoPrint/issues/330) - Ping pong sending to fix potential acknowledgement errors.
|
||||
Also affects [#166](https://github.com/foosel/OctoPrint/issues/166), [#470](https://github.com/foosel/OctoPrint/issues/470)
|
||||
and [#490](https://github.com/foosel/OctoPrint/issues/490).
|
||||
* Various fixes of bugs in newly introduced features and improvements:
|
||||
* [#625](https://github.com/foosel/OctoPrint/pull/625) - Newly added GCODE files were not being added to the analysis
|
||||
queue
|
||||
* [#664](https://github.com/foosel/OctoPrint/issues/664) - Fixed jog controls again
|
||||
* [#677](https://github.com/foosel/OctoPrint/issues/677) - Fixed extruder offsets not being properly editable in
|
||||
printer profiles
|
||||
* [#683](https://github.com/foosel/OctoPrint/issues/683) - Fixed heated bed option not being properly displayed in
|
||||
printer profiles
|
||||
* [#685](https://github.com/foosel/OctoPrint/issues/685) - Quoted file name for Timelapse creation to not make
|
||||
command hiccup on ``~`` in file name
|
||||
* [#709](https://github.com/foosel/OctoPrint/issues/709) - Fixed file sending to SD card
|
||||
* [#714](https://github.com/foosel/OctoPrint/issues/714) - Fixed type validation of printer profiles
|
||||
* Heating up the heated bed (if present) was not properly configured in CuraEngine plugin
|
||||
* [#720](https://github.com/foosel/OctoPrint/issues/720) - Fixed translation files not being properly copied over
|
||||
during install
|
||||
* [#724](https://github.com/foosel/OctoPrint/issues/724) - Fixed timelapse deletion for timelapses with non-ascii
|
||||
characters in their name
|
||||
* [#726](https://github.com/foosel/OctoPrint/issues/726) - Fixed ``babel_refresh`` command
|
||||
* [#759](https://github.com/foosel/OctoPrint/pull/759) - Properly initialize counter for template plugins of type
|
||||
"generic"
|
||||
* [#775](https://github.com/foosel/OctoPrint/pull/775) - Error messages in javascript console show the proper name
|
||||
of the objects
|
||||
* [#795](https://github.com/foosel/OctoPrint/issues/795) - Allow adding slicing profiles for unconfigured slicers
|
||||
* [#809](https://github.com/foosel/OctoPrint/issues/809) - Added proper form validation to printer profile editor
|
||||
* Various fixes without tickets:
|
||||
* GCODE viewer now doesn't stumble over completely extrusionless GCODE files
|
||||
* Do not deliver the API key on settings API unless user has admin rights
|
||||
* Don't hiccup on slic3r filament_diameter comments in GCODE generated for multi extruder setups
|
||||
* Color code successful or failed print results directly in file list, not just after a reload
|
||||
* Changing Timelapse post roll activates save button
|
||||
* Timelapse post roll is loaded properly from config
|
||||
* Handling of files on the printer's SD card contained in folders now works correctly
|
||||
* Don't display a "Disconnected" screen when trying to download a timelapse in Firefox
|
||||
* Fixed handling of SD card files in folders
|
||||
* Fixed refreshing of timelapse file list upon finished rendering of a new one
|
||||
|
||||
## 1.1.0 - 2014-09-03
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/master...devel))
|
||||
|
||||
## 1.1.2 (Unreleased)
|
||||
|
||||
### Improvements
|
||||
|
||||
* Added deletion of `*.pyc` files to `python setup.py clean` command, should help tremendously when switching branches (backported
|
||||
from [9e014eb](https://github.com/foosel/OctoPrint/commit/9e014eba1feffde11ed0601d9c911b8cac9f3fb0))
|
||||
* Increased default communication and connection timeouts
|
||||
* [#706](https://github.com/foosel/OctoPrint/issues/706) - Do not truncate error reported from printer
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated
|
||||
by versioneer
|
||||
* [#679](https://github.com/foosel/OctoPrint/issues/679) - Fix error where API state is requested and printer is offline
|
||||
(backport of [619fe9a](https://github.com/foosel/OctoPrint/commit/619fe9a0e78826bd1524b235a910156439bcb6d7)).
|
||||
* [#719](https://github.com/foosel/OctoPrint/issues/719) - Properly center print bed in GCODE viewer
|
||||
* [#780](https://github.com/foosel/OctoPrint/issues/780) - Always (re)set file position in SD files to 0 so that reprints
|
||||
work correctly (backported from ``devel``)
|
||||
* [#801](https://github.com/foosel/OctoPrint/issues/801) - Fixed setting of bed temperature offset
|
||||
* [IRC] - Don't hiccup on slic3r ``filament_diameter`` comments generated for multi extruder setups
|
||||
* [ML] - Fixed relative URL to SockJS endpoint, wasn't yet using the proper base url
|
||||
* [unreported] & [#698](https://github.com/foosel/OctoPrint/issues/698) - Generated URLs now take X-Forwarded-Host header
|
||||
sent by proxies into account for included host and port, also fixed [#698](https://github.com/foosel/OctoPrint/issues/698)
|
||||
introduced by this
|
||||
* Small fixes for timelapse creation:
|
||||
- [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there
|
||||
was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b)
|
||||
and [bf9d5ef](https://github.com/foosel/OctoPrint/commit/bf9d5efe43a1e57aacd8512125082ddca06b4efc))
|
||||
- [#693](https://github.com/foosel/OctoPrint/issues/693) - Try not to capture an image if image counter is still unset
|
||||
- [unreported] Synchronize image counter decrementing as well as incrementing to prevent rare race conditions when generating the
|
||||
image file names
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.1.1...master))
|
||||
|
||||
## 1.1.1 (2014-10-27)
|
||||
|
||||
### Improvements
|
||||
|
||||
* The API is now enabled by default and the API key -- if not yet set -- will be automatically generated on first
|
||||
server start and written back into ``config.yaml``
|
||||
* Event subscriptions are now enabled by default (it was an accident that they weren't)
|
||||
* Generate the key used for session hashing individually for each server instance
|
||||
* Generate the salt used for hashing user passwords individually for each server instance
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#580](https://github.com/foosel/OctoPrint/issues/580) - Properly unset job data when instructed so by callers
|
||||
* [#604](https://github.com/foosel/OctoPrint/issues/604) - Properly initialize settings basedir on server startup
|
||||
* [IRC] Also allow downloading .g files via Tornado
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.1.0...1.1.1))
|
||||
|
||||
## 1.1.0 (2014-09-03)
|
||||
|
||||
### New Features
|
||||
|
||||
@@ -103,6 +292,6 @@
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.0.0...1.1.0))
|
||||
|
||||
## 1.0.0
|
||||
## 1.0.0 (2014-06-22)
|
||||
|
||||
First release with new versioning scheme.
|
||||
First release with new versioning scheme.
|
||||
@@ -1,17 +1,49 @@
|
||||
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.
|
||||
Read the following short instructions **fully** and **follow them** if you want your ticket to be taken care of and not closed again directly! They are linked on top of every new issue form, so don't say nobody warned you afterwards.
|
||||
|
||||
- **Read the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)**
|
||||
- Always create **one ticket for one purpose**. So don't mix two or more feature requests, support requests, bugs etc into one ticket. If you do, your ticket will be closed!
|
||||
- If you want to report a bug, **READ AND FOLLOW [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 (**and really EVERYTHING that is written in there!**) you don't have to do anything special with your ticket. Listen to what GitIssueBot might have to say to you!
|
||||
- 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!**
|
||||
- If you need **support** with a problem of your installation (e.g. if you have problems getting the webcam to work) or have a general **question**, the issue tracker is not the right place. Consult the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) instead!
|
||||
- If you are a developer that wants to brainstorm a pull request or possible changes to the plugin system, **add [Brainstorming] to your issue's title!** (see below).
|
||||
- If you have another reason for creating a ticket that doesn't fit any of the above categories, it's something better suited for the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741).
|
||||
|
||||
Following these guidelines (**especially EVERYTHING mentioned in ["How to file a bug report"](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)**) is necessary so the tickets stay manageable - you are not the only one with an open issue, so please respect that you have to **play by the rules** so that your problem can be taken care of. Tickets not playing by the rules **will be closed without further investigation!**.
|
||||
|
||||
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. If you want to add a new feature to OctoPrint, **please always first consider if it wouldn't be better suited for a
|
||||
plugin.** As a general rule of thumb, any feature that is only of interest to a small sub group should be moved into a
|
||||
plugin. If the current plugin system doesn't allow you to implement your feature as a plugin, create a "Brainstorming"
|
||||
ticket to get the discussion going how best to solve *this* in OctoPrint's plugin system - maybe that's the actual PR
|
||||
you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large changes to the code or appearance, please open a "Brainstorming" ticket first** so that
|
||||
we can determine if it's a good time for your specific pull request. It might be that I'm currently in the process of
|
||||
making heavy changes to the code locations you'd target as well, or your approach doesn't fit the general "project
|
||||
vision", and that would just cause unnecessary work and frustration for everyone or possibly get the PR rejected.
|
||||
3. When adding code to OctoPrint, make sure you **follow the current coding style**. That means tabs instead of spaces in the
|
||||
python files (yes, I know that this goes against PEP-8, I don't care) and space instead of tabs in the Javascript sources,
|
||||
english language (that means code, variables, comments!), comments where necessary (tell why the code does something like
|
||||
it does it, structure your code), following the general architecture. If your PR needs to make changes to the Stylesheets,
|
||||
change the ``.less`` files from which the CSS is compiled. PRs that contain direct changes to the compiled
|
||||
CSS will be closed.
|
||||
4. **Test your changes thoroughly**. That also means testing with usage scenarios you don't normally use, e.g. if you only
|
||||
use access control, test without and vice versa. If you only test with your printer, test with the virtual printer and
|
||||
vice versa. State in your pull request how your tested your changes.
|
||||
5. Please create all pull requests **against the `devel` branch**.
|
||||
6. Create **one pull request per feature/bug fix**.
|
||||
7. 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.
|
||||
7. 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. The more thoroughly you explain your intent behind the PR here, the higher the chances it will get merged
|
||||
fast.
|
||||
|
||||
History
|
||||
-------
|
||||
|
||||
* 2015-01-23: More guidelines for creating pull requests, support/questions redirected to Mailinglist/G+ community
|
||||
* 2015-01-27: Added another explicit link to the FAQ
|
||||
@@ -1,4 +1,8 @@
|
||||
recursive-include src/octoprint/static *
|
||||
recursive-include src/octoprint/templates *
|
||||
recursive-include src/octoprint/plugins *
|
||||
recursive-include src/octoprint/translations *
|
||||
include versioneer.py
|
||||
include src/octoprint/_version.py
|
||||
include README.md
|
||||
include requirements.txt
|
||||
@@ -29,43 +29,45 @@ OctoPrint via `setup.py`:
|
||||
|
||||
python setup.py install
|
||||
|
||||
You should also do this after pulling from the repository, since the dependencies might have changed.
|
||||
You should also do this every time after pulling from the repository, since the dependencies might have changed.
|
||||
|
||||
OctoPrint currently only supports Python 2.7.
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
From the source directory you can start the server via
|
||||
Running the `setup.py` script installs the `octoprint` script in your Python installation's scripts folder
|
||||
(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The
|
||||
following usage examples assume that said `octoprint` script is on your `PATH`.
|
||||
|
||||
./run
|
||||
You can start the server via
|
||||
|
||||
octoprint
|
||||
|
||||
By default it binds to all interfaces on port 5000 (so pointing your browser to `http://127.0.0.1:5000`
|
||||
will do the trick). If you want to change that, use the additional command line parameters `host` and `port`,
|
||||
which accept the host ip to bind to and the numeric port number respectively. If for example you want the server
|
||||
to only listen on the local interface on port 8080, the command line would be
|
||||
|
||||
./run --host=127.0.0.1 --port=8080
|
||||
octoprint --host=127.0.0.1 --port=8080
|
||||
|
||||
Alternatively, the host and port on which to bind can be defined via the configuration.
|
||||
|
||||
If you want to run OctoPrint as a daemon (only supported on Linux), use
|
||||
|
||||
./run --daemon {start|stop|restart} [--pid PIDFILE]
|
||||
octoprint --daemon {start|stop|restart} [--pid PIDFILE]
|
||||
|
||||
If you do not supply a custom pidfile location via `--pid PIDFILE`, it will be created at `/tmp/octoprint.pid`.
|
||||
|
||||
You can also specify the configfile or the base directory (for basing off the `uploads`, `timelapse` and `logs` folders),
|
||||
e.g.:
|
||||
|
||||
./run --config /path/to/another/config.yaml --basedir /path/to/my/basedir
|
||||
octoprint --config /path/to/another/config.yaml --basedir /path/to/my/basedir
|
||||
|
||||
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`.
|
||||
See `octoprint --help` for further information.
|
||||
|
||||
OctoPrint also ships with a `run` script in its source directory. You can also invoke that to start up the server, it
|
||||
takes the same command line arguments as the `octoprint` script.
|
||||
|
||||
Configuration
|
||||
-------------
|
||||
@@ -75,4 +77,5 @@ which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows
|
||||
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).
|
||||
[on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration). Please note that the most commonly used
|
||||
configuration settings can also easily be edited from OctoPrint's settings dialog.
|
||||
@@ -1,6 +1,8 @@
|
||||
[python: src/octoprint/**.py]
|
||||
[jinja2: src/octoprint/templates/**.jinja2]
|
||||
[jinja2: src/octoprint/plugins/**.jinja2]
|
||||
extensions=jinja2.ext.autoescape, jinja2.ext.with_
|
||||
|
||||
[javascript: src/octoprint/static/js/app/**.js]
|
||||
[javascript: src/octoprint/plugins/**.js]
|
||||
extract_messages = gettext, ngettext
|
||||
@@ -0,0 +1,38 @@
|
||||
/* override table width restrictions */
|
||||
.wy-table-responsive table td, .wy-table-responsive table th {
|
||||
/* !important prevents the common CSS stylesheets from
|
||||
overriding this as on RTD they are loaded after this stylesheet */
|
||||
white-space: normal !important;
|
||||
}
|
||||
|
||||
.wy-table-responsive {
|
||||
overflow: visible !important;
|
||||
}
|
||||
|
||||
/* style headlink for code block captions like other headlinks */
|
||||
.code-block-caption .headerlink {
|
||||
display: none;
|
||||
visibility: hidden;
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
font-style: normal;
|
||||
font-weight: normal;
|
||||
line-height: 1;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
.code-block-caption:hover .headerlink {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.code-block-caption .headerlink:after {
|
||||
visibility: visible;
|
||||
content: "\f0c1";
|
||||
font-family: FontAwesome;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
/* make whitespace visualization in code listings not appear on same vertical position as dashes */
|
||||
.highlight .w {
|
||||
vertical-align: 10%;
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
.. _sec-api-apps:
|
||||
|
||||
****
|
||||
Apps
|
||||
****
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-apps-sessionkey:
|
||||
|
||||
Session Keys
|
||||
============
|
||||
|
||||
OctoPrint offers a special API key type for apps to use, the so called App Session Key. These keys have a time based
|
||||
validity and are generated by OctoPrint for requesting apps.
|
||||
|
||||
Obtaining those keys is based on a handshake procedure backed by cryptographic signatures using RSA. OctoPrint needs to
|
||||
be aware of apps and their associated public keys (this can be achieved either via entries in ``config.yaml`` or by
|
||||
installing app specific plugins which implement the ``AppPlugin`` type).
|
||||
|
||||
Apps can be registered within OctoPrint via ``config.yaml`` by adding them to the ``api`` > ``apps`` section, using the
|
||||
application's id concatenated with its version as key, with the public key provided as item ``pubkey`` (stripped of the
|
||||
``BEGIN RSA PUBLIC KEY`` and ``END RSA PUBLIC KEY`` separators and also newlines) and optionally also whether the app is
|
||||
enabled or not (defaults to enabled, so can be left out if it's not to be set to disabled explicitly).
|
||||
|
||||
Example:
|
||||
|
||||
.. sourcecode:: yaml
|
||||
|
||||
api:
|
||||
apps:
|
||||
"com.example.my_octoprint_app:0.9":
|
||||
pubkey: MEgCQQDYkr5Fv/YXK5ZL1uwRN4A61IagZaYLGqJ5JJGFo8wDrmpAMRqE9kK4+5hIDblC5DzfEr5oP7OA3tRO48Rf5yInAgMBAAE=
|
||||
enabled: false
|
||||
"com.example.my_octoprint_app:1.0":
|
||||
pubkey: MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4osvb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE=
|
||||
|
||||
In the example, the app ``com.example.my_octoprint_app`` in version 0.9 has been disabled (e.g. due to the key having
|
||||
leaked) whereas version 1.0 is fully registered with OctoPrint and may verify app session keys.
|
||||
|
||||
|
||||
.. _sec-api-apps-sessionkey-workflow:
|
||||
|
||||
Workflow
|
||||
--------
|
||||
|
||||
Apps perform the handshake by first requesting a temporary key with very limited validity,
|
||||
then sending a message back to OctoPrint containing their id, version, the temporary key and a signature created with their
|
||||
private key over these three pieces of data. OctoPrint then tries to verify the signature and if successful unlocks the
|
||||
key to be used as a fully recognized API key.
|
||||
|
||||
For performing the handshake a special API exists within OctoPrint for which no API key is needed which is described below.
|
||||
|
||||
.. _sec-api-apps-sessionkey-get:
|
||||
|
||||
Obtaining a temporary session key
|
||||
---------------------------------
|
||||
|
||||
.. http:get:: /apps/auth
|
||||
|
||||
Retrieve a temporary session key with a minimum validity. It can only be used as a proper API key after having been
|
||||
:ref:`verified <sec-api-apps-sessionkey-verify>`.
|
||||
|
||||
Returns the temporary session key and the timestamp until it's valid.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /apps/auth HTTP/1.1
|
||||
Host: example.com
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"unverifiedKey": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"validUntil": 1416220357.011
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-apps-sessionkey-verify:
|
||||
|
||||
Verifying a temporary session key
|
||||
---------------------------------
|
||||
|
||||
.. http:post:: /apps/auth
|
||||
|
||||
Verify a formerly :ref:`retrieved <sec-api-apps-sessionkey-get>` temporary session key by providing credentials and a
|
||||
cryptographic signature over these credentials and the temporary key.
|
||||
|
||||
Returns the now verified session key and the new validity.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /apps/auth HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"appid": "com.example.my_octoprint_app",
|
||||
"appversion": "1.0",
|
||||
"key": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"_sig": "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w=="
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"key": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"validUntil": 1416227497.011
|
||||
}
|
||||
|
||||
.. _sec-api-apps-sessionkey-signature:
|
||||
|
||||
Creating the signature
|
||||
----------------------
|
||||
|
||||
The signature is created by concatenating the ``appid``, ``appversion`` and ``key`` fields, separated by a ``:`` (colon),
|
||||
signing the result with the app's private key using SHA-1 and then BASE64-encoding the result, stripping newlines.
|
||||
|
||||
Example for signature generation using Python and the `Python RSA library <https://pypi.python.org/pypi/rsa>`_:
|
||||
|
||||
.. sourcecode:: python
|
||||
|
||||
import base64
|
||||
import rsa
|
||||
|
||||
appid = "com.example.my_octoprint_app"
|
||||
version = "1.0"
|
||||
unverified_key = "F43A844750F74AD080FE9F438D47B33C"
|
||||
message_to_sign = appid + ":" + version + ":" + unverified_key
|
||||
// => "com.example.my_octoprint_app:1.0:F43A844750F74AD080FE9F438D47B33C"
|
||||
|
||||
private_key = rsa.PrivateKey.load_pkcs1("...")
|
||||
signature = base64.encodestring(rsa.sign(message_to_sign, private_key, "SHA-1")).replace("\n", "")
|
||||
// => "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w=="
|
||||
|
||||
|
||||
.. _sec-api-apps-sessionkey-testing:
|
||||
|
||||
Testing your implementation
|
||||
---------------------------
|
||||
|
||||
If you want to use app session keys, here is the key pair with which the above examples were created, in order for you
|
||||
to verify your signature implementation::
|
||||
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIBPQIBAAJBAIhZ+Ls1zxtyd9kkm0DprhHIwL6woGUw5vbk5U00Hgva/ROIY7va
|
||||
NUpHiiy9vijO2VtFbkaR2JjRPYslx8Ni+QkCAwEAAQJARK4lFo+FEcs3yR2iQjEy
|
||||
p+yaAbNQJ4hZXlVvltLAYICzOM3kyKx53/eKU59NjskLz9q6QxfleymYPWAgl4NW
|
||||
fQIjAJVH8MjwNcaAquTM9z2OiFi3OC8WgaKOi5W/T+r2+B70wG8CHwDp08dqOZ/u
|
||||
xcBiy4Wzpcme9bckqoVuS3gWMm+YqgcCIwCMFU07kkY0NyumtzxPdIA4F/7OGSWf
|
||||
IHqWFEfvasAddHlbAh8A5UgkB3Zf7Bt+7aFSBnlvve6FWm/XDPL12xYztYgrAiIa
|
||||
W3miN6FjIm+8TDowrk+nyYXG2GZefeY7QXOjYr6tlDn0
|
||||
-----END RSA PRIVATE KEY-----
|
||||
|
||||
-----BEGIN RSA PUBLIC KEY-----
|
||||
MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4os
|
||||
vb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE=
|
||||
-----END RSA PUBLIC KEY-----
|
||||
|
||||
@@ -33,13 +33,16 @@ Get connection settings
|
||||
"current": {
|
||||
"state": "Operational",
|
||||
"port": "/dev/ttyACM0",
|
||||
"baudrate": 250000
|
||||
"baudrate": 250000,
|
||||
"printerProfile": "_default"
|
||||
},
|
||||
"options": {
|
||||
"ports": ["/dev/ttyACM0", "VIRTUAL"],
|
||||
"baudrates": [250000, 230400, 115200, 57600, 38400, 19200, 9600],
|
||||
"printerProfiles": [{"name": "Default", id: "_default"}],
|
||||
"portPreference": "/dev/ttyACM0",
|
||||
"baudratePreference": 250000,
|
||||
"printerProfilePreference": "_default",
|
||||
"autoconnect": true
|
||||
}
|
||||
}
|
||||
@@ -62,6 +65,8 @@ Issue a connection command
|
||||
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.
|
||||
* ``printerProfile`` Optional, specific printer profile to use for connection. If not set the current default printer
|
||||
profile will be used.
|
||||
* ``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.
|
||||
@@ -83,6 +88,7 @@ Issue a connection command
|
||||
"command": "connect",
|
||||
"port": "/dev/ttyACM0",
|
||||
"baudrate": 115200,
|
||||
"printerProfile": "my_printer_profile",
|
||||
"save": true,
|
||||
"autoconnect": true
|
||||
}
|
||||
@@ -115,6 +121,8 @@ Issue a connection command
|
||||
: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 string printerProfile: ``connect`` command: The id of the printer profile to use for the connection. If left out the current
|
||||
default printer profile will be used. Must be part of the available printer profiles.
|
||||
: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
|
||||
|
||||
@@ -304,7 +304,34 @@ Issue a file command
|
||||
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.
|
||||
slice
|
||||
Slices an STL file into GCODE. Note that this is an asynchronous operation that will take place in the background
|
||||
after the response has been sent back to the client. Additional parameters are:
|
||||
|
||||
* ``slicer``: The slicing engine to use, defaults to ``cura`` if not set, which is also the only supported slicer right now.
|
||||
* ``gcode``: Name of the GCODE file to generated, in the same location as the STL file. Defaults to the STL file name
|
||||
with extension ``.gco`` if not set.
|
||||
* ``position``: Position of the object-to-slice's center on the print bed. A dictionary containing both ``x`` and ``y``
|
||||
coordinate in mm is expected
|
||||
* ``printerProfile``: Name of the printer profile to use, if not set the default printer profile will be used.
|
||||
* ``profile``: Name of the slicing profile to use, if not set the default slicing profile of the slicer will be used.
|
||||
* ``profile.*``: Override parameters, the ``profile.`` prefix will be stripped and the matching profile key will
|
||||
be overridden with the supplied value. Use this if you want to specify things that change often like a different
|
||||
temperature, filament diameter or infill percentage. Profile keys are slicer specific.
|
||||
* ``select``: Optional, if set to ``true`` the file be selected for printing right after the slicing has finished. If the
|
||||
printer is not operational or already printing when this parameter is present and set to ``true``, the request will
|
||||
fail with a response of ``409 Conflict``
|
||||
* ``print``: Optional, if set to ``true`` the file be selected and start printing right after the slicing has finished.
|
||||
If the printer is not operational or already printing when this parameter is present and set to ``true``, the request
|
||||
will fail with a response of ``409 Conflict``. Note that if this parameter is set, the parameter ``select`` does not
|
||||
need to be set, it is automatically assumed to be ``true`` too, otherwise no printing would be possible.
|
||||
|
||||
If consecutive slicing calls are made targeting the same GCODE filename (that also holds true if the default is used),
|
||||
the slicing job already running in the background will be cancelled before the new one is started. Note that this will
|
||||
also mean that if it was supposed to be directly selected and start printing after the slicing finished, this will not
|
||||
take place anymore and whether this will happen with the new sliced file depends entirely on the new request!
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned, unless specified otherwise.
|
||||
|
||||
**Example Select Request**
|
||||
|
||||
@@ -324,16 +351,66 @@ Issue a file command
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
: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.
|
||||
**Example Slice Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/files/local/some_model.stl HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "slice",
|
||||
"slicer": "cura",
|
||||
"gcode": "some_model.first_try.gcode",
|
||||
"printerProfile": "my_custom_reprap",
|
||||
"profile": "high_quality",
|
||||
"profile.infill": 75,
|
||||
"profile.fill_density": 15,
|
||||
"position": {"x": 100, "y": 100},
|
||||
"print": true
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 202 Accepted
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"origin": "local",
|
||||
"name": "some_model.first_try.gcode",
|
||||
"refs": {
|
||||
"download": "http://example.com/downloads/files/local/some_model.first_try.gcode",
|
||||
"resource": "http://example.com/api/files/local/some_model.first_try.gcode"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
:param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads``
|
||||
folder) or ``sdcard`` for the printer's SD card (if available)
|
||||
:param filename: The filename of the file for which to issue the command
|
||||
:json string command: The command to issue for the file, currently only ``select`` is supported
|
||||
:json boolean print: ``select`` and ``slice`` command: Optional, whether to start printing the file directly after selection
|
||||
or slicing, defaults to ``false``.
|
||||
:json string slicer: ``slice`` command: The slicer to use, defaults to the default slicer.
|
||||
:json string gcode: ``slice`` command: The name of the gcode file to create, defaults to the targeted stl's file name
|
||||
with its extension changed to ``.gco`` (e.g. "test.stl" will be sliced to "test.gco" if not specified
|
||||
otherwise)
|
||||
:json string profile: ``slice`` command: The slicing profile to use, defaults to the selected slicer's default profile.
|
||||
:json string profile.*: ``slice`` command: Overrides for the selected slicing profile, e.g. to specify a different temperature
|
||||
or filament diameter.
|
||||
:json string printerProfile: ``slice`` command: The printer profile to use, defaults to the default printer profile.
|
||||
:json boolean select: ``slice`` command: Optional, whether to select the file for printing directly after slicing,
|
||||
defaults to ``false``
|
||||
:statuscode 200: No error for a ``select`` command.
|
||||
:statuscode 202: No error for a ``slice`` command.
|
||||
:statuscode 400: If the ``command`` is unknown or the request is otherwise invalid
|
||||
:statuscode 415: If a ``slice`` command was issued against something other than an STL file.
|
||||
: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 or
|
||||
if a file to be sliced is supposed to be selected or start printing directly but the printer
|
||||
is not operational or already printing.
|
||||
|
||||
.. _sec-api-fileops-delete:
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ 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.
|
||||
configured one, a user specific one if "Access Control" is enabled or an ref:`App Session Key <sec-api-apps-sessionkey>`.
|
||||
Users are able to generate and revoke their custom API key via the "Change password" dialog.
|
||||
|
||||
The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
.. _sec-api:
|
||||
|
||||
#################
|
||||
API Documentation
|
||||
#################
|
||||
########
|
||||
REST API
|
||||
########
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
general.rst
|
||||
version.rst
|
||||
apps.rst
|
||||
fileops.rst
|
||||
connection.rst
|
||||
printer.rst
|
||||
printerprofiles.rst
|
||||
job.rst
|
||||
logs.rst
|
||||
slicing.rst
|
||||
push.rst
|
||||
datamodel.rst
|
||||
@@ -199,8 +199,13 @@ Issue a print head command
|
||||
|
||||
* ``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.
|
||||
feedrate
|
||||
Changes the feedrate factor to apply to the movement's of the axes.
|
||||
|
||||
* ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 50 and 200%.
|
||||
|
||||
All of these commands except ``feedrate`` 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.
|
||||
|
||||
@@ -246,13 +251,34 @@ Issue a print head command
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example feed rate request**
|
||||
|
||||
Set the feed rate factor to 105%.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/printhead HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "feedrate",
|
||||
"factor": 105
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
: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``.
|
||||
:json number factor: ``feedrate`` command: The factor to apply to the feed rate, percentage between 50 and 200% as integer or float.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: Invalid axis specified, invalid value for travel amount for a jog command or otherwise invalid
|
||||
:statuscode 400: Invalid axis specified, invalid value for travel amount for a jog command or factor for feed rate or otherwise invalid
|
||||
request.
|
||||
:statuscode 409: If the printer is not operational or currently printing.
|
||||
|
||||
@@ -288,6 +314,10 @@ Issue a tool command
|
||||
|
||||
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
|
||||
|
||||
flowrate
|
||||
Changes the flow rate factor to apply to extrusion of the tool.
|
||||
|
||||
* ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 75 and 125%.
|
||||
|
||||
All of these commands may only be sent if the printer is currently operational and -- in case of ``select`` and
|
||||
``extrude`` -- not printing. Otherwise a :http:statuscode:`409` is returned.
|
||||
@@ -400,14 +430,35 @@ Issue a tool command
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example flow rate request**
|
||||
|
||||
Set the flow rate factor to 95%.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/tool HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "flowrate",
|
||||
"factor": 95
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``target``, ``offset``, ``select`` or ``extrude``.
|
||||
:json object targets: ``target`` command: The target temperatures to set. Valid properties have to match the format ``tool{n}``.
|
||||
:json object offsets: ``offset`` command: The offset temperature to set. Valid properties have to match the format ``tool{n}``.
|
||||
:json object tool: ``select`` command: The tool to select, value has to match the format ``tool{n}``.
|
||||
:json object amount: ``extrude`` command: The amount of filament to extrude from the currently selected tool.
|
||||
:json number factor: ``flowrate`` command: The factor to apply to the flow rate, percentage between 75 and 125% as integer or float.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If ``targets`` or ``offsets`` contains a property or ``tool`` contains a value not matching the format
|
||||
``tool{n}``, the target/offset temperature or extrusion amount is not a valid number or outside of
|
||||
``tool{n}``, the target/offset temperature, extrusion amount or flow rate factor 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 or -- in case of ``select`` or ``extrude`` -- currently printing.
|
||||
|
||||
@@ -755,6 +806,61 @@ Retrieve the current SD state
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If SD support has been disabled in OctoPrint's config.
|
||||
|
||||
.. _sec-api-printer-arbcommand:
|
||||
|
||||
Send an arbitrary command to the printer
|
||||
========================================
|
||||
|
||||
.. http:post:: /api/printer/command
|
||||
|
||||
Sends any command to the printer via the serial interface. Should be used with some care as some commands can interfere with
|
||||
or even stop a running print job.
|
||||
|
||||
Expects a :ref:`Arbitrary Command Request <sec-api-printer-datamodel-arbcommand>` as the request's body.
|
||||
|
||||
If successful returns a :http:statuscode:`204` and an empty body.
|
||||
|
||||
**Example for sending a single command**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/command HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "M106"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example for sending multiple commands**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/command HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"commands": [
|
||||
"M18",
|
||||
"M106 S0"
|
||||
]
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: Single command to send to the printer, mutually exclusive with ``commands``.
|
||||
:json string commands: List of commands to send to the printer, mutually exclusive with ``command``.
|
||||
:statuscode 204: No error
|
||||
|
||||
.. _sec-api-printer-datamodel:
|
||||
|
||||
Datamodel
|
||||
@@ -783,7 +889,7 @@ Full State Response
|
||||
- The printer's sd state data
|
||||
* - ``state``
|
||||
- 0..1
|
||||
- :ref:`Printer State <sec-api-printer-datamodel-printerstate>`
|
||||
- :ref:`Printer State <sec-api-datamodel-printer-state>`
|
||||
- The printer's general state
|
||||
|
||||
.. _sec-api-printer-datamodel-temps:
|
||||
@@ -831,3 +937,36 @@ SD State
|
||||
- Boolean
|
||||
- Whether the SD card has been initialized (``true``) or not (``false``).
|
||||
|
||||
.. _sec-api-printer-datamodel-arbcommand:
|
||||
|
||||
Arbitrary Command Request
|
||||
-------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``command``
|
||||
- 0..1
|
||||
- String
|
||||
- Single command to send to the printer, mutually exclusive with ``commands`` and ``script``.
|
||||
* - ``commands``
|
||||
- 0..*
|
||||
- Array of String
|
||||
- Multiple commands to send to the printer (in the given order), mutually exclusive with ``command`` and ``script``.
|
||||
* - ``script``
|
||||
- 0..*
|
||||
- String
|
||||
- Name of the GCODE script template to send to the printer, mutually exclusive with ``command`` and ``commands``.
|
||||
* - ``parameters``
|
||||
- 0..1
|
||||
- Map of key value pairs
|
||||
- Key value pairs of parameters to replace in sent commands/provide to the script renderer
|
||||
* - ``context``
|
||||
- 0..1
|
||||
- Map of key value pairs
|
||||
- (only if ``script`` is set) additional template variables to provide to the script renderer
|
||||
@@ -0,0 +1,190 @@
|
||||
.. _sec-api-printerprofiles:
|
||||
|
||||
**************************
|
||||
Printer profile operations
|
||||
**************************
|
||||
|
||||
.. contents::
|
||||
|
||||
OctoPrint allows the management of Printer profiles that define a printer's physical properties (such as print volume,
|
||||
whether a heated bed is available, maximum speeds on its axes etc). The data stored within these profiles is used
|
||||
for both slicing and gcode visualization.
|
||||
|
||||
.. _sec-api-printerprofiles-retrieve:
|
||||
|
||||
Retrieve all printer profiles
|
||||
=============================
|
||||
|
||||
.. http:get:: /api/printerprofiles
|
||||
|
||||
.. _sec-api-printerprofiles-add:
|
||||
|
||||
Add a new printer profile
|
||||
=========================
|
||||
|
||||
.. http:post:: /api/printerprofiles
|
||||
|
||||
.. _sec-api-printerporfiles-update:
|
||||
|
||||
Update an existing printer profile
|
||||
==================================
|
||||
|
||||
.. http:patch:: /api/printerprofiles/(string:profile)
|
||||
|
||||
.. _sec-api-printerprofiles-delete:
|
||||
|
||||
Remove an existing printer profile
|
||||
==================================
|
||||
|
||||
.. http:delete:: /api/printerprofiles/(string:profile)
|
||||
|
||||
.. _sec-api-printerprofiles-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-printerprofiles-datamodel-profilelist:
|
||||
|
||||
Profile list
|
||||
------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``profiles``
|
||||
- 1
|
||||
- Object
|
||||
- Collection of all printer profiles available in the system
|
||||
* - ``profiles.<profile id>``
|
||||
- 0..1
|
||||
- :ref:`Profile <sec-api-slicing-datamodel-profile>`
|
||||
- Information about a profile stored in the system.
|
||||
|
||||
.. _sec-api-printerprofiles-datamodel-update:
|
||||
|
||||
Add or update request
|
||||
---------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``profiles``
|
||||
- 1
|
||||
- :ref:`Profile <sec-api-slicing-datamodel-profile>`
|
||||
- Information about the profile being added/updated. For adding new profiles, all fields must be populated. For updating
|
||||
and existing profile, only the values to be overwritten need to be supplied.
|
||||
|
||||
.. _sec-api-printerprofiles-datamodel-profile:
|
||||
|
||||
Profile
|
||||
-------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``id``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Identifier of the profile. Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``name``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Display name of the profile. Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``color``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- The color to associate with this profile (used in the UI's title bar). Valid values are "default", "red", "orange",
|
||||
"yellow", "green", "blue", "black". Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``model``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Printer model of the profile. Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``default``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether this is the default profile to be used with new connections (``true``) or not (``false``). Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``current``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether this is the profile currently active. Will always be returned in responses but ignored in save/update
|
||||
requests.
|
||||
* - ``resource``
|
||||
- 0..1
|
||||
- ``URL``
|
||||
- Resource URL of the profile, will always be returned in responses but can be left out of save/update requests.
|
||||
* - ``volume``
|
||||
- 0..1
|
||||
- Object
|
||||
- The print volume, will always be returned in responses but can be left out of save/update requests.
|
||||
* - ``volume.formFactor``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- The form factor of the printer's bed, valid values are "rectangular" and "circular"
|
||||
* - ``volume.width``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- The width of the print volume
|
||||
* - ``volume.depth``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- The depth of the print volume
|
||||
* - ``volume.height``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- The height of the print volume
|
||||
* - ``heatedBed``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether the printer has a heated bed (``true``) or not (``false``)
|
||||
* - ``axes``
|
||||
- 0..1
|
||||
- Object
|
||||
- Description of the printer's axes properties, one entry each for ``x``, ``y``, ``z`` and ``e`` holding maxium speed
|
||||
and whether this axis is inverted or not.
|
||||
* - ``axes.{axis}.speed``
|
||||
- 0..1
|
||||
- ``int``
|
||||
- Maximum speed of the axis in mm/s.
|
||||
* - ``axes.{axis}.inverted``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether the axis is inverted or not.
|
||||
* - ``extruder``
|
||||
- 0..1
|
||||
- Object
|
||||
- Information about the printer's extruders
|
||||
* - ``extruder.nozzleDiameter``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- The diameter of the printer's nozzle(s) in mm.
|
||||
* - ``extruder.count``
|
||||
- 0..1
|
||||
- ``int``
|
||||
- Count of extruders on the printer (defaults to 1)
|
||||
* - ``extruder.offsets``
|
||||
- 0..1
|
||||
- Array of ``float`` tuples
|
||||
- Tuple of (x, y) values describing the offsets of the other extruders relative to the first extruder. E.g. for a
|
||||
printer with two extruders, if the second extruder is offset by 20mm in the X and 25mm in the Y direction, this
|
||||
array will read ``[ [0.0, 0.0], [20.0, 25.0] ]``
|
||||
|
||||
@@ -35,6 +35,9 @@ following message types are currently available for usage by 3rd party clients:
|
||||
payload data model as ``current``, see :ref:`below <sec-api-push-datamodel-currentandhistory>`.
|
||||
* ``event``: Events triggered within OctoPrint, such as e.g. ``PrintFailed`` or ``MovieRenderDone``. Payload is the event
|
||||
type and payload, see :ref:`below <sec-api-push-datamodel-event>`. Sent when an event is triggered internally.
|
||||
* ``slicingProgress``: Progress updates from an active slicing background job, payload contains information about the
|
||||
model being sliced, the target file, the slicer being used and the progress as a percentage.
|
||||
See :ref:`the payload data model <sec-api-push-datamodel-slicingprogress>`.
|
||||
|
||||
Clients must ignore any unknown messages.
|
||||
|
||||
@@ -112,3 +115,41 @@ Datamodel
|
||||
- 1
|
||||
- Object
|
||||
- Payload associated with the event
|
||||
|
||||
.. _sec-api-push-datamodel-slicingprogress:
|
||||
|
||||
``slicingProgress`` payload
|
||||
---------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``slicer``
|
||||
- 1
|
||||
- String
|
||||
- Name of the slicer used
|
||||
* - ``source_location``
|
||||
- 1
|
||||
- String
|
||||
- Location of the source file being sliced, at the moment either ``local`` or ``sdcard``
|
||||
* - ``source_path``
|
||||
- 1
|
||||
- String
|
||||
- Path of the source file being sliced (e.g. an STL file)
|
||||
* - ``dest_location``
|
||||
- 1
|
||||
- String
|
||||
- Location of the destination file being created, at the moment either ``local`` or ``sdcard``
|
||||
* - ``dest_path``
|
||||
- 1
|
||||
- String
|
||||
- Path of the destination file being sliced (e.g. a GCODE file)
|
||||
* - ``progress``
|
||||
- 1
|
||||
- Number (Float)
|
||||
- Percentage of slicing job already completed
|
||||
@@ -0,0 +1,336 @@
|
||||
.. _sec-api-slicing:
|
||||
|
||||
*******
|
||||
Slicing
|
||||
*******
|
||||
|
||||
.. warning::
|
||||
|
||||
The interface documented here is the status quo that might be changed while the interfaces are streamlined for
|
||||
a more general consumption. 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::
|
||||
|
||||
The Slicing API on one hand offers methods for managing slicing profiles stored within OctoPrint, on the other hand
|
||||
it will be extended in the future to also allow for multi extruder slicing (which currently is not possible with the
|
||||
``slice`` command of the :ref:`File operations API <sec-api-fileops-filecommand>` and other things.
|
||||
|
||||
.. _sec-api-slicing-listall:
|
||||
|
||||
List All Slicers and Slicing Profiles
|
||||
=====================================
|
||||
|
||||
.. http:get:: /api/slicing
|
||||
|
||||
Returns a list of all available slicing profiles for all registered slicers in the system.
|
||||
|
||||
Returns a :http:statuscode:`200` response with a :ref:`Slicer list <sec-api-slicing-datamodel-slicerlist>`
|
||||
as the body upon successful completion.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/slicing/profiles HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"cura": {
|
||||
"key": "cura",
|
||||
"displayName": "CuraEngine",
|
||||
"default": true,
|
||||
"profiles": {
|
||||
"high_quality": {
|
||||
"key": "high_quality",
|
||||
"displayName": "High Quality",
|
||||
"default": false,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
|
||||
},
|
||||
"medium_quality": {
|
||||
"key": "medium_quality",
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
},
|
||||
...
|
||||
}
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-slicing-list:
|
||||
|
||||
List Slicing Profiles of a Specific Slicer
|
||||
==========================================
|
||||
|
||||
.. http:get:: /api/slicing/(string:slicer)/profiles
|
||||
|
||||
Returns a list of all available slicing profiles for the requested slicer.
|
||||
|
||||
Returns a :http:statuscode:`200` response with a :ref:`Profile list <sec-api-slicing-datamodel-profilelist>`
|
||||
as the body upon successful completion.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/slicing/cura/profiles HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"high_quality": {
|
||||
"key": "high_quality",
|
||||
"displayName": "High Quality",
|
||||
"default": false,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
|
||||
},
|
||||
"medium_quality": {
|
||||
"key": "medium_quality",
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to list the available profiles.
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If the ``slicer`` was unknown to the system.
|
||||
|
||||
.. _sec-api-slicing-listspecific:
|
||||
|
||||
Retrieve Specific Profile
|
||||
=========================
|
||||
|
||||
.. http:get:: /api/slicing/(string:slicer)/profiles/(string:key)
|
||||
|
||||
Retrieves the specified profile from the system.
|
||||
|
||||
Returns a :http:statuscode:`200` response with a :ref:`full Profile <sec-api-slicing-datamodel-profile>`
|
||||
as the body upon successful completion.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/slicing/cura/profiles/quick_test HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test",
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/quick_test",
|
||||
"data": {
|
||||
"bottom_layer_speed": 20.0,
|
||||
"bottom_thickness": 0.3,
|
||||
"brim_line_count": 20,
|
||||
"cool_head_lift": false,
|
||||
"cool_min_feedrate": 10.0,
|
||||
"cool_min_layer_time": 5.0,
|
||||
...
|
||||
}
|
||||
}
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to list the available profiles.
|
||||
:param name: The identifying key of the profile to retrieve
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If the ``slicer`` or the profile was unknown to the system.
|
||||
|
||||
.. _sec-api-slicing-add:
|
||||
|
||||
Add Slicing Profile
|
||||
===================
|
||||
|
||||
.. http:put:: /api/slicing/(string:slicer)/profiles/(string:key)
|
||||
|
||||
Adds a new slicing profile for the given ``slicer`` to the system. If the profile identified by ``key`` already exists,
|
||||
it will be overwritten.
|
||||
|
||||
Expects a :ref:`Profile <sec-api-slicing-datamodel-profile>` as body.
|
||||
|
||||
Returns a :http:statuscode:`201` and an :ref:`abridged Profile <sec-api-slicing-datamodel-profile>` in the body
|
||||
upon successful completion.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
PUT /api/slicing/cura/profiles/quick_test HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
|
||||
"data": {
|
||||
"layer_height": 0.2,
|
||||
"skirt_line_count": 3
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 201 Created
|
||||
Content-Type: application/json
|
||||
Location: http://example.com/api/slicing/cura/profiles/quick_test
|
||||
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/quick_test"
|
||||
}
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to add the profile
|
||||
:param key: The identifying key of the new profile
|
||||
:statuscode 201: No error
|
||||
:statuscode 404: If the ``slicer`` was unknown to the system.
|
||||
|
||||
.. _sec-api-slicing-delete:
|
||||
|
||||
Delete Slicing Profile
|
||||
======================
|
||||
|
||||
.. http:delete:: /api/slicing/(string:slicer)/profiles/(string:key)
|
||||
|
||||
Delete the slicing profile identified by ``key`` for the slicer ``slicer``.
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to delete the profile
|
||||
:param key: The identifying key of the profile to delete
|
||||
:statuscode 204: No error
|
||||
:statuscode 404: If the ``slicer`` was unknown to the system.
|
||||
|
||||
.. _sec-api-slicing-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-slicing-datamodel-slicerlist:
|
||||
|
||||
Slicer list
|
||||
-----------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``<slicer key>``
|
||||
- 0..*
|
||||
- :ref:`Slicer <sec-api-slicing-datamodel-slicer>`
|
||||
- Information about a slicer registered in the system, incl. stored profiles without ``data``.
|
||||
|
||||
.. _sec-api-slicing-datamodel-slicer:
|
||||
|
||||
Slicer
|
||||
------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``key``
|
||||
- 1
|
||||
- ``string``
|
||||
- Identifier of the slicer
|
||||
* - ``displayName``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Display name of the slicer
|
||||
* - ``default``
|
||||
- 1
|
||||
- ``boolean``
|
||||
- Whether the slicer is the default slicer to use (``true``) or not (``false``).
|
||||
* - ``profiles``
|
||||
- 0..*
|
||||
- :ref:`Profile list <sec-api-slicing-datamodel-profilelist>`
|
||||
- Slicing profiles available for this slicer, mapped by their ``key``
|
||||
|
||||
.. _sec-api-slicing-datamodel-profilelist:
|
||||
|
||||
Profile list
|
||||
------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``<profile key>``
|
||||
- 0..1
|
||||
- :ref:`Profile <sec-api-slicing-datamodel-profile>`
|
||||
- Information about a profile stored in the system, ``data`` field will be left out.
|
||||
|
||||
.. _sec-api-slicing-datamodel-profile:
|
||||
|
||||
Profile
|
||||
-------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``key``
|
||||
- 1
|
||||
- ``string``
|
||||
- Identifier of the profile
|
||||
* - ``displayName``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Display name of the profile
|
||||
* - ``description``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Description of the profile
|
||||
* - ``default``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether this is the default profile to be used with this slicer (``true``) or not (``false``). Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``resource``
|
||||
- 0..1
|
||||
- ``URL``
|
||||
- Resource URL of the profile, will always be returned in responses but can be left out of save/update requests.
|
||||
* - ``data``
|
||||
- 0..1
|
||||
- Object
|
||||
- The actual profile data, including any default values if the profile was retrieved from the server. May contain
|
||||
only the keys differing from the defaults when saving/updating a profile. The keys to be found in here a slicer
|
||||
specific. Will be left out for list responses.
|
||||
|
||||
@@ -12,25 +12,27 @@
|
||||
# serve to show the default.
|
||||
|
||||
import sys, os
|
||||
|
||||
# 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('../src/'))
|
||||
sys.path.append(os.path.abspath('sphinxext'))
|
||||
|
||||
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'
|
||||
needs_sphinx = '1.3'
|
||||
|
||||
# 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']
|
||||
extensions = ['codeblockext', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain', 'sphinxcontrib.napoleon']
|
||||
todo_include_todos = True
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
@@ -102,9 +104,9 @@ pygments_style = 'sphinx'
|
||||
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()]
|
||||
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.
|
||||
@@ -139,6 +141,9 @@ if not on_rtd: # only import and set the theme if we're building docs locally
|
||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||
html_static_path = ['_static']
|
||||
|
||||
def setup(app):
|
||||
app.add_stylesheet("theme_overrides.css")
|
||||
|
||||
# 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'
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
.. _sec-configuration-config_yaml:
|
||||
|
||||
config.yaml
|
||||
===========
|
||||
|
||||
If not specified via the command line, the main configuration file ``config.yaml`` for OctoPrint is expected in its
|
||||
settings folder, which unless defined differently via the command line is located at ``~/.octoprint`` on Linux, at
|
||||
``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on MacOS. If the file is not there,
|
||||
you can just create it - it will only get created by OctoPrint once you save settings that deviate from the default
|
||||
settings.
|
||||
|
||||
Note that many of these settings are available from the "Settings" menu in OctoPrint itself.
|
||||
|
||||
Serial
|
||||
------
|
||||
|
||||
Use the following settings to configure the serial connection to the printer:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
serial:
|
||||
# Use the following option to define the default serial port, defaults to unset (= AUTO)
|
||||
port: /dev/ttyACM0
|
||||
|
||||
# Use the following option to define the default baudrate, defaults to unset (= AUTO)
|
||||
baudrate: 115200
|
||||
|
||||
# Whether to automatically connect to the printer on server startup (if available)
|
||||
autoconnect: false
|
||||
|
||||
# Whether to log whole communication to serial.log (warning: might decrease performance)
|
||||
log: false
|
||||
|
||||
# Timeouts used for the serial connection to the printer, you might want to adjust these if you are
|
||||
# experiencing connection problems
|
||||
timeout:
|
||||
|
||||
# Timeout for waiting for a response from the currently tested port during autodetect, in seconds.
|
||||
# Defaults to 0.5 sec
|
||||
detection: 0.5
|
||||
|
||||
# Timeout for waiting to establish a connection with the selected port, in seconds.
|
||||
# Defaults to 2 sec
|
||||
connection: 2
|
||||
|
||||
# Timeout during serial communication, in seconds.
|
||||
# Defaults to 5 sec
|
||||
communication: 5
|
||||
|
||||
# Use this to define additional patterns to consider for serial port listing. Must be a valid
|
||||
# "glob" pattern (see http://docs.python.org/2/library/glob.html). Defaults to not set.
|
||||
additionalPorts:
|
||||
- /dev/myPrinterSymlink
|
||||
|
||||
Server
|
||||
------
|
||||
|
||||
Use the following settings to configure the server:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
server:
|
||||
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all interfaces)
|
||||
host: 0.0.0.0
|
||||
|
||||
# Use this option to define the port to which to bind the server, defaults to 5000
|
||||
port: 5000
|
||||
|
||||
# Use this option to define an optional baseUrl (with a leading /, so absolute to your
|
||||
# server's root) under which to run OctoPrint. This should only be needed if you want to run
|
||||
# OctoPrint behind a reverse proxy under a different root endpoint than `/` and can't configure
|
||||
# said reverse proxy to send `X-Script-Name` and `X-Scheme` HTTP headers with
|
||||
# forwarded requests (see below). Defaults to an empty string and therefore the server root.
|
||||
baseUrl: /octoprint
|
||||
|
||||
# Use this option to define an optional URL scheme under which to run OctoPrint.
|
||||
# Should only be needed for use with reverse proxies, see above.
|
||||
scheme: http
|
||||
|
||||
# will be automatically set to false once the first-run-wizard has been completed
|
||||
firstRun: true
|
||||
|
||||
.. note::
|
||||
|
||||
If you want to run OctoPrint behind a reverse proxy such as HAProxy or Nginx and use a different base URL than the
|
||||
server root ``/`` you have two options to achieve this. One approach is using the configuration settings ``baseUrl`` and
|
||||
``scheme`` mentioned above in which OctoPrint will only work under the configured base URL.
|
||||
|
||||
The second and better approach is to make your proxy send a couple of custom headers with each forwarded requests:
|
||||
|
||||
* ``X-Script-Name``: should contain your custom baseUrl (absolute server path), e.g. ``/octoprint``
|
||||
* ``X-Scheme``: should contain your custom URL scheme to use (if different from ``http``), e.g. ``https``
|
||||
|
||||
If you use these headers OctoPrint will work both via the reverse proxy as well as when called directly. Take a look
|
||||
`into OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Reverse-proxy-configuration-examples>`_ for a couple
|
||||
of examples on how to configure this.
|
||||
|
||||
Webcam
|
||||
------
|
||||
|
||||
Use the following settings to configure webcam support:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
webcam:
|
||||
# Use this option to enable display of a webcam stream in the UI, e.g. via MJPG-Streamer.
|
||||
# Webcam support will be disabled if not set
|
||||
stream: http://<stream host>:<stream port>/?action=stream
|
||||
|
||||
# Use this option to enable timelapse support via snapshot, e.g. via MJPG-Streamer.
|
||||
# Timelapse support will be disabled if not set
|
||||
snapshot: http://<stream host>:<stream port>/?action=snapshot
|
||||
|
||||
# Path to ffmpeg binary to use for creating timelapse recordings.
|
||||
# Timelapse support will be disabled if not set
|
||||
ffmpeg: /path/to/ffmpeg
|
||||
|
||||
# The bitrate to use for rendering the timelapse video. This gets directly passed to ffmpeg.
|
||||
bitrate: 5000k
|
||||
|
||||
# Whether to include a "created with OctoPrint" watermark in the generated timelapse movies
|
||||
watermark: true
|
||||
|
||||
# The default timelapse settings.
|
||||
timelapse:
|
||||
|
||||
# The timelapse type. Can be either "off", "zchange" or "timed". Defaults to "off"
|
||||
type: timed
|
||||
|
||||
# Additional options depending on the timelapse type. Currently only the "timed" timelapse takes
|
||||
# the interval which to leave between images as option "interval", given in seconds. This example
|
||||
# therefore configures a "Timed" timelapse with an interval of 2s. Defaults to empty.
|
||||
options:
|
||||
interval: 2
|
||||
|
||||
Feature
|
||||
-------
|
||||
|
||||
Use the following settings to enable or disable OctoPrint features:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
feature:
|
||||
# Whether to enable the gcode viewer in the UI or not
|
||||
gCodeVisualizer: true
|
||||
|
||||
# Whether to enable the temperature graph in the UI or not
|
||||
temperatureGraph: true
|
||||
|
||||
# Specifies whether OctoPrint should wait for the start response from the printer before trying to send commands
|
||||
# during connect.
|
||||
waitForStartOnConnect: false
|
||||
|
||||
# Specifies whether OctoPrint should send linenumber + checksum with every command. Needed for
|
||||
# successful communication with Repetier firmware
|
||||
alwaysSendChecksum: false
|
||||
|
||||
# Whether to ignore the first ok after a resend response. Needed for successful communication with
|
||||
# Repetier firmware
|
||||
swallowOkAfterResend: false
|
||||
|
||||
# Specifies whether support for SD printing and file management should be enabled
|
||||
sdSupport: true
|
||||
|
||||
Folder
|
||||
------
|
||||
|
||||
Use the following settings to set custom paths for folders used by OctoPrint:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
folder:
|
||||
# Absolute path where to store gcode uploads. Defaults to the uploads folder in the OctoPrint settings folder
|
||||
uploads: /path/to/upload/folder
|
||||
|
||||
# Absolute path where to store finished timelapse recordings. Defaults to the timelapse folder in the OctoPrint
|
||||
# settings dir
|
||||
timelapse: /path/to/timelapse/folder
|
||||
|
||||
# Absolute path where to store temporary timelapse files. Defaults to the timelapse/tmp folder in the OctoPrint
|
||||
# settings dir
|
||||
timelapse_tmp: /path/to/timelapse/tmp/folder
|
||||
|
||||
# Absolute path where to store log files. Defaults to the logs folder in the OctoPrint settings dir
|
||||
logs: /path/to/logs/folder
|
||||
|
||||
# Absolute path to the virtual printer's simulated SD card. Only useful for development, just ignore
|
||||
# it otherwise
|
||||
virtualSd: /path/to/virtualSd/folder
|
||||
|
||||
# Absolute path to a folder being watched for new files which then get automatically
|
||||
# added to OctoPrint (and deleted from that folder). Can e.g. be used to define a folder which
|
||||
# can then be mounted from remote machines and used as local folder for quickly adding downloaded
|
||||
# and/or sliced objects to print in the future.
|
||||
watched: /path/to/watched/folder
|
||||
|
||||
Temperature
|
||||
-----------
|
||||
|
||||
Use the following settings to configure temperature profiles which will be displayed in the temperature tab:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
temperature:
|
||||
profiles:
|
||||
- name: ABS
|
||||
extruder: 210
|
||||
bed: 100
|
||||
- name: PLA
|
||||
extruder: 180
|
||||
bed: 60
|
||||
|
||||
Appearance
|
||||
----------
|
||||
|
||||
Use the following settings to tweak OctoPrint's appearance a bit to better distinguish multiple instances/printers
|
||||
appearance:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
appearance:
|
||||
# Use this to give your printer a name. It will be displayed in the title bar (as "<Name> [OctoPrint]") and in the
|
||||
# navigation bar (as "OctoPrint: <Name>")
|
||||
name: My Printer Model
|
||||
|
||||
# Use this to color the navigation bar. Supported colors are red, orange, yellow, green, blue, violet and default.
|
||||
color: blue
|
||||
|
||||
Controls
|
||||
--------
|
||||
|
||||
Use the ``controls`` section to add :ref:`custom controls <sec-features-custom_controls>` to the "Controls" tab within
|
||||
OctoPrint.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
controls:
|
||||
- name: Fan
|
||||
layout: horizontal
|
||||
children:
|
||||
- name: Enable Fan
|
||||
type: parametric_command
|
||||
command: M106 S%(speed)s
|
||||
input:
|
||||
- name: Speed (0-255)
|
||||
parameter: speed
|
||||
default: 255
|
||||
- name: Disable Fan
|
||||
type: command
|
||||
command: M107
|
||||
|
||||
System
|
||||
------
|
||||
|
||||
Use the following settings to add custom system commands to the "System" dropdown within OctoPrint's top bar.
|
||||
|
||||
Commands consist of a name, an action identifier, the commandline to execute and an optional confirmation message to
|
||||
display before actually executing the command (should be set to False if a confirmation dialog is not desired).
|
||||
|
||||
The following example defines a command for shutting down the system under Linux. It assumes that the user under which
|
||||
OctoPrint is running is allowed to do this without password entry:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
system:
|
||||
actions:
|
||||
- name: Shutdown
|
||||
action: shutdown
|
||||
command: sudo shutdown -h now
|
||||
confirm: You are about to shutdown the system.
|
||||
|
||||
Access Control
|
||||
--------------
|
||||
|
||||
Use the following settings to enable access control:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
accessControl:
|
||||
# whether to enable access control or not. Defaults to true
|
||||
enabled: true
|
||||
|
||||
# The user manager implementation to use for accessing user information. Currently only a filebased
|
||||
# user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml
|
||||
# in the default configuration folder, see below)
|
||||
userManager: octoprint.users.FilebasedUserManager
|
||||
|
||||
# The YAML user file to use. If left out defaults to users.yaml in the default configuration folder.
|
||||
userFile: /path/to/users.yaml
|
||||
|
||||
# If set to true, will automatically log on clients originating from any of the networks defined in
|
||||
# "localNetworks" as the user defined in "autologinAs". Defaults to false.
|
||||
autologinLocal: true
|
||||
|
||||
# The name of the user to automatically log on clients originating from "localNetworks" as. Must
|
||||
# be the name of one of your configured users.
|
||||
autologinAs: someUser
|
||||
|
||||
# A list of networks or IPs for which an automatic logon as the user defined in "autologinAs" will
|
||||
# take place. If available OctoPrint will evaluate the "X-Forwarded-For" HTTP header for determining
|
||||
# the client's IP address (see https://code.google.com/p/haproxy-docs/wiki/forwardfor on how to
|
||||
# configure the sending of this header in HAProxy). Defaults to 127.0.0.0/8 (so basically anything
|
||||
# originating from localhost).
|
||||
localNetworks:
|
||||
- 127.0.0.0/8
|
||||
- 192.168.1.0/24
|
||||
|
||||
Events
|
||||
------
|
||||
|
||||
Use the following settings to add shell/gcode commands to be executed on certain :ref:`events <sec-events>`:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
events:
|
||||
subscriptions:
|
||||
# example event consumer that prints a message to the system log if the printer is disconnected
|
||||
- event: Disconnected
|
||||
command: "logger 'Printer got disconnected'"
|
||||
type: system
|
||||
|
||||
# example event consumer that queries printer information from the firmware, prints a "Connected"
|
||||
# message to the LCD and homes the print head upon established printer connection, disabled though
|
||||
- event: Connected
|
||||
command: M115,M117 printer connected!,G28
|
||||
type: gcode
|
||||
enabled: False
|
||||
|
||||
Terminal Filters
|
||||
----------------
|
||||
|
||||
Use the following settings to define a set of terminal filters to display in the terminal tab for filtering certain
|
||||
lines from the display terminal log.
|
||||
|
||||
Use `Javascript regular expressions <https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions>`_:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
# A list of filters to display in the terminal tab. Defaults to the filters shown below
|
||||
terminalFilters:
|
||||
- name: Suppress M105 requests/responses
|
||||
regex: '(Send: M105)|(Recv: ok T:)'
|
||||
- name: Suppress M27 requests/responses
|
||||
regex: '(Send: M27)|(Recv: SD printing byte)'
|
||||
|
||||
API
|
||||
---
|
||||
|
||||
Settings for the REST API:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
api:
|
||||
# whether to enable the API
|
||||
enabled: True
|
||||
|
||||
# current API key needed for accessing the API
|
||||
apikey: ...
|
||||
|
||||
Development settings
|
||||
--------------------
|
||||
|
||||
The following settings are only relevant to you if you want to do OctoPrint development:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
# Settings only relevant for development
|
||||
devel:
|
||||
|
||||
# Settings for the virtual printer
|
||||
virtualPrinter:
|
||||
|
||||
# Whether to enable the virtual printer and include it in the list of available serial connections.
|
||||
# Defaults to false.
|
||||
enabled: true
|
||||
|
||||
# Whether to send an additional "ok" after a resend request (like Repetier)
|
||||
okAfterResend: false
|
||||
|
||||
# Whether to force checksums and line number in the communication (like Repetier), if set to true
|
||||
# printer will only accept commands that come with linenumber and checksum and throw an error for
|
||||
# lines that don't. Defaults to false
|
||||
forceChecksum: false
|
||||
|
||||
# Whether to send "ok" responses with the line number that gets acknowledged by the "ok". Defaults
|
||||
# to false.
|
||||
okWithLinenumber: false
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
.. _sec-configuration:
|
||||
|
||||
#############
|
||||
Configuration
|
||||
#############
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
yaml.rst
|
||||
config_yaml.rst
|
||||
logging_yaml.rst
|
||||
@@ -0,0 +1,100 @@
|
||||
.. _sec-configuration-logging_yaml:
|
||||
|
||||
logging.yaml
|
||||
============
|
||||
|
||||
The logging configuration file ``logging.yaml`` for OctoPrint is expected in its settings folder, which unless defined
|
||||
differently on the command line is located at ``~/.octoprint`` on Linux, at ``%APPDATA%/OctoPrint`` on Windows and at
|
||||
``~/Library/Application Support/OctoPrint`` on MacOS.
|
||||
|
||||
You can use it to change the log levels of the individual components within OctoPrint, which might be necessary to help
|
||||
in debugging issues you are experiencing, or to change the configuration of the logging handlers themselves, e.g. in
|
||||
order to change size after which to rollover the ``serial.log``.
|
||||
|
||||
Changing log levels
|
||||
-------------------
|
||||
|
||||
If you need to change the default logging level within OctoPrint, create the file with a text editor of your choice
|
||||
(it's usually not there). The general format is this::
|
||||
|
||||
logger:
|
||||
<component>:
|
||||
level: <loglevel>
|
||||
|
||||
with ``<component>`` being the internal OctoPrint component for which to change the loglevel, and ``<loglevel>`` being the
|
||||
new log level to set. An example for increasing the log level of the events and the file management components to
|
||||
``DEBUG`` (the highest amount of logging) would be this ``logging.yaml``:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
logger:
|
||||
octoprint.events:
|
||||
level: DEBUG
|
||||
octoprint.filemanager:
|
||||
level: DEBUG
|
||||
|
||||
A list of important components for which an increase in logging might be interesting follows:
|
||||
|
||||
* ``octoprint.events``: the event sub system
|
||||
* ``octoprint.filemanager``: the file management layer
|
||||
* ``octoprint.plugin``: the plugin sub system
|
||||
* ``octoprint.plugins.<plugin>``: the plugin ``<plugin>``, e.g. ``octoprint.plugins.discovery`` to change the log level of
|
||||
the `Discovery plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_ or ``octoprint.plugins.cura``
|
||||
to change the log level of the `Cura plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_.
|
||||
* ``octoprint.slicing``: the slicing sub system
|
||||
|
||||
This list will be expanded when deemed necessary.
|
||||
|
||||
Changing logging handlers
|
||||
-------------------------
|
||||
|
||||
You can also change the configuration of the logging handlers themselves, e.g. in order to make the ``serial.log`` larger
|
||||
for debugging long running communications or to change the behaviour of the ``octoprint.log``.
|
||||
|
||||
You can find the default configurations of the ``file`` handler used for the ``octoprint.log``, the ``serialFile`` handler
|
||||
used for the ``serial.log`` and the ``console`` handler used for the output to stdout in YAML format below:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
handlers:
|
||||
# stdout
|
||||
console:
|
||||
class: logging.StreamHandler
|
||||
level: DEBUG
|
||||
formatter: simple
|
||||
stream: ext://sys.stdout
|
||||
|
||||
# octoprint.log
|
||||
file:
|
||||
class: logging.handlers.TimedRotatingFileHandler
|
||||
level: DEBUG
|
||||
formatter: simple
|
||||
when: D
|
||||
backupCount: 1
|
||||
filename: /path/to/octoprints/logs/octoprint.log
|
||||
|
||||
# serial.log
|
||||
serialFile:
|
||||
class: logging.handlers.RotatingFileHandler
|
||||
level: DEBUG
|
||||
formatter: simple
|
||||
maxBytes: 2097152 # 2 * 1024 * 1024 = 2 MB in bytes
|
||||
filename: /path/to/octoprints/logs/serial.log
|
||||
|
||||
You can find more information on the used logging handlers in the
|
||||
`Python documentation on logging handlers <https://docs.python.org/2/library/logging.handlers.html>`_.
|
||||
|
||||
Changing logging formatters
|
||||
---------------------------
|
||||
|
||||
The logging formatters can be defined via ``logging.yaml`` as well. The ``simple`` formatter as referenced above is
|
||||
expressed in YAML as follows:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
formatters:
|
||||
simple:
|
||||
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
|
||||
The possible keys for the logging format can be found in the
|
||||
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
|
||||
@@ -0,0 +1,224 @@
|
||||
.. _sec-configuration-yaml:
|
||||
|
||||
A YAML Primer
|
||||
=============
|
||||
|
||||
Most of OctoPrint's configuration is done under the hood through `YAML <https://en.wikipedia.org/wiki/YAML>`_ files,
|
||||
which is why it makes sense to shed some light on the basics of this data serialization format.
|
||||
|
||||
YAML is a text based format which excels at representing the most common of data structures in an easy and very human
|
||||
readable way, which is why it was chosen for OctoPrint's configuration files. A text editor is all you need in order
|
||||
to write YAML configuration files.
|
||||
|
||||
.. _sec-configuration-yaml-basic:
|
||||
|
||||
Basic Rules
|
||||
-----------
|
||||
|
||||
First of all some basic things to know about working with YAML files:
|
||||
|
||||
* Never use tabs outside of quoted strings, especially not for indentation. The tab character is illegal within
|
||||
YAML files.
|
||||
* Whitespace and indentation matters and plays an important part in structuring the data, so take special care
|
||||
to stay consistent here.
|
||||
* YAML's comments start with a ``#`` and go until the end of the line.
|
||||
|
||||
.. _sec-configuration-yaml-types:
|
||||
|
||||
Interesting data types
|
||||
----------------------
|
||||
|
||||
You will probably only come across the three most basic types of data within OctoPrint's YAML files: scalars
|
||||
(such as strings, integers, ...), lists and associated arrays (aka key-value-pairs, aka maps, aka dictionaries).
|
||||
|
||||
.. _sec-configuration-yaml-types-scalar:
|
||||
|
||||
Scalars
|
||||
.......
|
||||
|
||||
Scalars are the most basic of all data types and are simple string, integer, float or boolean values.
|
||||
|
||||
For most scalars you don't need any quotes at all, but if you need to define some piece of data which contains characters
|
||||
that could be mistaken with YAML syntax you need to quote it in either double ``"`` or single ``'`` quotes for the
|
||||
YAML file to stay valid. As simple rule of thumb, if your data contains any of these characters ``:-{}[]!#|>&%@`` better
|
||||
quote it. Also quote it if you want a string but it could be mistaken for a valid number (integer or float) or if
|
||||
it consists only of "Yes", "No", "yes", "no", "true" or "false", which would be converted to a boolean without quotes.
|
||||
|
||||
In double quoted strings if you need to include a literal double quote in your string you can escape it by prefixing
|
||||
it with a backslash ``\`` (which you can in turn escape by itself). In single quoted strings the single quote character
|
||||
can be escaped by prefixing it with another single quote, basically doubling it. Backslashes in single quoted strings
|
||||
do not need to be escaped.
|
||||
|
||||
Quoted strings can also span across multiple lines, just indent the following lines. Note that you'll need to add a
|
||||
completely empty line in order for force a line break, the data will not be actually wrapped across multiple lines
|
||||
just because you spread its representation across multiple lines.
|
||||
|
||||
.. _sec-configuration-yaml-types-scalar-int:
|
||||
|
||||
int
|
||||
'''
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
23
|
||||
|
||||
42
|
||||
|
||||
.. _sec-configuration-yaml-types-scalar-float:
|
||||
|
||||
float
|
||||
'''''
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
23.5
|
||||
|
||||
100.0
|
||||
|
||||
.. _sec-configuration-yaml-types-scalar-boolean:
|
||||
|
||||
boolean
|
||||
'''''''
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
true
|
||||
|
||||
false
|
||||
|
||||
Yes
|
||||
|
||||
No
|
||||
|
||||
yes
|
||||
|
||||
no
|
||||
|
||||
.. _sec-configuration-yaml-types-scalar-string:
|
||||
|
||||
string
|
||||
''''''
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
a string
|
||||
|
||||
"some quoted string with a : colon and a { bracket and a quote \" and a backslash \\ - phew"
|
||||
|
||||
'some single quoted string with a single quote '' and a backslash \ - yay'
|
||||
|
||||
"and a multiline string - just because we can we'll make it span
|
||||
across not two but four YAML lines!
|
||||
|
||||
Including this paragraph. But in fact it will only be two lines :)"
|
||||
|
||||
"23"
|
||||
|
||||
"42.3"
|
||||
|
||||
"Yes"
|
||||
|
||||
"No"
|
||||
|
||||
"true"
|
||||
|
||||
"false"
|
||||
|
||||
yes and no
|
||||
|
||||
true or false
|
||||
|
||||
.. _sec-configuration-yaml-types-lists:
|
||||
|
||||
Lists
|
||||
.....
|
||||
|
||||
Lists allow to "collect" a number of similar things into one data structure. They are created by prefixing one or more
|
||||
consecutive lines with a ``-``:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
- item 1
|
||||
- 23.42
|
||||
- 57
|
||||
- true
|
||||
|
||||
Take special care to have all of your list items at the same indentation level!
|
||||
|
||||
.. _sec-configuration-yaml-types-dicts:
|
||||
|
||||
Dictionaries
|
||||
............
|
||||
|
||||
Dictionaries (aka associative arrays aka maps) allow organizing the data in key value pairs, with the key and the value
|
||||
being separated through a colon ``:``:
|
||||
|
||||
.. sourcecode:: yaml
|
||||
|
||||
key: value
|
||||
anotherkey: another value
|
||||
|
||||
.. _sec-configuration-yaml-examples:
|
||||
|
||||
Examples
|
||||
--------
|
||||
|
||||
Based on the three types explained above, quite complex data structures are possible (whitespace made visible to
|
||||
help track indentation):
|
||||
|
||||
.. code-block-ext:: yaml
|
||||
:whitespace:
|
||||
|
||||
general:
|
||||
some_setting: some_value
|
||||
a_list:
|
||||
- item 1
|
||||
- 23.42
|
||||
- 57
|
||||
- true
|
||||
some_flag: true
|
||||
quoted_string: "This string is quoted because {we have this here} and also > this and : that"
|
||||
specific:
|
||||
setting1: value1
|
||||
setting2:
|
||||
subsetting21: value11
|
||||
subsetting22:
|
||||
- subsubsetting221
|
||||
- subsubsetting222
|
||||
- subsubsetting223
|
||||
the_end: yes
|
||||
|
||||
In this example we have a dictionary on the top most "layer" which has three keys, ``general``, ``specific`` and
|
||||
``the_end``.
|
||||
|
||||
``general`` in turn is a dictionary with the keys ``some_setting`` (a string), ``a_list`` (a list with four items,
|
||||
a string, a float, an int and a boolean), ``some_flag`` (a boolean) and ``quoted_string`` (a -- you guessed it -- string).
|
||||
|
||||
``specific`` is also a dictionary, with keys ``setting1`` (a string) and ``setting2``, a dictionary with two keys, one
|
||||
a string and the other again a list.
|
||||
|
||||
Finally, ``the_end`` is just a boolean, since an unquoted ``yes`` evaluates as a boolean value as we saw in the
|
||||
:ref:`section about boolean scalars above <sec-configuration-yaml-types-scalar-boolean>`.
|
||||
|
||||
Don't get confused by the list "dividing" one part of the dictionary under ``general`` from the other -- your mind is
|
||||
just playing a trick on you due to the list's dashes ``-`` being on the same levels as the dictionary keys. You could
|
||||
also just add two more spaces to your identation and write that part like this, which makes the structure a bit
|
||||
clearer (whitespace again made visible to help track indentation):
|
||||
|
||||
.. code-block-ext:: yaml
|
||||
:whitespace:
|
||||
|
||||
general:
|
||||
some_setting: some_value
|
||||
a_list:
|
||||
- item 1
|
||||
- 23.42
|
||||
- 57
|
||||
- true
|
||||
some_flag: true
|
||||
# ...
|
||||
|
||||
Just make sure you follow a consistent way of indenting your files -- YAML is not as strict as Python when it comes to
|
||||
differing identation variants within the same file (as long as it's still valid), but consistency will help you as
|
||||
a lot as a human. Ideally you'll use a text editor which highlights white space characters for you (most editors can
|
||||
be configured this way), this will help tremendously when editing whitespace sensitive syntax such as YAML.
|
||||
@@ -0,0 +1,10 @@
|
||||
.. _sec-development:
|
||||
|
||||
###########
|
||||
Development
|
||||
###########
|
||||
|
||||
.. todo::
|
||||
|
||||
This is where notes regarding developing OctoPrint will be placed, such as workflow for setting up the
|
||||
development environment, code guidelines etc.
|
||||
@@ -1,16 +1,19 @@
|
||||
.. _sec-events:
|
||||
|
||||
####################
|
||||
Events Documentation
|
||||
####################
|
||||
######
|
||||
Events
|
||||
######
|
||||
|
||||
.. 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.
|
||||
|
||||
.. note::
|
||||
|
||||
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:
|
||||
|
||||
@@ -56,7 +59,7 @@ Example
|
||||
Placeholders
|
||||
============
|
||||
|
||||
You can use the following generic placeholders in your events:
|
||||
You can use the following generic placeholders in your event hooks:
|
||||
|
||||
* ``{__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
|
||||
@@ -96,6 +99,10 @@ ClientOpened
|
||||
ClientClosed
|
||||
A client has disconnected from the webserver
|
||||
|
||||
Payload:
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that disconnected
|
||||
|
||||
Printer communication
|
||||
---------------------
|
||||
|
||||
@@ -132,7 +139,14 @@ UpdatedFiles
|
||||
|
||||
Payload:
|
||||
|
||||
* ``type``: the type of file list that was modified, currently only ``gcode`` is supported here
|
||||
* ``type``: the type of file list that was modified. Currently only ``printables`` and ``gcode`` (DEPRECATED) are supported here.
|
||||
|
||||
.. note::
|
||||
|
||||
The type ``gcode`` has been renamed to ``printables`` with the introduction of a new file management layer that
|
||||
supports STL files as first class citizens as well. For reasons of backwards compatibility the ``UpdatedFiles``
|
||||
event for printable files will be fired twice, once with ``type`` set to ``gcode``, once set to ``printables``.
|
||||
Support for the ``gcode`` type will be removed in the next release after version 1.2.0.
|
||||
|
||||
MetadataAnalysisStarted
|
||||
The metadata analysis of a GCODE file has started.
|
||||
@@ -321,6 +335,7 @@ SlicingStarted
|
||||
|
||||
* ``stl``: the STL's filename
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
* ``progressAvailable``: true if progress information via the ``slicingProgress`` push update will be available, false if not
|
||||
|
||||
SlicingDone
|
||||
The slicing of a file has completed.
|
||||
@@ -331,6 +346,15 @@ SlicingDone
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
* ``time``: the time needed for slicing, in seconds (float)
|
||||
|
||||
SlicingCancelled
|
||||
The slicing of a file has been cancelled. This will happen if a second slicing job
|
||||
targeting the same GCODE file has been started by the user.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``stl``: the STL's filename
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
|
||||
SlicingFailed
|
||||
The slicing of a file has failed.
|
||||
|
||||
@@ -339,3 +363,9 @@ SlicingFailed
|
||||
* ``stl``: the STL's filename
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
* ``reason``: the reason for the slicing having failed
|
||||
|
||||
Settings
|
||||
--------
|
||||
|
||||
SettingsUpdated
|
||||
The internal settings were updated.
|
||||
@@ -0,0 +1,277 @@
|
||||
.. _sec-features-custom_controls:
|
||||
|
||||
Custom Controls
|
||||
===============
|
||||
|
||||
.. contents::
|
||||
|
||||
OctoPrint allows you to add custom controls to the "Control" tab of its interface. Control types reach from simple
|
||||
buttons which trigger sending of one or more lines of GCODE to the printer over more complex controls allowing
|
||||
parameterization of these commands with values entered by the user to full blown GCODE script templates backed by
|
||||
`Jinja2 <http://jinja.pocoo.org/>`_.
|
||||
|
||||
Custom controls are configured within :ref:`config.yaml <sec-configuration-config_yaml>` in a ``controls`` section which
|
||||
basically represents a hierarchical structure of all configured custom controls of various types.
|
||||
|
||||
.. note::
|
||||
|
||||
To make sure that your ``config.yaml`` stays valid when adding custom controls, don't hesitate to take a look at the
|
||||
:ref:`YAML Primer <sec-configuration-yaml>`.
|
||||
|
||||
The following example defines a control for enabling the cooling fan with a variable speed defined by the user
|
||||
(default 255 and selectable through a slider UI element) and a control for disabling the fan, all within a section named
|
||||
"Fan", two example controls with multiple commands in a section "Example for multiple commands", a command with printer
|
||||
feedback evaluation for the result of the M114 "Get Position" gcode inside a section named "Reporting" and finally
|
||||
a GCODE script including user input.
|
||||
|
||||
.. code-block-ext:: yaml
|
||||
|
||||
controls:
|
||||
- name: Fan
|
||||
layout: horizontal
|
||||
children:
|
||||
- name: Enable Fan
|
||||
command: M106 S%(speed)s
|
||||
input:
|
||||
- name: Speed (0-255)
|
||||
parameter: speed
|
||||
default: 255
|
||||
slider:
|
||||
min: 0
|
||||
max: 255
|
||||
- name: Disable Fan
|
||||
command: M107
|
||||
- name: Example for multiple commands
|
||||
children:
|
||||
- name: Move X (static)
|
||||
confirm: You are about to move the X axis right by 10mm with 3000mm/s.
|
||||
commands:
|
||||
- G91
|
||||
- G1 X10 F3000
|
||||
- G90
|
||||
- name: Move X (parametric)
|
||||
commands:
|
||||
- G91
|
||||
- G1 X%(distance)s F%(speed)s
|
||||
- G90
|
||||
input:
|
||||
- default: 10
|
||||
name: Distance
|
||||
parameter: distance
|
||||
- default: 3000
|
||||
name: Speed
|
||||
parameter: speed
|
||||
- name: Reporting
|
||||
children:
|
||||
- name: Get Position
|
||||
command: M114
|
||||
regex: "X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)"
|
||||
template: "Position: X={0}, Y={1}, Z={2}, E={3}"
|
||||
- name: Fun stuff
|
||||
children:
|
||||
- name: Dance
|
||||
script: custom/dance.gco
|
||||
input:
|
||||
- name: Go arounds
|
||||
parameter: repetitions
|
||||
slider:
|
||||
max: 10
|
||||
min: 1
|
||||
step: 1
|
||||
|
||||
Adding this to ``config.yaml``, restarting the OctoPrint server and switching to the "Control" tab within its
|
||||
interface yields the following visual representation:
|
||||
|
||||
.. _fig-configuration-custom_controls-example:
|
||||
.. figure:: ../images/features-custom_controls-example.png
|
||||
:align: center
|
||||
:alt: The rendered output created through the example configuration
|
||||
|
||||
As you can see you have two basic types of control definitions here: controls that actually do something (providing a
|
||||
button that sends one or more commands to the printer when clicked, displaying output received from the printer) and
|
||||
controls that just serve as *container* for other controls, the latter being identified by having a ``children``
|
||||
attribute wrapping more controls.
|
||||
|
||||
.. _sec-features-custom_controls-types:
|
||||
|
||||
Types
|
||||
-----
|
||||
|
||||
Let's take a closer look at the possible attributes that are available for both basic types.
|
||||
|
||||
.. _sec-features-custom_controls-types-containers:
|
||||
|
||||
Containers
|
||||
..........
|
||||
|
||||
.. list-table::
|
||||
:widths: 25 75
|
||||
|
||||
* - **Attribute**
|
||||
- **Description**
|
||||
* - ``children``
|
||||
- A list of children controls or containers contained within this container
|
||||
* - ``name``
|
||||
- (Optional) A name to display above the container, basically a section header
|
||||
* - ``layout``
|
||||
- (Optional) The layout to use for laying out the contained children, either from top to bottom (``vertical``) or
|
||||
from left to right (``horizontal``). Defaults to a ``vertical`` layout.
|
||||
|
||||
.. _sec-features-custom_controls-types-controls:
|
||||
|
||||
Controls
|
||||
........
|
||||
|
||||
.. list-table::
|
||||
:widths: 25 75
|
||||
|
||||
* - **Attribute**
|
||||
- **Description**
|
||||
* - ``name``
|
||||
- The name of the control, will be displayed either on the button if it's a control sending a command or as a label
|
||||
for controls which only display output.
|
||||
* - ``command``
|
||||
- (Optional) A single GCODE command to send to the printer. Will be rendered as a button which sends the command to
|
||||
the printer upon click. The button text will be the value of the ``name`` attribute. Mutually exclusive with
|
||||
``commands`` and ``script``. The rendered button be disabled if the printer is currently offline or printing or
|
||||
alternatively if the requirements defined via the ``enabled`` attribute are not met.
|
||||
* - ``commands``
|
||||
- (Optional) A list of GCODE commands to send to the printer. Will be rendered as a button which sends the commands
|
||||
to the printer upon click. The button text will be the value of the ``name`` attribute. Mutually exclusive with
|
||||
``command`` and ``script``. The rendered button will be disabled if the printer is currently offline or printing
|
||||
or alternatively if the requirements defined via the ``enabled`` attribute are not met.
|
||||
* - ``script``
|
||||
- (Optional) The name of a full blown :ref:`GCODE script <sec-features-gcode_scripts>` to send to the printer.
|
||||
Will be rendered as a button which sends the script to the printer upon click. The button text will be the value
|
||||
of the ``name`` attribute. Mutually exclusive with ``command`` and ``commands``. The rendered button will be
|
||||
disabled if the printer is currently offline or printing or alternatively if the requirements defined via the
|
||||
``enabled`` attribute are not met.
|
||||
|
||||
Values of input parameters will be available in the template context under the ``parameter`` variable (e.g.
|
||||
an input parameter ``speed`` will be available in the script template as ``parameter.speed``). On top of that all
|
||||
other variables defined in the :ref:`GCODE template context <sec-features-gcode_scripts-context>` will be available.
|
||||
|
||||
:ref:`See below for an example <sec-features-custom_controls-examples-gcode_script>`.
|
||||
* - ``javascript``
|
||||
- (Optional) A JavaScript snippet to be executed when the button rendered for ``command`` or ``commands`` is
|
||||
clicked. This allows to override the direct sending of the command or commands to the printer with more
|
||||
sophisticated behaviour. The JavaScript snippet is ``eval``'d and processed in a context where the control
|
||||
it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``.
|
||||
* - ``enabled``
|
||||
- (Optional) A JavaScript snippet returning either ``true`` or ``false`` determining whether the control
|
||||
should be enabled or not. This allow to override the default logic for this (disabled if printer is offline
|
||||
or currently printing). The JavaScript snippet is ``eval``'d and processed in a context where the control
|
||||
it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``.
|
||||
* - ``input``
|
||||
- (Optional) A list of definitions of input parameters for a ``command`` or ``commands``, to be rendered as
|
||||
additional input fields. ``command``/``commands`` may contain placeholders to be replaced by the values obtained
|
||||
from the user for the defined input fields:
|
||||
|
||||
.. code-block-ext:: yaml
|
||||
|
||||
name: Enable Fan
|
||||
command: M106 S%(speed)s
|
||||
input:
|
||||
- name: Speed (0-255)
|
||||
parameter: speed
|
||||
default: 255
|
||||
slider:
|
||||
min: 0
|
||||
max: 255
|
||||
|
||||
In OctoPrint's default UI input fields are always rendered left to right (inline).
|
||||
* - ``input.name``
|
||||
- Name to display for the input field.
|
||||
* - ``input.parameter``
|
||||
- Internal parameter name for the input field, used as a placeholder in ``command``/``commands``.
|
||||
* - ``input.default``
|
||||
- Default value for the input field.
|
||||
* - ``input.slider``
|
||||
- (Optional) If this attribute is included, instead of an input field a slider control will
|
||||
be rendered. If you don't want to define any of ``min``, ``max`` or ``step``, write ``slider: {}`` to render
|
||||
a slider based on default values.
|
||||
* - ``input.slider.min``
|
||||
- (Optional) Minimum value of the slider, defaults to 0.
|
||||
* - ``input.slider.max``
|
||||
- (Optional) Maximum value of the slider, defaults to 255.
|
||||
* - ``input.slider.step``
|
||||
- (Optional) Step size per slider "tick", defaults to 1.
|
||||
* - ``regex``
|
||||
- (Optional) A `regular expression <https://docs.python.org/2/library/re.html#regular-expression-syntax>`_ to
|
||||
match against lines received from the printer to retrieve information from it (e.g. specific output). Together
|
||||
with ``template`` this allows rendition of received data from the printer within the UI.
|
||||
* - ``template``
|
||||
- (Optional) A template to use for rendering the match of ``regex``. May contain placeholders in
|
||||
`Python Format String Syntax <https://docs.python.org/2/library/string.html#format-string-syntax>`_ for either named
|
||||
groups within the regex (e.g. ``Temperature: {temperature}`` for a regex ``T:\s*(?P<temperature>\d+(\.\d*)``)
|
||||
or positional groups within the regex (e.g. ``Position: X={0}, Y={1}, Z={2}, E={3}`` for a regex
|
||||
``X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)``).
|
||||
* - ``confirm``
|
||||
- (Optional) A text to display to the user to confirm his button press. Can be used with sensitive custom controls
|
||||
like changing EEPROM values in order to prevent accidental clicks. The text will be displayed in a confirmation
|
||||
dialog like the following:
|
||||
|
||||
.. _fig-configuration-custom_controls-confirm:
|
||||
.. figure:: ../images/features-custom_controls-confirm.png
|
||||
:align: center
|
||||
:alt: An example confirmation dialog
|
||||
|
||||
.. _sec-features-custom_controls-examples:
|
||||
|
||||
Examples
|
||||
--------
|
||||
|
||||
.. _sec-features-custom_controls-examples-gcode_script:
|
||||
|
||||
Parameterized GCODE Script
|
||||
..........................
|
||||
|
||||
.. code-block-ext:: yaml
|
||||
:caption: Control definition in ~/.octoprint/config.yaml
|
||||
:name: code-features-custom_controls-example-gcode_script-config_yaml
|
||||
|
||||
name: Dance
|
||||
script: custom/dance.gco
|
||||
input:
|
||||
- default: 5
|
||||
name: Go arounds
|
||||
parameter: repetitions
|
||||
slider:
|
||||
max: 10
|
||||
min: 1
|
||||
step: 1
|
||||
|
||||
.. code-block-ext:: jinja
|
||||
:caption: ~/.octoprint/scripts/gcode/custom/dance.gco
|
||||
:name: code-features-custom_controls-example-gcode_script-dance_gco
|
||||
|
||||
{% set center_x = printer_profile.volume.width / 2 %}
|
||||
{% set center_y = printer_profile.volume.depth / 2 %}
|
||||
{% set speed_x = printer_profile.axes.x.speed %}
|
||||
{% set speed_y = printer_profile.axes.y.speed %}
|
||||
{% set speed_z = printer_profile.axes.z.speed %}
|
||||
M117 run {{ script.name }}
|
||||
G4 P500
|
||||
G1 Z10
|
||||
G1 X{{ center_x }} Y{{ center_y }} F{{ speed_x }}
|
||||
M117 let's dance!
|
||||
G91
|
||||
G1 X-1 Y-1 F{{ speed_x }}
|
||||
{% for n in range(parameters.repetitions) %}
|
||||
M117 and {{ n + 1 }}
|
||||
{% if n % 2 == 0 %}
|
||||
G1 Z1 F{{ speed_z }}
|
||||
G1 Z-2 F{{ speed_z }}
|
||||
G1 Z1 F{{ speed_z }}
|
||||
{% endif %}
|
||||
G1 X2 F{{ speed_x }}
|
||||
G1 Y2 F{{ speed_y }}
|
||||
G1 X-2 F{{ speed_x }}
|
||||
G1 Y-2 F{{ speed_y }}
|
||||
{% endfor %}
|
||||
G90
|
||||
G1 X{{ center_x }} Y{{ center_y }} F{{ speed_x }}
|
||||
G28 X0 Y0
|
||||
|
||||
Note the usage of the ``parameters.repetitions`` template variable in the GCODE script template, which will contain
|
||||
the value selected by the user for the "Go arounds" slider.
|
||||
@@ -0,0 +1,18 @@
|
||||
.. _sec-features-gcode_scripts:
|
||||
|
||||
GCODE Scripts
|
||||
=============
|
||||
|
||||
.. todo::
|
||||
|
||||
Needs to be written
|
||||
|
||||
.. _sec-features-gcode_scripts-context:
|
||||
|
||||
Context
|
||||
-------
|
||||
|
||||
.. _sec-features-gcode_scripts-bundled:
|
||||
|
||||
Bundled Scripts
|
||||
---------------
|
||||
@@ -0,0 +1,11 @@
|
||||
.. _section-features:
|
||||
|
||||
********
|
||||
Features
|
||||
********
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
custom_controls.rst
|
||||
gcode_scripts.rst
|
||||
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 47 KiB |
@@ -0,0 +1,309 @@
|
||||
<?xml version="1.0"?>
|
||||
<Document xmlns="http://www.evolus.vn/Namespace/Pencil"><Properties/><Pages><Page><Properties><Property name="name">sidebar</Property><Property name="id">1421408377849_1407</Property><Property name="width">1531</Property><Property name="height">847</Property><Property name="dimBackground"/><Property name="transparentBackground">true</Property><Property name="backgroundColor">#FFFFFFFF</Property><Property name="background">transparent</Property></Properties><Content><g xmlns="http://www.w3.org/2000/svg" p:type="Group" xmlns:p="http://www.evolus.vn/Namespace/Pencil" transform="translate(200,211.5)" id="9c37daabc3ba46d8a8d9392db9c5bfec" p:sizing-gow="533.5" p:sizing-goh="366.5"><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="db0858b72c864467b215dbf33d56f344" transform="matrix(1,0,0,1,57,-0.5)" p:sizing-ox="58" p:sizing-oy="0.5" p:sizing-ow="264" p:sizing-oh="368"><p:metadata><p:property name="box"><![CDATA[264,368]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,46]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="262" height="366" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="6a0c5dd8bb904291948a061be156b69a" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="47e2c5b978d04acdae01fb06a59a4447">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#6a0c5dd8bb904291948a061be156b69a" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#47e2c5b978d04acdae01fb06a59a4447)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="1bb1baaca7cc44c1b02cd9b42c705cc4"/>
|
||||
<use xlink:href="#6a0c5dd8bb904291948a061be156b69a" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="46" y="184" width="172" height="0" p:name="text" id="85bd2e4e256b4cb7842522f2f03f3c81" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="76483818cd584af4995434fb28810ce8" transform="matrix(1,0,0,1,73,15.5)" p:sizing-ox="74" p:sizing-oy="16.5" p:sizing-ow="232" p:sizing-oh="112"><p:metadata><p:property name="box"><![CDATA[232,112]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,14]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="230" height="110" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="3013ddbcc4fa492995a68798edd29384" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="d1e4f71d5d584c4791ec9a7c9e5be830">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#3013ddbcc4fa492995a68798edd29384" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#d1e4f71d5d584c4791ec9a7c9e5be830)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="99bedd6f63d44a4a98c846ef4bec10a1"/>
|
||||
<use xlink:href="#3013ddbcc4fa492995a68798edd29384" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="14" y="56" width="204" height="0" p:name="text" id="628f108cd2324e66b43059a0f6820ee6" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="cab18e5323344976a22116d09ed7f8d9" transform="matrix(1,0,0,1,73,143.5)" p:sizing-ox="74" p:sizing-oy="144.5" p:sizing-ow="232" p:sizing-oh="208"><p:metadata><p:property name="box"><![CDATA[232,208]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,25.999999999999993]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="230" height="206" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="81f28baf72ac469cbdebdcaeb5aeb243" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="d7c2713036ee43909c0c1edc167e270b">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#81f28baf72ac469cbdebdcaeb5aeb243" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#d7c2713036ee43909c0c1edc167e270b)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="825e8e4a336247cba2f89994b72de93e"/>
|
||||
<use xlink:href="#81f28baf72ac469cbdebdcaeb5aeb243" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="26" y="104" width="180" height="0" p:name="text" id="5da32f0eb5b64ebc8ed60f5ad52e1693" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="5bb69b63f17c4b90bab26e055b40809d" transform="matrix(1,0,0,1,88,52.5)" p:sizing-ox="89" p:sizing-oy="53.5" p:sizing-ow="200" p:sizing-oh="56"><p:metadata><p:property name="box"><![CDATA[200,56]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,7]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|5,5]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="198" height="54" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1; stroke-dasharray: 5, 5;" p:name="rrRect" id="50d1edd378e8475a976ee62cc51e187a" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="646abf607f094b84b088ebb2615c88cd">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#50d1edd378e8475a976ee62cc51e187a" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#646abf607f094b84b088ebb2615c88cd)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="ebb65993472448b0827d87c3a3b09450"/>
|
||||
<use xlink:href="#50d1edd378e8475a976ee62cc51e187a" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="7" y="28" width="186" height="0" p:name="text" id="1ebe6438f1de49eaab62aa0ac42a63dd" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:PlainTextV2" id="253be0b8bade43249b1d0373589b4bde" transform="matrix(1,0,0,1,118,43.5)" p:sizing-ox="117.859375" p:sizing-oy="21.5" p:sizing-ow="79.7890625" p:sizing-oh="28"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[<name>]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Open Sans|bold|normal|20px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
|
||||
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="a00b6941683d4803957395e5c0b93fc5" width="0" height="0"/>
|
||||
<text xml:space="preserve" p:name="text" id="907a2badd36140fa9e10760dbe67b52d" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Open Sans; font-size: 20px; font-weight: bold; font-style: normal; text-decoration: none;"><tspan x="0" y="0"><name></tspan></text>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="a7b1d219b2e04f00946f8ad6fb892a70" transform="matrix(1,0,0,1,333,186.5)" p:sizing-ox="305.5" p:sizing-oy="187" p:sizing-ow="200" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[200,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,12]]></p:property><p:property name="leftEnd"><![CDATA[0,33]]></p:property><p:property name="rightStart"><![CDATA[200,12]]></p:property><p:property name="rightEnd"><![CDATA[200,33]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,80]]></p:property><p:property name="bottomEnd"><![CDATA[33,80]]></p:property><p:property name="pin"><![CDATA[-28,23]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">styles_content / styles<br />classes_content / classes</span><br />]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="d1b2e26143ba4dc9b5011127eaf859fa">
|
||||
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
|
||||
</filter>
|
||||
<g p:name="container" id="1d983e33baff4b5db9814e8bc44d5ff2">
|
||||
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="9d05a5c681eb4e8690d7092cfde36dd4" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 72 C 200 77.33333333333333 197.33333333333334 80 192 80 L 8 80 C 2.6666666666666665 80 0 77.33333333333333 0 72 L 0 33 L -28 23 L 0 12 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
|
||||
</g>
|
||||
</defs>
|
||||
<use xlink:href="#1d983e33baff4b5db9814e8bc44d5ff2" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#d1b2e26143ba4dc9b5011127eaf859fa)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="0a8c818f34d64855927948dca5fdd21e"/>
|
||||
<use xlink:href="#1d983e33baff4b5db9814e8bc44d5ff2" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="8" y="24" width="184" height="33" p:name="text" id="4edecb8e11ca486cad7e10fecaff8778" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">styles_content / styles<br />classes_content / classes</span><br /></div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="c736be040cc84947b5eb28896b2f18b0" transform="matrix(1,0,0,1,333,-0.5)" p:sizing-ox="321.5" p:sizing-oy="0" p:sizing-ow="200" p:sizing-oh="94"><p:metadata><p:property name="box"><![CDATA[200,94]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,14.100000000000001]]></p:property><p:property name="leftEnd"><![CDATA[0,38.775]]></p:property><p:property name="rightStart"><![CDATA[200,14.100000000000001]]></p:property><p:property name="rightEnd"><![CDATA[200,38.775]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,94]]></p:property><p:property name="bottomEnd"><![CDATA[33,94]]></p:property><p:property name="pin"><![CDATA[-12,27.025000000000002]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles_wrapper / styles<br />classes_wrapper / classes<br /></span>]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="da71a006d4af4ce6b8f0dc6b1763b086">
|
||||
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
|
||||
</filter>
|
||||
<g p:name="container" id="9352a73150934cfd986e88ce1ab4a93e">
|
||||
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="1d692ff756b24c2aafa9c15372494c5d" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 86 C 200 91.33333333333333 197.33333333333334 94 192 94 L 8 94 C 2.6666666666666665 94 0 91.33333333333333 0 86 L 0 38.775 L -12 27.025000000000002 L 0 14.100000000000001 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
|
||||
</g>
|
||||
</defs>
|
||||
<use xlink:href="#9352a73150934cfd986e88ce1ab4a93e" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#da71a006d4af4ce6b8f0dc6b1763b086)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="2186895b427e4e0bac628bdbf5b65fe6"/>
|
||||
<use xlink:href="#9352a73150934cfd986e88ce1ab4a93e" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="8" y="22" width="184" height="50" p:name="text" id="b02113fca2d14fa783c537fba5d391e6" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles_wrapper / styles<br />classes_wrapper / classes<br /></span></div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:PlainTextV2" id="61991a849e7f4c72a857ddebed80da33" transform="matrix(1,0,0,1,89,166.5)" p:sizing-ox="87.3984375" p:sizing-oy="154.5" p:sizing-ow="60" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[template]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
|
||||
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="6d064b059239458684409f224ccbb316" width="0" height="0"/>
|
||||
<text xml:space="preserve" p:name="text" id="dadbe69e489042ce8e4eb9fc489ea745" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">template</tspan></text>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:PlainTextV2" id="39a78451571e4e14b57426ec83d5c92a" transform="matrix(1,0,0,1,100,75.5)" p:sizing-ox="98.3984375" p:sizing-oy="63.5" p:sizing-ow="109.1640625" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[template_header]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
|
||||
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="538be6af592e49a686d10f714de79255" width="0" height="0"/>
|
||||
<text xml:space="preserve" p:name="text" id="bb1be320b027418592c6edf7f319411d" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">template_header</tspan></text>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="2f7cafb48e32492193fc2507d4a77a41" transform="matrix(1,0,0,1,88,24.5)" p:sizing-ox="89" p:sizing-oy="25.5" p:sizing-ow="24" p:sizing-oh="24"><p:metadata><p:property name="box"><![CDATA[24,24]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,3]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="22" height="22" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(255, 255, 255); stroke-opacity: 1;" p:name="rrRect" id="226ab97c12354c4c824fbf94a11a98b0" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="8ae0aa26919c481db673739e49601e78">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#226ab97c12354c4c824fbf94a11a98b0" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#8ae0aa26919c481db673739e49601e78)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="13e998ab0f984d15b0b4f7c8f136ac21"/>
|
||||
<use xlink:href="#226ab97c12354c4c824fbf94a11a98b0" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="3" y="12" width="18" height="0" p:name="text" id="998c2f0c678e447fa46f5424e9b8a698" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:arrow" id="f983474041574164a9ed540858755610" transform="matrix(1,0,0,1,-144,61.5)" p:sizing-ox="16" p:sizing-oy="30.5" p:sizing-ow="72" p:sizing-oh="63"><p:metadata><p:property name="startPin"><![CDATA[160,32]]></p:property><p:property name="endPin" p:connectedShapeId="2f7cafb48e32492193fc2507d4a77a41" p:connectedOutletId="middle-left" p:viax="222" p:viay="-25"><![CDATA[232,-25]]></p:property><p:property name="withStartArrow"><![CDATA[false]]></p:property><p:property name="withEndArrow"><![CDATA[true]]></p:property><p:property name="mode"><![CDATA[curvy]]></p:property><p:property name="detached"><![CDATA[false]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
<defs>
|
||||
<path style="stroke-linejoin: round; fill: none;" p:name="path" id="d96ef38bf8c04e81aec043fef0b2d21c" d="M 160 32 C 160 -14 186 -25 232 -25 M 226 -31 L 232 -25 L 226 -19"/>
|
||||
</defs>
|
||||
<use xlink:href="#d96ef38bf8c04e81aec043fef0b2d21c" xmlns:xlink="http://www.w3.org/1999/xlink" stroke-width="10" stroke-opacity="0" stroke="#FF0000"/>
|
||||
<use xlink:href="#d96ef38bf8c04e81aec043fef0b2d21c" xmlns:xlink="http://www.w3.org/1999/xlink" p:name="outArrow1" id="66e4484f068b49a09813e21c39d8994e" style="stroke: rgb(27, 50, 128); stroke-opacity: 1; stroke-width: 2;"/>
|
||||
<text p:name="text" id="b0d40ebba7664c20a9a4f1452c86a07d" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;">
|
||||
<textPath xlink:href="#d96ef38bf8c04e81aec043fef0b2d21c" xmlns:xlink="http://www.w3.org/1999/xlink" startOffset="50%" text-anchor="middle" alignment-baseline="middle">
|
||||
<tspan dy="-4.333333333333333" p:name="textSpan" id="73255d7945434ce9bc661341349735e1" dx="-16"></tspan>
|
||||
</textPath>
|
||||
</text>
|
||||
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:PlainTextV2" id="86ed3ea65aee42199bac08824c3826a6" transform="matrix(1,0,0,1,1,104.5)" p:sizing-ox="0" p:sizing-oy="92.5" p:sizing-ow="31.140625" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[icon]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
|
||||
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="a9ecdbb9c77b4ce4928e46b7cfe54dcf" width="0" height="0"/>
|
||||
<text xml:space="preserve" p:name="text" id="02a5711e99924fc4b34e5730e2a78fa8" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">icon</tspan></text>
|
||||
</g></g></Content></Page><Page><Properties><Property name="name">tab</Property><Property name="id">1421409530685_8513</Property><Property name="width">1531</Property><Property name="height">847</Property><Property name="dimBackground"/><Property name="transparentBackground">true</Property><Property name="backgroundColor">#FFFFFFFF</Property><Property name="background">transparent</Property></Properties><Content><g xmlns="http://www.w3.org/2000/svg" p:type="Group" xmlns:p="http://www.evolus.vn/Namespace/Pencil" transform="translate(201,144)" id="d8e8f6e0f752428680f67384aa52208f" p:sizing-gow="598.5" p:sizing-goh="310"><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="9e881048fedf43d6a67dfad7f06548e9" transform="matrix(1,0,0,1,0,47)" p:sizing-ox="1" p:sizing-oy="48" p:sizing-ow="384" p:sizing-oh="264"><p:metadata><p:property name="box"><![CDATA[384,264]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,33]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="382" height="262" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="12a9d962fb7b4cabbe2795c5e396d6ec" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="76b2ce77019f45daad45b48817f65325">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#12a9d962fb7b4cabbe2795c5e396d6ec" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#76b2ce77019f45daad45b48817f65325)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="6ed5bd1e00f648a792981e16e260963e"/>
|
||||
<use xlink:href="#12a9d962fb7b4cabbe2795c5e396d6ec" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="33" y="132" width="318" height="0" p:name="text" id="14b2622dcb514c21a19fcf064f8abe55" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="fb37074399fd40dc8078a398f9299f3e" transform="matrix(1,0,0,1,16,63)" p:sizing-ox="17" p:sizing-oy="64" p:sizing-ow="352" p:sizing-oh="232"><p:metadata><p:property name="box"><![CDATA[352,232]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,29]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="350" height="230" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="d8debccd7e4f482b8c04420ef54ffa70" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="1eb07f64e796487984ddffea498f79b9">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#d8debccd7e4f482b8c04420ef54ffa70" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#1eb07f64e796487984ddffea498f79b9)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="9b45931ea5e84b15a01479b46dc76b83"/>
|
||||
<use xlink:href="#d8debccd7e4f482b8c04420ef54ffa70" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="29" y="116" width="294" height="0" p:name="text" id="6d8d3f3cce8b4da0b0f97ed8a5fce058" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:PlainTextV2" id="407ebd46fa5f48f395a7d5a0b8d46d2a" transform="matrix(1,0,0,1,26,83)" p:sizing-ox="24.3984375" p:sizing-oy="71" p:sizing-ow="60" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[template]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
|
||||
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="efd58ec8f2eb45dcbeea7bb13c573cc5" width="0" height="0"/>
|
||||
<text xml:space="preserve" p:name="text" id="ba9f30328268467ba17566dbd14ae998" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">template</tspan></text>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:trapezoid" id="cb49850d258c4367abbee3628aa93512" transform="matrix(1,0,0,1,0,0)" p:sizing-ox="0" p:sizing-oy="0" p:sizing-ow="119" p:sizing-oh="48"><p:metadata><p:property name="box"><![CDATA[119,48]]></p:property><p:property name="a"><![CDATA[29.750000000000004,0]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property></p:metadata>
|
||||
<path style="stroke-linejoin: round; stroke: rgb(0, 0, 0); stroke-opacity: 1; stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1;" p:name="path" id="ac794f7d717045878f0fdebc737e9adc" transform="translate(0,0)" d="M 29.750000000000004 0 L 89.25 0 L 119 48 L 0 48 z"/>
|
||||
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:trapezoid" id="b0b14e6d505d4af7a04a05a8cc7fe672" transform="matrix(1,0,0,1,87,0)" p:sizing-ox="87" p:sizing-oy="0" p:sizing-ow="120" p:sizing-oh="48"><p:metadata><p:property name="box"><![CDATA[120,48]]></p:property><p:property name="a"><![CDATA[30,0]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property></p:metadata>
|
||||
<path style="stroke-linejoin: round; stroke: rgb(0, 0, 0); stroke-opacity: 1; stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1;" p:name="path" id="5c4e128120224a0f87c3c6f9e98f9183" transform="translate(0,0)" d="M 30 0 L 90 0 L 120 48 L 0 48 z"/>
|
||||
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:trapezoid" id="b95ce307dbc04cb297e1d019f1c31d0d" transform="matrix(1,0,0,1,263,0)" p:sizing-ox="263" p:sizing-oy="0" p:sizing-ow="120" p:sizing-oh="48"><p:metadata><p:property name="box"><![CDATA[120,48]]></p:property><p:property name="a"><![CDATA[30,0]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property></p:metadata>
|
||||
<path style="stroke-linejoin: round; stroke: rgb(0, 0, 0); stroke-opacity: 1; stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1;" p:name="path" id="58f26895549a4afe87215738aad60c7f" transform="translate(0,0)" d="M 30 0 L 90 0 L 120 48 L 0 48 z"/>
|
||||
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:trapezoid" id="dd08c65002d54b4d963c0fc1ddd8da56" transform="matrix(1,0,0,1,175,0)" p:sizing-ox="175" p:sizing-oy="0" p:sizing-ow="120" p:sizing-oh="48"><p:metadata><p:property name="box"><![CDATA[120,48]]></p:property><p:property name="a"><![CDATA[30,0]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property></p:metadata>
|
||||
<path style="stroke-linejoin: round; stroke: rgb(0, 0, 0); stroke-opacity: 1; stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1;" p:name="path" id="2ff5fd3ed1174b1ca120e0521506dfdb" transform="translate(0,0)" d="M 30 0 L 90 0 L 120 48 L 0 48 z"/>
|
||||
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:PlainTextV2" id="c821784d3f6f4c54a482c9b800303096" transform="matrix(1,0,0,1,196,38)" p:sizing-ox="195.859375" p:sizing-oy="16" p:sizing-ow="79.7890625" p:sizing-oh="28"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[<name>]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Open Sans|bold|normal|20px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
|
||||
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="45c9bc72749f4114b754dd78d39294d9" width="0" height="0"/>
|
||||
<text xml:space="preserve" p:name="text" id="510af970bf6e4a3299e10d5726dc506b" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Open Sans; font-size: 20px; font-weight: bold; font-style: normal; text-decoration: none;"><tspan x="0" y="0"><name></tspan></text>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="28819f317c9a44f487d89358bc01d35e" transform="matrix(1,0,0,1,398,0)" p:sizing-ox="284.5" p:sizing-oy="0.5" p:sizing-ow="200" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[200,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,12]]></p:property><p:property name="leftEnd"><![CDATA[0,33]]></p:property><p:property name="rightStart"><![CDATA[200,12]]></p:property><p:property name="rightEnd"><![CDATA[200,33]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,80]]></p:property><p:property name="bottomEnd"><![CDATA[33,80]]></p:property><p:property name="pin"><![CDATA[-114,22]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles_link / styles<br />classes_link / classes</span><br />]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="f46117a9847b442a848d6dc6d0f1ca02">
|
||||
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
|
||||
</filter>
|
||||
<g p:name="container" id="7e565a2554874c8693bee8c3b1fb4a96">
|
||||
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="35606f3a84d34cfabef6fd7995e162c9" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 72 C 200 77.33333333333333 197.33333333333334 80 192 80 L 8 80 C 2.6666666666666665 80 0 77.33333333333333 0 72 L 0 33 L -114 22 L 0 12 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
|
||||
</g>
|
||||
</defs>
|
||||
<use xlink:href="#7e565a2554874c8693bee8c3b1fb4a96" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#f46117a9847b442a848d6dc6d0f1ca02)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="fba23d0e302047588af7e9e586dfb238"/>
|
||||
<use xlink:href="#7e565a2554874c8693bee8c3b1fb4a96" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="8" y="15" width="184" height="50" p:name="text" id="d94b77112885453db437a00ff25500ca" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles_link / styles<br />classes_link / classes</span><br /></div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="6f1c4f61a1fb4f14a28d1793b958ba0a" transform="matrix(1,0,0,1,397,120)" p:sizing-ox="369.5" p:sizing-oy="120.5" p:sizing-ow="200" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[200,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,12]]></p:property><p:property name="leftEnd"><![CDATA[0,33]]></p:property><p:property name="rightStart"><![CDATA[200,12]]></p:property><p:property name="rightEnd"><![CDATA[200,33]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,80]]></p:property><p:property name="bottomEnd"><![CDATA[33,80]]></p:property><p:property name="pin"><![CDATA[-28,23]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles_content / styles<br />classes_content / classes</span><br />]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="acf275ea0a954d79ae41107f58d208ae">
|
||||
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
|
||||
</filter>
|
||||
<g p:name="container" id="a75b69e48d5e40f4b6150b1ec2953af3">
|
||||
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="eb3218f33a0b49fb8ec0ad9f86d2872a" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 72 C 200 77.33333333333333 197.33333333333334 80 192 80 L 8 80 C 2.6666666666666665 80 0 77.33333333333333 0 72 L 0 33 L -28 23 L 0 12 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
|
||||
</g>
|
||||
</defs>
|
||||
<use xlink:href="#a75b69e48d5e40f4b6150b1ec2953af3" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#acf275ea0a954d79ae41107f58d208ae)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="809f63827dbe473db68c768a9299d7be"/>
|
||||
<use xlink:href="#a75b69e48d5e40f4b6150b1ec2953af3" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="8" y="15" width="184" height="50" p:name="text" id="31d16c095ee849c791565b6c88b93fad" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles_content / styles<br />classes_content / classes</span><br /></div></foreignObject>
|
||||
</g></g></Content></Page><Page><Properties><Property name="name">settings</Property><Property name="id">1421410253180_3579</Property><Property name="width">1531</Property><Property name="height">847</Property><Property name="dimBackground"/><Property name="transparentBackground">true</Property><Property name="backgroundColor">#FFFFFFFF</Property><Property name="background">transparent</Property></Properties><Content><g xmlns="http://www.w3.org/2000/svg" p:type="Group" xmlns:p="http://www.evolus.vn/Namespace/Pencil" transform="translate(323,143)" id="7395842d34de4079b3029fbb8f377213" p:sizing-gow="769.5" p:sizing-goh="390"><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="5267d389e1714536a6262df513ff7665" transform="matrix(1,0,0,1,-1,-1)" p:sizing-ox="0" p:sizing-oy="0" p:sizing-ow="144" p:sizing-oh="392"><p:metadata><p:property name="box"><![CDATA[144,392]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,49]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="142" height="390" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="cb16e9a309e341f1ba7f6440a0483dc7" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="54e55b5fad5d4a3995c3806b790f2d05">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#cb16e9a309e341f1ba7f6440a0483dc7" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#54e55b5fad5d4a3995c3806b790f2d05)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="904bde4e72cb4b5aa6cb5b963c339bdf"/>
|
||||
<use xlink:href="#cb16e9a309e341f1ba7f6440a0483dc7" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="49" y="196" width="46" height="0" p:name="text" id="e13fe7a85e1a4ca081470478b747bc8c" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="00107838b5c846ac87f4bbc67a235524" transform="matrix(1,0,0,1,143,-1)" p:sizing-ox="144" p:sizing-oy="0" p:sizing-ow="416" p:sizing-oh="392"><p:metadata><p:property name="box"><![CDATA[416,392]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,49]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="414" height="390" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="cbe5e6469a9647b9a54b064a30ee0c35" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="8d5eca961f8d499abcbcdb90c9f38da8">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#cbe5e6469a9647b9a54b064a30ee0c35" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#8d5eca961f8d499abcbcdb90c9f38da8)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="34141c77145742d3810b0e7474f6e012"/>
|
||||
<use xlink:href="#cbe5e6469a9647b9a54b064a30ee0c35" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="49" y="196" width="318" height="0" p:name="text" id="41ef32306e1e4d9da9165746657a5965" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="dfc036f4a3394f48abfd564cd42b2b0e" transform="matrix(1,0,0,1,159,15)" p:sizing-ox="160" p:sizing-oy="16" p:sizing-ow="384" p:sizing-oh="360"><p:metadata><p:property name="box"><![CDATA[384,360]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,45]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="382" height="358" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="29dc0c2600da465fb63911073183eafe" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="451d197a117c48f7a68d1c1be41304e5">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#29dc0c2600da465fb63911073183eafe" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#451d197a117c48f7a68d1c1be41304e5)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="6c260c83376042eda5122f600dac0784"/>
|
||||
<use xlink:href="#29dc0c2600da465fb63911073183eafe" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="45" y="180" width="294" height="0" p:name="text" id="cb978529c3144a3085a502964a33bfa4" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="f2e9506fa0ed4466890d1042d5ac901e" transform="matrix(1,0,0,1,15,175)" p:sizing-ox="16" p:sizing-oy="176" p:sizing-ow="112" p:sizing-oh="40"><p:metadata><p:property name="box"><![CDATA[112,40]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,5]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="110" height="38" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="76d805dced5640149e7d9b75b58e9479" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="4fc6940222be4d1bb3d1bba581209b59">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#76d805dced5640149e7d9b75b58e9479" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#4fc6940222be4d1bb3d1bba581209b59)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="60a990d0eb9e4ea69c10c41791e58323"/>
|
||||
<use xlink:href="#76d805dced5640149e7d9b75b58e9479" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="5" y="20" width="102" height="0" p:name="text" id="54e8a52460b84409b8c52e713918e527" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:PlainTextV2" id="3a5c9441f4dd450489ef6c32b84277bb" transform="matrix(1,0,0,1,22,202)" p:sizing-ox="21.859375" p:sizing-oy="180" p:sizing-ow="79.7890625" p:sizing-oh="28"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[<name>]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Open Sans|bold|normal|20px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
|
||||
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="49590ece8832421093f480572615621e" width="0" height="0"/>
|
||||
<text xml:space="preserve" p:name="text" id="638c493afd75474bba33ba6ed7f6b418" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Open Sans; font-size: 20px; font-weight: bold; font-style: normal; text-decoration: none;"><tspan x="0" y="0"><name></tspan></text>
|
||||
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:PlainTextV2" id="ebd3473021234611aefc9fa212dcc943" transform="matrix(1,0,0,1,175,37)" p:sizing-ox="173.3984375" p:sizing-oy="25" p:sizing-ow="60" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[template]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
|
||||
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="a7f7b8da20384df091964756d22bd5df" width="0" height="0"/>
|
||||
<text xml:space="preserve" p:name="text" id="85ffc835cc2f4e8ea41c1857b55af53e" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">template</tspan></text>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="a0d9b8a91b8d4913bc11cca99c86a459" transform="matrix(1,0,0,1,569,15)" p:sizing-ox="541.5" p:sizing-oy="15.5" p:sizing-ow="200" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[200,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,12]]></p:property><p:property name="leftEnd"><![CDATA[0,33]]></p:property><p:property name="rightStart"><![CDATA[200,12]]></p:property><p:property name="rightEnd"><![CDATA[200,33]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,80]]></p:property><p:property name="bottomEnd"><![CDATA[33,80]]></p:property><p:property name="pin"><![CDATA[-28,23]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles_content / styles<br />classes_content / classes<br /></span>]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="2f5319b357c84839b3986162a515c00e">
|
||||
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
|
||||
</filter>
|
||||
<g p:name="container" id="9c15a0a8bd764d0187e813cd78f906d4">
|
||||
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="0f6d812601a94e60b7f5e3f1d859d630" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 72 C 200 77.33333333333333 197.33333333333334 80 192 80 L 8 80 C 2.6666666666666665 80 0 77.33333333333333 0 72 L 0 33 L -28 23 L 0 12 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
|
||||
</g>
|
||||
</defs>
|
||||
<use xlink:href="#9c15a0a8bd764d0187e813cd78f906d4" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#2f5319b357c84839b3986162a515c00e)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="4a90c69f97384e74ae968cff348b2ed9"/>
|
||||
<use xlink:href="#9c15a0a8bd764d0187e813cd78f906d4" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="8" y="15" width="184" height="50" p:name="text" id="eac648dfa87d4f719c8d271b82f1c930" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles_content / styles<br />classes_content / classes<br /></span></div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="bda1534d936b4b1a8851bd7316333963" transform="matrix(1,0,0,1,137,175)" p:sizing-ox="125.5" p:sizing-oy="175.5" p:sizing-ow="200" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[200,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,12]]></p:property><p:property name="leftEnd"><![CDATA[0,33]]></p:property><p:property name="rightStart"><![CDATA[200,12]]></p:property><p:property name="rightEnd"><![CDATA[200,33]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,80]]></p:property><p:property name="bottomEnd"><![CDATA[33,80]]></p:property><p:property name="pin"><![CDATA[-12,23]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles_link / styles<br />classes_link / classes</span><br />]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="7190c91fd5a0498faee46f6a07e4ee36">
|
||||
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
|
||||
</filter>
|
||||
<g p:name="container" id="e38975d273874cd7ac31fa1c63716ec1">
|
||||
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="72ab543eb28a48e6bedf116266c72fbb" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 72 C 200 77.33333333333333 197.33333333333334 80 192 80 L 8 80 C 2.6666666666666665 80 0 77.33333333333333 0 72 L 0 33 L -12 23 L 0 12 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
|
||||
</g>
|
||||
</defs>
|
||||
<use xlink:href="#e38975d273874cd7ac31fa1c63716ec1" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#7190c91fd5a0498faee46f6a07e4ee36)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="f143de029bc146c7a3a7bca494562509"/>
|
||||
<use xlink:href="#e38975d273874cd7ac31fa1c63716ec1" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="8" y="15" width="184" height="50" p:name="text" id="9ba09cfb0e0643c69291c6942df8c8c9" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles_link / styles<br />classes_link / classes</span><br /></div></foreignObject>
|
||||
</g></g></Content></Page><Page><Properties><Property name="name">navbar</Property><Property name="id">1421410510071_9693</Property><Property name="width">1531</Property><Property name="height">847</Property><Property name="dimBackground"/><Property name="transparentBackground">true</Property><Property name="backgroundColor">#FFFFFFFF</Property><Property name="background">transparent</Property></Properties><Content><g xmlns="http://www.w3.org/2000/svg" p:type="Group" xmlns:p="http://www.evolus.vn/Namespace/Pencil" transform="translate(126,121)" id="31a617e276fe4161a5e3b70380bb0e34" p:sizing-gow="490.5" p:sizing-goh="78"><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="fa8da9aed28744f5af9f11285080496c" transform="matrix(1,0,0,1,-1,-1)" p:sizing-ox="0" p:sizing-oy="0" p:sizing-ow="283" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[283,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,10]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="281" height="78" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="ea12bfd96e974a0f8f92afced67bdd6f" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="d5043318357b49a1bb219a00f76eddd9">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#ea12bfd96e974a0f8f92afced67bdd6f" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#d5043318357b49a1bb219a00f76eddd9)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="0d42ff0970ff472aa4c006ef85d8e87a"/>
|
||||
<use xlink:href="#ea12bfd96e974a0f8f92afced67bdd6f" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="10" y="40" width="263" height="0" p:name="text" id="40018080392b490da490d8b286b95c41" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="5b845ca54039496591b80db2010a32bc" transform="matrix(1,0,0,1,122,15)" p:sizing-ox="123" p:sizing-oy="16" p:sizing-ow="144" p:sizing-oh="48"><p:metadata><p:property name="box"><![CDATA[144,48]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,6]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
|
||||
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<rect width="142" height="46" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="480225b90d8842139e20649d22caa757" transform="translate(1,1)"/>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="db76ffd36668492aa45c3dacb4ed2d52">
|
||||
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<use xlink:href="#480225b90d8842139e20649d22caa757" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#db76ffd36668492aa45c3dacb4ed2d52)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="125928c2b681488ba446768b095a76a5"/>
|
||||
<use xlink:href="#480225b90d8842139e20649d22caa757" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="6" y="24" width="132" height="0" p:name="text" id="de5cbf018c224ba3adf8aed52ebc5f77" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
|
||||
</div></foreignObject>
|
||||
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:PlainTextV2" id="3637818ac51540849a753285e83d950d" transform="matrix(1,0,0,1,132,35)" p:sizing-ox="130.3984375" p:sizing-oy="23" p:sizing-ow="60" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[template]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
|
||||
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="6f91157aa1354619ab2b7960baeb8cba" width="0" height="0"/>
|
||||
<text xml:space="preserve" p:name="text" id="638334d0a39b4b39a7e4806254e2e418" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">template</tspan></text>
|
||||
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="c0be16ae150d4dc68b7bffdc19d19262" transform="matrix(1,0,0,1,294,7)" p:sizing-ox="266.5" p:sizing-oy="7.5" p:sizing-ow="196" p:sizing-oh="64"><p:metadata><p:property name="box"><![CDATA[196,64]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[7.84,0]]></p:property><p:property name="leftStart"><![CDATA[0,9.84]]></p:property><p:property name="leftEnd"><![CDATA[0,26.400000000000002]]></p:property><p:property name="rightStart"><![CDATA[196,9.84]]></p:property><p:property name="rightEnd"><![CDATA[196,26.400000000000002]]></p:property><p:property name="topStart"><![CDATA[11.76,0]]></p:property><p:property name="topEnd"><![CDATA[32.339999999999996,0]]></p:property><p:property name="bottomStart"><![CDATA[11.76,64]]></p:property><p:property name="bottomEnd"><![CDATA[32.339999999999996,64]]></p:property><p:property name="pin"><![CDATA[-28,18]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles<br />classes</span><br />]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
|
||||
|
||||
<defs>
|
||||
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="f3a0f53acfa3492abf13b69eb2bf8e75">
|
||||
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
|
||||
</filter>
|
||||
<g p:name="container" id="8eaa88f76ee748fdbb66142e124db376">
|
||||
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="e5ed7702279b485f83a84e170232b245" d="M 7.84 0 L 188.16 0 C 193.38666666666666 0 196 2.6133333333333333 196 7.84 L 196 56.16 C 196 61.38666666666667 193.38666666666666 64 188.16 64 L 7.84 64 C 2.6133333333333333 64 0 61.38666666666667 0 56.16 L 0 26.400000000000002 L -28 18 L 0 9.84 L 0 7.84 C 0 2.6133333333333333 2.6133333333333333 0 7.84 0"/>
|
||||
</g>
|
||||
</defs>
|
||||
<use xlink:href="#8eaa88f76ee748fdbb66142e124db376" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#f3a0f53acfa3492abf13b69eb2bf8e75)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="e7a7687af8d14f2888d588636e0cd333"/>
|
||||
<use xlink:href="#8eaa88f76ee748fdbb66142e124db376" xmlns:xlink="http://www.w3.org/1999/xlink"/>
|
||||
<foreignObject x="7.84" y="7" width="180.32" height="50" p:name="text" id="cdcded6607b7463ea18aa393da7520bc" style="font-family: "Liberation Sans",Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles<br />classes</span><br /></div></foreignObject>
|
||||
</g></g></Content></Page></Pages></Document>
|
||||
@@ -6,17 +6,16 @@ Welcome to OctoPrint's documentation!
|
||||
: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 a 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
|
||||
|
||||
features/index.rst
|
||||
configuration/index.rst
|
||||
api/index.rst
|
||||
events/index.rst
|
||||
plugins/index.rst
|
||||
modules/index.rst
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
.. _sec-modules-filemanager:
|
||||
|
||||
octoprint.filemanager
|
||||
---------------------
|
||||
|
||||
.. automodule:: octoprint.filemanager
|
||||
:members:
|
||||
|
||||
.. _sec-modules-filemanager-analysis:
|
||||
|
||||
octoprint.filemanager.analysis
|
||||
------------------------------
|
||||
|
||||
.. automodule:: octoprint.filemanager.analysis
|
||||
:members:
|
||||
|
||||
.. _sec-modules-filemanager-destinations:
|
||||
|
||||
octoprint.filemanager.destinations
|
||||
----------------------------------
|
||||
|
||||
.. automodule:: octoprint.filemanager.destinations
|
||||
:members:
|
||||
|
||||
.. _sec-modules-filemanager-storage:
|
||||
|
||||
octoprint.filemanager.storage
|
||||
-----------------------------
|
||||
|
||||
.. automodule:: octoprint.filemanager.storage
|
||||
:members: StorageInterface, LocalFileStorage
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
.. _sec-modules:
|
||||
|
||||
################
|
||||
Internal Modules
|
||||
################
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 3
|
||||
|
||||
filemanager.rst
|
||||
plugin.rst
|
||||
printer.rst
|
||||
settings.rst
|
||||
util.rst
|
||||
@@ -0,0 +1,20 @@
|
||||
.. _sec-modules-plugin:
|
||||
|
||||
octoprint.plugin
|
||||
----------------
|
||||
|
||||
.. automodule:: octoprint.plugin
|
||||
|
||||
.. _sec-modules-plugin-core:
|
||||
|
||||
octoprint.plugin.core
|
||||
---------------------
|
||||
|
||||
.. automodule:: octoprint.plugin.core
|
||||
|
||||
.. _sec-modules-plugin-types:
|
||||
|
||||
octoprint.plugin.types
|
||||
----------------------
|
||||
|
||||
.. automodule:: octoprint.plugin.types
|
||||
@@ -0,0 +1,6 @@
|
||||
.. _sec-modules-printer:
|
||||
|
||||
octoprint.printer
|
||||
-----------------
|
||||
|
||||
.. automodule:: octoprint.printer
|
||||
@@ -0,0 +1,6 @@
|
||||
.. _sec-modules-settings:
|
||||
|
||||
octoprint.settings
|
||||
------------------
|
||||
|
||||
.. automodule:: octoprint.settings
|
||||
@@ -0,0 +1,9 @@
|
||||
.. _sec-modules-util:
|
||||
|
||||
octoprint.util
|
||||
--------------
|
||||
|
||||
.. automodule:: octoprint.util
|
||||
:members:
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
.. _sec-plugins-distribution:
|
||||
|
||||
Distributing your plugin
|
||||
========================
|
||||
|
||||
You can distribute a plugin with OctoPrint via two ways:
|
||||
|
||||
- You can have your users copy it to OctoPrint's plugin folder (normally located at ``~/.octoprint/plugins`` under Linux,
|
||||
``%APPDATA%\OctoPrint\plugins`` on Windows and ... on Mac). In this case your plugin will be distributed directly
|
||||
as a Python module (a single ``.py`` file containing all of your plugin's code directly and named
|
||||
like your plugin) or a package (a folder named like your plugin + ``__init.py__`` contained within).
|
||||
- You can have your users install it via ``pip`` and register it for the `entry point <https://pythonhosted.org/setuptools/setuptools.html#dynamic-discovery-of-services-and-plugins>`_ ``octoprint.plugin`` via
|
||||
your plugin's ``setup.py``, this way it will be found automatically by OctoPrint upon initialization of the
|
||||
plugin subsystem [#f1]_.
|
||||
|
||||
For an example of how the directory structure and related files would look like in this case, please take a
|
||||
look at the `helloworld example from OctoPrint's example plugins <https://github.com/OctoPrint/Plugin-Examples/tree/master/helloworld>`_.
|
||||
|
||||
This variant is highly recommended for pretty much any plugin besides the most basic ones since it also allows
|
||||
requirements management and pretty much any thing else that Python's setuptools provide to the developer.
|
||||
|
||||
.. rubric:: Footnotes
|
||||
|
||||
.. [#f1] The automatic registration will only work within the same Python installation (this also includes virtual
|
||||
environments), so make sure to instruct your users to use the exact same Python installation for installing
|
||||
the plugin that they also used for installing & running OctoPrint.
|
||||
|
||||
@@ -0,0 +1,906 @@
|
||||
.. _sec-plugins-gettingstarted:
|
||||
|
||||
Getting Started
|
||||
===============
|
||||
|
||||
Over the course of this little tutorial we'll build a full fledged, installable OctoPrint plugin that displays "Hello World!"
|
||||
at some locations throughout OctoPrint and also offers some other basic functionality to give you an idea of what
|
||||
you can achieve with OctoPrint's plugin system.
|
||||
|
||||
We'll start at the most basic form a plugin can take - just a couple of simple lines of Python code:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
|
||||
Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup::
|
||||
|
||||
2015-01-27 11:14:35,124 - octoprint.server - INFO - Starting OctoPrint 1.2.0-dev-448-gd96e56e (devel branch)
|
||||
2015-01-27 11:14:35,124 - octoprint.plugin.core - INFO - Loading plugins from /home/pi/.octoprint/plugins, /home/pi/OctoPrint/src/octoprint/plugins and installed plugin packages...
|
||||
2015-01-27 11:14:36,135 - octoprint.plugin.core - INFO - Found 3 plugin(s): Hello World (1.0), CuraEngine (0.1), Discovery (0.1)
|
||||
|
||||
OctoPrint found that plugin in the folder and took a look into it. The name and the version it displays in that log
|
||||
entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from
|
||||
``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now.
|
||||
|
||||
.. _sec-plugins-gettingstarted-sayinghello:
|
||||
|
||||
Saying hello: How to make the plugin actually do something
|
||||
----------------------------------------------------------
|
||||
|
||||
Apart from being discovered by OctoPrint, our plugin does nothing yet. We want to change that. Let's make it print
|
||||
"Hello World!" to the log upon server startup. Modify our ``helloworld.py`` like this:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 4-8,13
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin):
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
__plugin_implementations__ = [HelloWorldPlugin()]
|
||||
|
||||
and restart OctoPrint. You now get this output in the log::
|
||||
|
||||
2015-01-27 11:17:10,792 - octoprint.plugins.helloworld - INFO - Hello World!
|
||||
|
||||
Neat, isn't it? We added a custom class that subclasses one of OctoPrint's :ref:`plugin mixins <sec-plugins-mixins>`
|
||||
with :class:`~octoprint.plugin.StartupPlugin` and another control property, ``__plugin_implementations__``, that instantiates
|
||||
our plugin class and tells OctoPrint about it. Taking a look at the documentation of :class:`~octoprint.plugin.StartupPlugin` we see that
|
||||
this mixin offers two methods that get called by OctoPrint during startup of the server, :func:`~octoprint.plugin.StartupPlugin.on_startup` and
|
||||
:func:`~octoprint.plugin.StartupPlugin.on_after_startup`. We decided to add our logging output by overriding :func:`~octoprint.plugin.StartupPlugin.on_after_startup`, but we could also have
|
||||
used :func:`~octoprint.plugin.StartupPlugin.on_startup` instead, in which case our logging statement would be executed before the server was done starting
|
||||
up and ready to serve requests.
|
||||
|
||||
You'll also note that we are using ``self._logger`` for logging. Where did that one come from? OctoPrint's plugin system
|
||||
injects :ref:`a couple of useful objects <sec-plugins-infrastructure-injections>` into our plugin implementation classes,
|
||||
one of those being a fully instantiated `python logger <https://docs.python.org/2/library/logging.html>`_ ready to be
|
||||
used by your plugin. As you can see in the log output above, that logger uses the namespace ``octoprint.plugins.helloworld``
|
||||
for our little plugin here, or more generally ``octoprint.plugins.<plugin identifier>``.
|
||||
|
||||
.. _sec-plugins-gettingstarted-growingup:
|
||||
|
||||
Growing up: How to make it distributable
|
||||
----------------------------------------
|
||||
|
||||
If you now want to distribute this plugin to other OctoPrint users (since it is so awesome to be greeted upon server
|
||||
startup), let's take a look at how you'd go about that now before our plugin gets more complicated.
|
||||
|
||||
You basically have two options to distribute your plugin. One would be about the exact same way we are using it now,
|
||||
as a simple python file following the naming convention ``<plugin identifier>.py`` that your users add to their
|
||||
``~/.octoprint/plugins`` folder. You already know how that works. But let's say you have more than just a simple plugin
|
||||
that can be done in one file. Distributing multiple files and getting your users to install them in the right way
|
||||
so that OctoPrint will be able to actually find and load them is certainly not impossible (see :ref:`the plugin distribution
|
||||
documentation <sec-plugins-distribution>` if you want to take a closer look at that option), but we want to do it in the
|
||||
best way possible, meaning we want to make our plugin a fully installable python module that your users will be able to
|
||||
install directly via Python's standard package manager ``pip`` or alternatively via `OctoPrint's own plugin manager <https://github.com/OctoPrint/OctoPrint-PluginManager>`_.
|
||||
|
||||
So let's begin. First checkout the `Plugin Skeleton <https://github.com/OctoPrint/OctoPrint-PluginSkeleton>`_ and rename
|
||||
the ``octoprint_skeleton`` folder to something better suited to our "Hello World" plugin::
|
||||
|
||||
$ git clone https://github.com/OctoPrint/OctoPrint-PluginSkeleton.git OctoPrint-HelloWorld
|
||||
Cloning into 'OctoPrint-HelloWorld'...
|
||||
[...]
|
||||
$ cd OctoPrint-HelloWorld
|
||||
$ mv octoprint_skeleton octoprint_helloworld
|
||||
|
||||
Then edit the configuration in the ``setup.py`` file to mirror our own "Hello World" plugin. The configuration should
|
||||
look something like this:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
plugin_identifier = "helloworld"
|
||||
plugin_name = "OctoPrint-HelloWorld"
|
||||
plugin_version = "1.0"
|
||||
plugin_description = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
plugin_author = "You"
|
||||
plugin_author_email = "you@somewhere.net"
|
||||
plugin_url = "https://github.com/you/OctoPrint-HelloWorld"
|
||||
|
||||
Now all that's left to do is to move our ``helloworld.py`` into the ``octoprint_helloworld`` folder and renaming it to
|
||||
``__init__.py``. Make sure to delete the copy under ``~/.octoprint/plugins`` in the process, including the `.pyc` file!
|
||||
|
||||
The plugin is now ready to be installed via ``python setup.py install``. However, since we are still
|
||||
working on our plugin, it makes more sense to use ``python setup.py develop`` for now -- this way the plugin becomes
|
||||
discoverable by OctoPrint, however we don't have to reinstall it after any changes we will still do::
|
||||
|
||||
$ python setup.py develop
|
||||
running develop
|
||||
running egg_info
|
||||
creating OctoPrint_HelloWorld.egg-info
|
||||
[...]
|
||||
Finished processing dependencies for OctoPrint-HelloWorld==1.0
|
||||
|
||||
Restart OctoPrint. Your plugin should still be properly discovered and the log line should be printed::
|
||||
|
||||
2015-01-27 13:43:34,134 - octoprint.server - INFO - Starting OctoPrint 1.2.0-dev-448-gd96e56e (devel branch)
|
||||
2015-01-27 13:43:34,134 - octoprint.plugin.core - INFO - Loading plugins from /home/pi/.octoprint/plugins, /home/pi/OctoPrint/src/octoprint/plugins and installed plugin packages...
|
||||
2015-01-27 13:43:34,818 - octoprint.plugin.core - INFO - Found 3 plugin(s): Hello World (1.0), CuraEngine (0.1), Discovery (0.1)
|
||||
[...]
|
||||
2015-01-27 13:43:38,997 - octoprint.plugins.helloworld - INFO - Hello World!
|
||||
|
||||
Looks like it still works!
|
||||
|
||||
Something is still a bit ugly though. Take a look into ``__init__.py`` and ``setup.py``. It seems like we have a bunch
|
||||
of information now defined twice:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
# __init__.py:
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
|
||||
# setup.py
|
||||
plugin_name = "OctoPrint-HelloWorld"
|
||||
plugin_version = "1.0"
|
||||
plugin_description = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
|
||||
The nice thing about our plugin now being a proper python package is that OctoPrint can and will access the metadata defined
|
||||
within ``setup.py``! So, we don't really need to define all this data twice. Remove ``__plugin_name__``, ``__plugin_version__``
|
||||
and ``__plugin_description__``:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin):
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_implementations__ = [HelloWorldPlugin()]
|
||||
|
||||
and restart OctoPrint::
|
||||
|
||||
2015-01-27 13:46:33,786 - octoprint.plugin.core - INFO - Found 3 plugin(s): OctoPrint-HelloWorld (1.0), CuraEngine (0.1), Discovery (0.1)
|
||||
|
||||
Our "Hello World" Plugin still gets detected fine, but it's now listed under the same name it's installed under,
|
||||
"OctoPrint-HelloWorld". That's a bit redundant and squashed, so we'll override that bit via ``__plugin_name__`` again:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 10
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin):
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_implementations__ = [HelloWorldPlugin()]
|
||||
|
||||
|
||||
Restart OctoPrint again::
|
||||
|
||||
2015-01-27 13:48:54,122 - octoprint.plugin.core - INFO - Found 3 plugin(s): Hello World (1.0), CuraEngine (0.1), Discovery (0.1)
|
||||
|
||||
Much better! You can override pretty much all of the metadata defined within ``setup.py`` from within your Plugin itself --
|
||||
take a look at :ref:`the available control properties <sec-plugins-infrastructure-controlproperties>` for all available
|
||||
overrides.
|
||||
|
||||
Following the README of the `Plugin Skeleton <https://github.com/OctoPrint/OctoPrint-PluginSkeleton>`_ you could now
|
||||
already publish your plugin on Github and it would be directly installable by others using pip::
|
||||
|
||||
pip install https://github.com/you/OctoPrint-HelloWorld/archive/master.zip
|
||||
|
||||
But let's add some more features instead.
|
||||
|
||||
.. _sec-plugins-gettingstarted-templates:
|
||||
|
||||
Frontend fun: How to add functionality to OctoPrint's web interface
|
||||
-------------------------------------------------------------------
|
||||
|
||||
Outputting a log line upon server startup is all nice and well, but we want to greet not only the administrator of
|
||||
our OctoPrint instance but actually everyone that opens OctoPrint in their browser. Therefore, we need to modify
|
||||
OctoPrint's web interface itself.
|
||||
|
||||
We can do this using the :class:`TemplatePlugin` mixin. For now, let's start with a little "Hello World!" in OctoPrint's
|
||||
navigation bar right at the top that links to the Wikipedia node about "Hello World" programs. For this we'll first
|
||||
add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 7
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.TemplatePlugin):
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_implementations__ = [HelloWorldPlugin()]
|
||||
|
||||
Next, we'll create a sub folder ``templates`` underneath our ``octoprint_helloworld`` folder, and within that a file
|
||||
``helloworld_navbar.jinja2`` like so:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
|
||||
<a href="https://en.wikipedia.org/wiki/Hello_world">Hello World!</a>
|
||||
|
||||
Our plugin's directory structure should now look like this::
|
||||
|
||||
octoprint_helloworld/
|
||||
templates/
|
||||
helloworld_navbar.jinja2
|
||||
__init__.py
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
|
||||
Restart OctoPrint and open the web interface in your browser (make sure to clear your browser's cache!).
|
||||
|
||||
.. _fig-plugins-gettingstarted-helloworld_navbar:
|
||||
.. figure:: ../images/plugins_gettingstarted_helloworld_navbar.png
|
||||
:align: center
|
||||
:alt: Our "Hello World" navigation bar element in action
|
||||
|
||||
Now look at that!
|
||||
|
||||
.. _sec-plugins-gettingstarted-settings:
|
||||
|
||||
Settings Galore: How to make parts of your plugin user adjustable
|
||||
-----------------------------------------------------------------
|
||||
|
||||
Remember that Wikipedia link we added to our little link in the navigation bar? It links to the english Wikipedia. But
|
||||
what if we want to allow our users to adjust that according to their wishes, e.g. to link to the german language node
|
||||
about "Hello World" programs instead?
|
||||
|
||||
To allow your users to customized the behaviour of your plugin you'll need to implement the :class:`~octoprint.plugin.SettingsPlugin`
|
||||
mixin and override it's :func:`~octoprint.plugin.SettingsPlugin.get_settings_defaults` method. We'll save the URL to
|
||||
inject into the link under the key ``url`` in our plugin's settings and set it to the old value by default. We'll therefore
|
||||
return just a single key in our default settings dictionary. To be able to quickly see if we've done that right we'll
|
||||
extend our little startup message to also log the current setting to the console. We can access that via ``self._settings``,
|
||||
which is a little settings manager OctoPrint conveniently injects into our Plugin when we include the :class:`~octoprint.plugin.SettingsPlugin`
|
||||
mixin.
|
||||
|
||||
Let's take a look at how all that would look in our plugin's ``__init__.py``:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 8, 10, 12-13
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.SettingsPlugin):
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_implementations__ = [HelloWorldPlugin()]
|
||||
|
||||
Restart OctoPrint. You should see something like this::
|
||||
|
||||
2015-01-30 11:41:06,058 - octoprint.plugins.helloworld - INFO - Hello World! (more: https://en.wikipedia.org/wiki/Hello_world)
|
||||
|
||||
So far so good. But how do we now get that value into our template? We have two options, the
|
||||
static one using so called template variables and a dynamic one which retrieves that data from the backend and binds it
|
||||
into the template using `Knockout data bindings <http://knockoutjs.com/documentation/introduction.html>`_. First let's
|
||||
take a look at the static version using template variables. We already have the :class:`~octoprint.plugin.TemplatePlugin`
|
||||
mixin included in our plugin, we just need to override its method :func:`~octoprint.plugin.TemplatePlugin.get_template_vars`
|
||||
to add our URL as a template variable.
|
||||
|
||||
Adjust your plugin's ``__init__.py`` like this:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 15-16
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.SettingsPlugin):
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
|
||||
|
||||
def get_template_vars(self):
|
||||
return dict(url=self._settings.get(["url"]))
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_implementations__ = [HelloWorldPlugin()]
|
||||
|
||||
Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
|
||||
<a href="{{ plugin_helloworld_url|escape }}">Hello World!</a>
|
||||
|
||||
OctoPrint injects the template variables that your plugin defines prefixed with ``plugin_<plugin identifier>_`` into
|
||||
the template renderer, so your ``url`` got turned into ``plugin_helloworld_url`` which you can now use as a simple
|
||||
`Jinja2 Variable <http://jinja.pocoo.org/docs/dev/templates/#variables>`_ in your plugin's template.
|
||||
|
||||
Restart OctoPrint and shift-reload the page in your browser (to make sure you really get a fresh copy). The link should
|
||||
still work and point to the URL we defined as default.
|
||||
|
||||
Let's change the URL! Open up your OctoPrint instance's ``config.yaml`` file and add the following to it (if a ``plugins``
|
||||
section doesn't yet exist in the file, create it):
|
||||
|
||||
.. code-block:: yaml
|
||||
:emphasize-lines: 3-4
|
||||
|
||||
# [...]
|
||||
plugins:
|
||||
helloworld:
|
||||
url: https://de.wikipedia.org/wiki/Hallo-Welt-Programm
|
||||
# [...]
|
||||
|
||||
Restart OctoPrint. Not only should the URL displayed in the log file have changed, but also the link should now (after
|
||||
a proper shift-reload) point to the german Wikipedia node about "Hello World" programs::
|
||||
|
||||
2015-01-30 11:47:18,634 - octoprint.plugins.helloworld - INFO - Hello World! (more: https://de.wikipedia.org/wiki/Hallo-Welt-Programm)
|
||||
|
||||
Nice! But not very user friendly. We don't have any way yet to edit the URL from within OctoPrint and have to restart
|
||||
the server and reload the page every time we want a value change to take effect. Let's try adding a little settings dialog
|
||||
for our plugin in which we can edit the URL and take any changes take immediate effect.
|
||||
|
||||
First of all, we'll create the settings dialog. You might already have guessed that we'll need another template for that.
|
||||
So in your plugin's ``templates`` folder create a new file ``helloworld_settings.jinja2`` and put the following content
|
||||
into it:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('URL') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.plugins.helloworld.url">
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
Note how we access our plugin's property via ``settings.plugins.helloworld.url``. The ``settings`` observable is made
|
||||
available in the ``SettingsViewModel`` and holds the exact data structure returned from the server for all of
|
||||
OctoPrint's settings. Accessing plugin settings hence works by following the path under which they are stored in
|
||||
OctoPrint's internal settings data model (made public via the ``config.yaml``), ``plugins.<plugin identifier>.<configuration key>``.
|
||||
We'll bind our own settings dialog to the existing ``SettingsViewModel``, so this will be the way we'll access our
|
||||
property.
|
||||
|
||||
Now adjust your ``templates/helloworld_navbar.jinja2`` file to use a ``data-bind`` attribute to set the value from the
|
||||
settings view model into the ``href`` attribute of the link tag:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
|
||||
<a href="#" data-bind="attr: {href: settings.settings.plugins.helloworld.url}">Hello World!</a>
|
||||
|
||||
You might have noticed the quite ugly way to access our plugin's ``url`` property here: ``settings.settings.plugins.helloworld.url``.
|
||||
The reason for this is that we'll make our plugin use the existing ``NavigationViewModel`` which holds the
|
||||
``SettingsViewModel`` as a property called ``settings``. So to get to the ``settings`` property of the ``SettingsViewModel``
|
||||
from the ``NavigationViewModel``, we'll need to first "switch" to the ``SettingsViewModel`` using its property name. Hence
|
||||
the ugly access string.
|
||||
|
||||
If you were now to restart OctoPrint and reload the web interface, you'll get the settings dialog placed just fine
|
||||
in OctoPrint's settings, and the link would also still show up in the navigation bar, but both the input field of the
|
||||
settings dialog as well as the link's ``href`` attribute would not show our link. The reason for this is that OctoPrint
|
||||
by default assumes that you'll want to bind your own view models to your templates and hence "unbinds" the included
|
||||
templates from the templates that are in place at the injected location already. In order to tell OctoPrint to please
|
||||
don't do this here (since we *do* want to use both ``NavigationViewModel`` and ``SettingsViewModel``), we'll need to
|
||||
override the default template configuration using the :class:`~octoprint.plugin.TemplatePlugin`s
|
||||
:func:`~octoprint.plugin.TemplatePlugin.get_template_configs` method. We'll tell OctoPrint to use no custom bindings
|
||||
for both our ``navbar`` and our ``settings`` plugin. We'll also remove the override of :func:`octoprint.plugin.TemplatePlugin.get_template_vars`
|
||||
again since we don't use that anymore:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 15-19
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.SettingsPlugin):
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="navbar", custom_bindings=False),
|
||||
dict(type="settings", custom_bindings=False)
|
||||
]
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_implementations__ = [HelloWorldPlugin()]
|
||||
|
||||
Restart OctoPrint and shift-reload your browser. Your link in the navigation bar should still point to the URL we
|
||||
defined in ``config.yaml`` earlier. Open the "Settings" and click on the new "Hello World" entry that shows up under
|
||||
"Plugins".
|
||||
|
||||
.. _fig-plugins-gettingstarted-helloworld_settings:
|
||||
.. figure:: ../images/plugins_gettingstarted_helloworld_settings.png
|
||||
:align: center
|
||||
:alt: Our "Hello World" navigation bar element in action
|
||||
|
||||
Nice! Edit the value, then click "Save". Your link in the navigation bar should now have been updated as well.
|
||||
|
||||
.. note::
|
||||
|
||||
The way we've done our data binding and how OctoPrint currently works, your link's target will update immediately
|
||||
when you update the value in the settings dialog. Even if you click Cancel instead of Save, the change will still
|
||||
be reflected in the UI but will be overwritten again by the stored data upon a reload. This is caused by OctoPrint
|
||||
not storing a copy of the settings data while it is being edited, which might be changed in the future to
|
||||
prevent this unexpected behaviour from occurring.
|
||||
|
||||
Congratulations, you've just made your Plugin configurable :)
|
||||
|
||||
More frontend fun: Adding custom javascript to your frontend components
|
||||
-----------------------------------------------------------------------
|
||||
|
||||
In the previous section we set that ``custom_bindings`` parameter to ``False`` since we wanted OctoPrint to bind the
|
||||
``SettingsViewModel`` to our settings dialog and the ``NavigationViewModel`` to our entry in the nav bar.
|
||||
|
||||
But what if we want to define our own, with more functionality that is already available? Let's take a look. We'll now
|
||||
add an additional UI component to our OctoPrint interface, a custom tab. It will act as a little internal web browser,
|
||||
showing the website behind the URL from the settings in an IFrame but also allowing the user to load a different URL
|
||||
without having to change the settings.
|
||||
|
||||
First let us create the Jinja2 template for our tab. In your plugin's ``templates`` folder create a new file
|
||||
``helloworld_tab.jinja2`` like so:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-xxlarge" data-bind="value: newUrl">
|
||||
<button class="btn btn-primary" data-bind="click: goToUrl">{{ _('Go') }}</button>
|
||||
</div>
|
||||
|
||||
|
||||
<iframe data-bind="attr: {src: currentUrl}" style="width: 100%; height: 600px; border: 1px solid #808080"></iframe>
|
||||
|
||||
Then we create a new folder in your plugin's root called ``static`` and within that folder another folder by the name of
|
||||
``js``. Finally, within that folder create a file ``helloworld.js``. Our plugin's folder structure should now
|
||||
look like this::
|
||||
|
||||
octoprint_helloworld/
|
||||
static/
|
||||
js/
|
||||
helloworld.js
|
||||
templates/
|
||||
helloworld_navbar.jinja2
|
||||
helloworld_settings.jinja2
|
||||
helloworld_tab.jinja2
|
||||
__init__.py
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
|
||||
We need to tell OctoPrint about this new static asset so that it will properly inject it into the page. For this we
|
||||
just need to subclass :class:`~octoprint.plugin.AssetPlugin` and override its method :func:`~octoprint.plugin.AssetPlugin.get_assets`
|
||||
like so:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 9,22-25
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.AssetPlugin):
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="navbar", custom_bindings=False),
|
||||
dict(type="settings", custom_bindings=False)
|
||||
]
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/helloworld.js"]
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_implementations__ = [HelloWorldPlugin()]
|
||||
|
||||
Note how we did not add another entry to the return value of :func:`~octoprint.plugin.TemplatePlugin.get_template_configs`.
|
||||
Remember how we only added those since we wanted OctoPrint to use existing bindings on our navigation bar and settings
|
||||
menu entries? We don't want this this time, and we named our tab template such that OctoPrint will pick it up automatically
|
||||
so we don't have to do anything here.
|
||||
|
||||
Then we'll create our custom `Knockout <http://knockoutjs.com/documentation/introduction.html>`_ view model in ``helloworld.js``
|
||||
like so:
|
||||
|
||||
.. code-block:: javascript
|
||||
:linenos:
|
||||
|
||||
$(function() {
|
||||
function HelloWorldViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.settings = parameters[0];
|
||||
|
||||
// this will hold the URL currently displayed by the iframe
|
||||
self.currentUrl = ko.observable();
|
||||
|
||||
// this will hold the URL entered in the text field
|
||||
self.newUrl = ko.observable();
|
||||
|
||||
// this will be called when the user clicks the "Go" button and set the iframe's URL to
|
||||
// the entered URL
|
||||
self.goToUrl = function() {
|
||||
self.currentUrl(self.newUrl());
|
||||
};
|
||||
|
||||
// This will get called before the HelloWorldViewModel gets bound to the DOM, but after its
|
||||
// dependencies have already been initialized. It is especially guaranteed that this method
|
||||
// gets called _after_ the settings have been retrieved from the OctoPrint backend and thus
|
||||
// the SettingsViewModel been properly populated.
|
||||
self.onBeforeBinding = function() {
|
||||
self.newUrl(self.settings.settings.plugins.helloworld.url());
|
||||
self.goToUrl();
|
||||
}
|
||||
}
|
||||
|
||||
// This is how our plugin registers itself with the application, by adding some configuration
|
||||
// information to the global variable OCTOPRINT_VIEWMODELS
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
// This is the constructor to call for instantiating the plugin
|
||||
HelloWorldViewModel,
|
||||
|
||||
// This is a list of dependencies to inject into the plugin, the order which you request
|
||||
// here is the order in which the dependencies will be injected into your view model upon
|
||||
// instantiation via the parameters argument
|
||||
["settingsViewModel"],
|
||||
|
||||
// Finally, this is the list of selectors for all elements we want this view model to be bound to.
|
||||
["#tab_plugin_helloworld"]
|
||||
]);
|
||||
});
|
||||
|
||||
Take a close look at lines 31 to 42. This is how our plugin tells OctoPrint about our new view model, how to
|
||||
instantiate it, which dependencies to inject and to which elements in the final page to bind. Since we want to access
|
||||
the URL from the settings of our plugin, we'll have OctoPrint inject the ``SettingsViewModel`` into our own view model,
|
||||
which is registered within OctoPrint under the name ``settingsViewModel``. We'll only bind to our custom tab
|
||||
for now, which OctoPrint will make available in a container with the id ``tab_plugin_helloworld`` (unless otherwise
|
||||
configured).
|
||||
|
||||
Our view model defines two observables: ``newUrl``, which we bound to the input field in our template, and ``currentUrl``
|
||||
which we bound to the ``src`` attribute of the "browser iframe" in our template. There's also a function ``goToUrl``
|
||||
which we bound to the click event of the "Go" button in our template.
|
||||
|
||||
Restart OctoPrint and shift-reload the browser. You should see a shiny new "Hello World" tab right at the end of the
|
||||
tab bar. Click on it!
|
||||
|
||||
.. _fig-plugins-gettingstarted-helloworld_tab:
|
||||
.. figure:: ../images/plugins_gettingstarted_helloworld_tab.png
|
||||
:align: center
|
||||
:alt: Our "Hello World" tab in action
|
||||
|
||||
The desktop version of that article looks a bit squished in there, so let's enter ``https://de.m.wikipedia.org/wiki/Hallo-Welt-Programm``
|
||||
into the input field and click the "Go" button. The page inside the iframe should be replaced with the mobile version
|
||||
of the same article.
|
||||
|
||||
Style matters: Injecting custom CSS into the page
|
||||
-------------------------------------------------
|
||||
|
||||
So it appears that this stuff is working great already. Only one thing is a bit ugly, let's take another look at
|
||||
our ``helloworld_tab.jinja2``:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
:emphasize-lines: 6
|
||||
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-xxlarge" data-bind="value: newUrl">
|
||||
<button class="btn btn-primary" data-bind="click: goToUrl">{{ _('Go') }}</button>
|
||||
</div>
|
||||
|
||||
<iframe data-bind="attr: {src: currentUrl}" style="width: 100%; height: 600px; border: 1px solid #808080"></iframe>
|
||||
|
||||
We hardcoded some ``style`` on our ``iframe`` in line 6, to make it look a bit better. It would be nicer if that was actually
|
||||
located inside a stylesheet instead of directly inside our HTML template. Of course that's no problem, we'll just
|
||||
add a CSS file to our plugin's provided static assets.
|
||||
|
||||
First we'll create a new folder within our plugin's ``static`` folder called ``css`` and within that folders a file
|
||||
``helloworld.css``. Our plugin's file structure should now look like this::
|
||||
|
||||
octoprint_helloworld/
|
||||
static/
|
||||
css/
|
||||
helloworld.css
|
||||
js/
|
||||
helloworld.js
|
||||
templates/
|
||||
helloworld_navbar.jinja2
|
||||
helloworld_settings.jinja2
|
||||
helloworld_tab.jinja2
|
||||
__init__.py
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
|
||||
|
||||
Put something like the following into ``helloworld.css``:
|
||||
|
||||
.. code-block:: css
|
||||
:linenos:
|
||||
|
||||
#tab_plugin_helloworld {
|
||||
iframe {
|
||||
width: 100%;
|
||||
height: 600px;
|
||||
border: 1px solid #808080;
|
||||
}
|
||||
}
|
||||
|
||||
Don't forget to remove the ``style`` attribute from the ``iframe`` tag in ``helloworld_tab.jinja2``:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
:emphasize-lines: 6
|
||||
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-xxlarge" data-bind="value: newUrl">
|
||||
<button class="btn btn-primary" data-bind="click: goToUrl">{{ _('Go') }}</button>
|
||||
</div>
|
||||
|
||||
<iframe data-bind="attr: {src: currentUrl}"></iframe>
|
||||
|
||||
Then adjust our plugin's ``__init__.py`` so that the :func:`~octoprint.plugin.AssetPlugin.get_assets` method returns
|
||||
a reference to our CSS file:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 26
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.AssetPlugin):
|
||||
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="navbar", custom_bindings=False),
|
||||
dict(type="settings", custom_bindings=False)
|
||||
]
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/helloworld.js"],
|
||||
css=["css/helloworld.css"]
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_implementations__ = [HelloWorldPlugin()]
|
||||
|
||||
Restart OctoPrint, shift-reload your browser and take a look. Everything should still look like before, but now
|
||||
OctoPrint linked to our stylesheet and the style information for the ``iframe`` is taken from that instead of
|
||||
hardcoded in our template. Way better!
|
||||
|
||||
Now, if you had something more complicated than just the couple of line of CSS we used here, you might want to use
|
||||
something like LESS for generating your CSS from. If you use `LESS <http://lesscss.org/>`_, which is what OctoPrint
|
||||
uses for that purpose, you can even put OctoPrint into a mode where it directly uses your LESS files instead of the
|
||||
generated CSS files (and compiles them on the fly in your browser using `lessjs <http://lesscss.org/#client-side-usage>`_),
|
||||
which makes development so much easier. Let's try that, so you know how it works for future bigger projects.
|
||||
|
||||
Add another folder to our ``static`` folder called ``less`` and within that create a file ``helloworld.less``. Put
|
||||
into that the same content as into our CSS file. Compile that LESS file to CSS [#f1]_, overwriting our old ``helloworld.css``
|
||||
in the process. The folder structure of our plugin should now look like this::
|
||||
|
||||
octoprint_helloworld/
|
||||
static/
|
||||
css/
|
||||
helloworld.css
|
||||
js/
|
||||
helloworld.js
|
||||
less/
|
||||
helloworld.less
|
||||
templates/
|
||||
helloworld_navbar.jinja2
|
||||
helloworld_settings.jinja2
|
||||
helloworld_tab.jinja2
|
||||
__init__.py
|
||||
README.md
|
||||
requirements.txt
|
||||
setup.py
|
||||
|
||||
|
||||
Then adjust our returned assets to include our LESS file as well:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 27
|
||||
:linenos:
|
||||
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.AssetPlugin):
|
||||
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
dict(type="navbar", custom_bindings=False),
|
||||
dict(type="settings", custom_bindings=False)
|
||||
]
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/helloworld.js"],
|
||||
css=["css/helloworld.css"],
|
||||
less=["less/helloworld.less"]
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_implementations__ = [HelloWorldPlugin()]
|
||||
|
||||
|
||||
and enable LESS mode by adjusting one of OctoPrint's ``devel`` flags via the ``config.yaml`` file:
|
||||
|
||||
.. code-block:: yaml
|
||||
:emphasize-lines: 2-3
|
||||
|
||||
# [...]
|
||||
devel:
|
||||
stylesheet: less
|
||||
# [...]
|
||||
|
||||
Restart OctoPrint and shift-reload. Your "Hello World" tab should still look like before. Take a look at the site's
|
||||
source code. In the ``head`` section of the page you'll see that instead of your ``helloworld.css`` OctoPrint now
|
||||
embedded the ``helloworld.less`` file instead:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
:emphasize-lines: 7
|
||||
|
||||
<head>
|
||||
<!-- [...] -->
|
||||
<link href="/static/less/octoprint.less" rel="stylesheet/less" type="text/css" media="screen">
|
||||
|
||||
<!-- Plugin files -->
|
||||
<!-- [...] -->
|
||||
<link href="/plugin_assets/helloworld/less/helloworld.less" rel="stylesheet/less" type="text/css" media="screen">
|
||||
<!-- [...] -->
|
||||
<!-- /Plugin files -->
|
||||
|
||||
<script src="/static/js/lib/less.min.js" type="text/javascript"></script>
|
||||
<!-- [...] -->
|
||||
</head>
|
||||
|
||||
Switch your config back to CSS mode by either removing the ``stylesheet`` setting we just added to ``config.yaml`` or
|
||||
setting it to ``css``, e.g.
|
||||
|
||||
.. code-block:: yaml
|
||||
:emphasize-lines: 3
|
||||
|
||||
# [...]
|
||||
devel:
|
||||
stylesheet: css
|
||||
# [...]
|
||||
|
||||
Restart and shift-reload and take another look at the ``head``:
|
||||
|
||||
.. code-block:: html
|
||||
:linenos:
|
||||
:emphasize-lines: 7
|
||||
|
||||
<head>
|
||||
<!-- [...] -->
|
||||
<link href="/static/css/octoprint.css" rel="stylesheet" type="text/css" media="screen">
|
||||
|
||||
<!-- Plugin files -->
|
||||
<!-- [...] -->
|
||||
<link href="/plugin_assets/helloworld/css/helloworld.css" rel="stylesheet" type="text/css" media="screen">
|
||||
<!-- [...] -->
|
||||
<!-- /Plugin files -->
|
||||
<!-- [...] -->
|
||||
</head>
|
||||
|
||||
Now the CSS file is linked and no trace of the LESS links is left in the source. This should help to speed up your development
|
||||
tremendously when you have to work with complex stylesheets, just don't forgot to check the generated CSS file in with
|
||||
the rest of your plugin or people will miss it when trying to run your plugin!
|
||||
|
||||
.. note::
|
||||
|
||||
If your plugin only provides CSS files, OctoPrint will detect this when switched to LESS mode and include your
|
||||
CSS files instead of any non-existing LESS files. So you don't really *have* to use LESS if you don't want, but
|
||||
as soon as you need it just switch over.
|
||||
|
||||
The same thing works the other way around too btw. If your plugin only provides LESS files, OctoPrint will link to
|
||||
those and add lessjs to the page as well. Please keep in mind though that also providing CSS files is the cleaner
|
||||
way.
|
||||
|
||||
Where do we go from here?
|
||||
-------------------------
|
||||
|
||||
You've now seen how easy it is to add functionality to OctoPrint with this little tutorial. You can find the full
|
||||
source code of the little Hello World plugin we built together here `on Github <https://github.com/OctoPrint/Plugin-Examples/tree/master/helloworld>`_.
|
||||
|
||||
But I want to invite you to dive deeper into OctoPrint's plugin system. To get an idea of all the other various plugin types
|
||||
you haven't seen yet, :ref:`take a look at the available plugin mixins <sec-plugins-mixins>`.
|
||||
|
||||
For some insight on how to create plugins that react to various events within OctoPrint,
|
||||
`the Growl Plugin <https://github.com/OctoPrint/OctoPrint-Growl>`_ might be a good example to learn from. For how to
|
||||
add support for a slicer, OctoPrint's own bundled `CuraEngine plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_
|
||||
might give some hints. For extending OctoPrint's interface, the `NavbarTemp plugin <https://github.com/imrahil/OctoPrint-NavbarTemp>`_
|
||||
might show what's possible with a few lines of code already. Finally, just take a look at the
|
||||
`list of available plugins <https://github.com/foosel/OctoPrint/wiki#plugins>`_ on the OctoPrint wiki if you are
|
||||
looking for examples.
|
||||
|
||||
.. rubric:: Footnotes
|
||||
|
||||
.. [#f1] Refer to the `LESS documentation <http://lesscss.org/#using-less>`_ on how to do that. If you are developing
|
||||
your plugin under Windows you might also want to give `WinLESS <http://winless.org/>`_ a look which will run
|
||||
in the background and keep your CSS files up to date with your various project's LESS files automatically.
|
||||
@@ -0,0 +1,8 @@
|
||||
.. _sec-plugins-hooks:
|
||||
|
||||
Available plugin hooks
|
||||
======================
|
||||
|
||||
.. todo::
|
||||
|
||||
Needs to be documented
|
||||
@@ -1,61 +1,23 @@
|
||||
.. _sec-plugins:
|
||||
|
||||
#####################
|
||||
Plugins Documentation
|
||||
#####################
|
||||
|
||||
.. contents::
|
||||
#######
|
||||
Plugins
|
||||
#######
|
||||
|
||||
Starting with OctoPrint 1.2.0, there's now a plugin system in place which allows to individually
|
||||
extend OctoPrint's functionality.
|
||||
|
||||
Right now plugins can be used to extend OctoPrint's settings dialog, to execute specific tasks on server startup and
|
||||
shutdown or to provide custom (API) endpoints with special functionality. More plugin types are planned for the future.
|
||||
Right now plugins can be used to extend OctoPrint's web interface, to execute specific tasks on server startup and
|
||||
shutdown, to provide custom (API) endpoints with special functionality, to react on system events or to add support for
|
||||
additional slicers. More plugin types are planned for the future.
|
||||
|
||||
.. _sec-plugins-installation:
|
||||
.. toctree::
|
||||
:maxdepth: 3
|
||||
|
||||
Installing Plugins
|
||||
==================
|
||||
|
||||
Plugins can be installed either by unpacking them into one of the configured plugin folders (regularly those are
|
||||
``<octoprint-root>/plugins`` and ``~/.octoprint/plugins`` or by installing them as regular python modules via ``pip``.
|
||||
Please refer to the documentation of the plugin for installations instructions.
|
||||
|
||||
The latter is the more common case since all currently published plugins not bundled with OctoPrint can and should be installed
|
||||
this way.
|
||||
|
||||
For a plugin available on the Python Package Index (PyPi), the process is as simple as issuing a
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pip install <plugin_name>
|
||||
|
||||
For plugins not available on PyPi, you'll have to give ``pip`` an URL from which to install the package (e.g. the URL to
|
||||
a ZIP file of the current master branch of a Github repository hosting a plugin, or even a ``git+https`` URL), example:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pip install https://github.com/OctoPrint/OctoPrint-Growl/archive/master.zip
|
||||
|
||||
See `the pip install documentation <http://pip.readthedocs.org/en/latest/reference/pip_install.html>`_ for what URL
|
||||
types are possible.
|
||||
|
||||
.. _sec-plugins-available:
|
||||
|
||||
Available Plugins
|
||||
=================
|
||||
|
||||
Currently there's no such thing as a centralized plugin repository for available plugins.
|
||||
|
||||
Plugins may be found in the lists provided in `the OctoPrint wiki <https://github.com/foosel/OctoPrint/wiki#plugins>`_
|
||||
and on the `OctoPrint organization Github page <https://github.com/OctoPrint>`_.
|
||||
|
||||
.. _sec-plugins-developing:
|
||||
|
||||
Developing Plugins
|
||||
==================
|
||||
|
||||
.. todo::
|
||||
|
||||
A section on how to develop plugins yourself, including a tutorial creating an exemplatory plugin as well as
|
||||
a documentation of the plugin API, will be added in the near future.
|
||||
using.rst
|
||||
gettingstarted.rst
|
||||
infrastructure.rst
|
||||
templates.rst
|
||||
distributing.rst
|
||||
mixins.rst
|
||||
hooks.rst
|
||||
@@ -0,0 +1,70 @@
|
||||
.. _sec-plugins-infrastructure:
|
||||
|
||||
Plugin Infrastructure
|
||||
=====================
|
||||
|
||||
.. _sec-plugins-infrastructure-controlproperties:
|
||||
|
||||
Control Properties
|
||||
------------------
|
||||
|
||||
``__plugin_name__``
|
||||
Name of your plugin, optional, overrides the name specified in ``setup.py`` if provided.
|
||||
``__plugin_version__``
|
||||
Version of your plugin, optional, overrides the version specified in ``setup.py`` if provided.
|
||||
``__plugin_description__``
|
||||
Description of your plugin, optional, overrides the description specified in ``setup.py`` if provided.
|
||||
``__plugin_author__``
|
||||
Author of your plugin, optional, overrides the author specified in ``setup.py`` if provided.
|
||||
``__plugin_url__``
|
||||
URL of the webpage of your plugin, e.g. the Github repository, optional, overrides the URL specified in ``setup.py`` if
|
||||
provided.
|
||||
``__plugin_license__``
|
||||
License of your plugin, optional, overrides the license specified in ``setup.py`` if provided.
|
||||
``__plugin_implementations__``
|
||||
Instances of one or more of the various :ref:`plugin mixins <sec-plugins-mixins>`
|
||||
``__plugin_hooks__``
|
||||
Handlers for one or more of the various :ref:`plugin hooks <sec-plugins-hooks>`
|
||||
``__plugin_check__``
|
||||
Method called upon discovery of the plugin by the plugin subsystem, should return ``True`` if the
|
||||
plugin can be instantiated later on, ``False`` if there are reasons why not, e.g. if dependencies
|
||||
are missing.
|
||||
``__plugin_init__``
|
||||
Method called upon initializing of the plugin by the plugin subsystem, can be used to instantiate
|
||||
plugin implementations, connecting them to hooks etc.
|
||||
|
||||
.. _sec-plugins-infrastructure-injections:
|
||||
|
||||
Injected Properties
|
||||
-------------------
|
||||
|
||||
``self._identifier``
|
||||
The plugin's identifier.
|
||||
``self._plugin_name``
|
||||
The plugin's name, as taken from either the ``__plugin_name__`` control property or the package info.
|
||||
``self._plugin_version``
|
||||
The plugin's version, as taken from either the ``__plugin_version__`` control property or the package info.
|
||||
``self._basefolder``
|
||||
The plugin's base folder where it's installed. Can be used to refer to files relative to the plugin's installation
|
||||
location, e.g. included scripts, templates or assets.
|
||||
``self._logger``
|
||||
A `python logger instance <https://docs.python.org/2/library/logging.html>`_ logging to the log target
|
||||
``octoprint.plugin.<plugin identifier>``.
|
||||
``self._settings``
|
||||
The plugin's personalized settings manager, injected only into plugins that include the :class:`SettingsPlugin` mixin.
|
||||
``self._plugin_manager``
|
||||
OctoPrint's plugin manager.
|
||||
``self._printer_profile_manager``
|
||||
OctoPrint's printer profile manager.
|
||||
``self._event_bus``
|
||||
OctoPrint's event bus.
|
||||
``self._analysis_queue``
|
||||
OctoPrint's analysis queue for analyzing GCODEs or other files.
|
||||
``self._slicing_manager``
|
||||
OctoPrint's slicing manager.
|
||||
``self._file_manager``
|
||||
OctoPrint's file manager.
|
||||
``self._printer``
|
||||
OctoPrint's printer management object.
|
||||
``self._app_session_manager``
|
||||
OctoPrint's application session manager.
|
||||
@@ -0,0 +1,101 @@
|
||||
.. _sec-plugins-mixins:
|
||||
|
||||
Available plugin mixins
|
||||
=======================
|
||||
|
||||
The following plugin mixins are currently available:
|
||||
|
||||
.. contents::
|
||||
:local:
|
||||
|
||||
Please note that all plugin mixins inherit from :class:`~octoprint.plugin.core.Plugin` and
|
||||
:class:`~octoprint.plugin.types.OctoPrintPlugin`, which also provide attributes of interest to plugin developers.
|
||||
|
||||
.. _sec-plugins-mixins-startupplugin:
|
||||
|
||||
StartupPlugin
|
||||
-------------
|
||||
|
||||
.. autoclass:: octoprint.plugin.StartupPlugin
|
||||
:members:
|
||||
|
||||
.. _sec-plugins-mixins-shutdownplugin:
|
||||
|
||||
ShutdownPlugin
|
||||
--------------
|
||||
|
||||
.. autoclass:: octoprint.plugin.ShutdownPlugin
|
||||
:members:
|
||||
|
||||
.. _sec-plugins-mixins-settingsplugin:
|
||||
|
||||
SettingsPlugin
|
||||
--------------
|
||||
|
||||
.. autoclass:: octoprint.plugin.SettingsPlugin
|
||||
:members:
|
||||
|
||||
.. _sec-plugins-mixins-assetplugin:
|
||||
|
||||
AssetPlugin
|
||||
-----------
|
||||
|
||||
.. autoclass:: octoprint.plugin.AssetPlugin
|
||||
:members:
|
||||
|
||||
.. _sec-plugins-mixins-templateplugin:
|
||||
|
||||
TemplatePlugin
|
||||
--------------
|
||||
|
||||
.. autoclass:: octoprint.plugin.TemplatePlugin
|
||||
:members:
|
||||
|
||||
.. _sec-plugins-mixins-simpleapiplugin:
|
||||
|
||||
SimpleApiPlugin
|
||||
---------------
|
||||
|
||||
.. autoclass:: octoprint.plugin.SimpleApiPlugin
|
||||
:members:
|
||||
|
||||
.. _sec-plugins-mixins-blueprintplugin:
|
||||
|
||||
BlueprintPlugin
|
||||
---------------
|
||||
|
||||
.. autoclass:: octoprint.plugin.BlueprintPlugin
|
||||
:members:
|
||||
|
||||
.. _sec-plugins-mixins-eventhandlerplugin:
|
||||
|
||||
EventHandlerPlugin
|
||||
------------------
|
||||
|
||||
.. autoclass:: octoprint.plugin.EventHandlerPlugin
|
||||
:members:
|
||||
|
||||
.. _sec-plugins-mixins-progressplugin:
|
||||
|
||||
ProgressPlugin
|
||||
--------------
|
||||
|
||||
.. autoclass:: octoprint.plugin.ProgressPlugin
|
||||
:members:
|
||||
|
||||
.. _sec-plugins-mixins-slicerplugin:
|
||||
|
||||
SlicerPlugin
|
||||
------------
|
||||
|
||||
.. autoclass:: octoprint.plugin.SlicerPlugin
|
||||
:members:
|
||||
|
||||
.. _sec-plugins-mixins-appplugin:
|
||||
|
||||
AppPlugin
|
||||
---------
|
||||
|
||||
.. autoclass:: octoprint.plugin.AppPlugin
|
||||
:members:
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
.. _sec-plugins-templates:
|
||||
|
||||
Templates
|
||||
=========
|
||||
|
||||
.. todo::
|
||||
|
||||
Needs to be written.
|
||||
@@ -0,0 +1,44 @@
|
||||
.. _sec-plugins-using:
|
||||
|
||||
*************
|
||||
Using Plugins
|
||||
*************
|
||||
|
||||
.. _sec-plugins-using-available:
|
||||
|
||||
Finding Plugins
|
||||
===============
|
||||
|
||||
Currently there's no such thing as a centralized plugin repository for available plugins.
|
||||
|
||||
Plugins may be found in the lists provided in `the OctoPrint wiki <https://github.com/foosel/OctoPrint/wiki#plugins>`_
|
||||
and on the `OctoPrint organization Github page <https://github.com/OctoPrint>`_.
|
||||
|
||||
.. _sec-plugins-using-installing:
|
||||
|
||||
Installing Plugins
|
||||
==================
|
||||
|
||||
Plugins can be installed either by unpacking them into one of the configured plugin folders (regularly those are
|
||||
``<octoprint-root>/plugins`` and ``~/.octoprint/plugins`` or by installing them as regular python modules via ``pip``.
|
||||
Please refer to the documentation of the plugin for installations instructions.
|
||||
|
||||
The latter is the more common case since all currently published plugins not bundled with OctoPrint can and should be installed
|
||||
this way.
|
||||
|
||||
For a plugin available on the Python Package Index (PyPi), the process is as simple as issuing a
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pip install <plugin_name>
|
||||
|
||||
For plugins not available on PyPi, you'll have to give ``pip`` an URL from which to install the package (e.g. the URL to
|
||||
a ZIP file of the current master branch of a Github repository hosting a plugin, or even a ``git+https`` URL), example:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pip install https://github.com/OctoPrint/OctoPrint-Growl/archive/master.zip
|
||||
|
||||
See `the pip install documentation <http://pip.readthedocs.org/en/latest/reference/pip_install.html>`_ for what URL
|
||||
types are possible.
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
sphinxcontrib-httpdomain
|
||||
sphinx_rtd_theme
|
||||
@@ -0,0 +1,258 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
|
||||
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
|
||||
|
||||
from sphinx.directives.code import CodeBlock
|
||||
|
||||
import sphinx.highlighting
|
||||
from sphinx.highlighting import PygmentsBridge
|
||||
from sphinx.ext import doctest
|
||||
from sphinx.util.texescape import tex_hl_escape_map_new
|
||||
|
||||
from docutils.nodes import General, FixedTextElement, literal_block, container
|
||||
from docutils.parsers.rst import directives
|
||||
|
||||
from six import text_type
|
||||
|
||||
from pygments import highlight
|
||||
from pygments.filters import VisibleWhitespaceFilter, ErrorToken
|
||||
from pygments.lexers.python import PythonConsoleLexer
|
||||
from pygments.util import ClassNotFound
|
||||
|
||||
def _merge_dict(a, b):
|
||||
"""
|
||||
Little helper to merge two dicts a and b on the fly.
|
||||
"""
|
||||
result = dict(a)
|
||||
result.update(b)
|
||||
return result
|
||||
|
||||
class literal_block_ext(General, FixedTextElement):
|
||||
"""
|
||||
Custom node which is basically the same as a :class:`literal_block`, just with whitespace support and introduced
|
||||
in order to be able to have a custom visitor.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def from_literal_block(cls, block):
|
||||
"""
|
||||
Factory method constructing an instance exactly copying all attributes over from ``block`` and settings a
|
||||
custom ``tagname``.
|
||||
"""
|
||||
new = literal_block_ext()
|
||||
for a in ("attributes", "basic_attributes", "child_text_separator", "children", "document", "known_attributes",
|
||||
"line", "list_attributes", "local_attributes", "parent", "rawsource", "source"):
|
||||
setattr(new, a, getattr(block, a))
|
||||
new.tagname = "literal_block_ext"
|
||||
return new
|
||||
|
||||
class CodeBlockExt(CodeBlock):
|
||||
"""
|
||||
This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option
|
||||
``whitespace`` which if present will enable (together with everything else in here) to render whitespace in
|
||||
code blocks.
|
||||
"""
|
||||
|
||||
option_spec = _merge_dict(CodeBlock.option_spec, dict(whitespace=directives.flag))
|
||||
|
||||
def run(self):
|
||||
# get result from parent implementation
|
||||
code_block = CodeBlock.run(self)
|
||||
|
||||
def find_and_wrap_literal_block(node):
|
||||
"""
|
||||
Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`.
|
||||
"""
|
||||
|
||||
if isinstance(node, container):
|
||||
# container node => handle all children
|
||||
children = []
|
||||
for child in node.children:
|
||||
children.append(find_and_wrap_literal_block(child))
|
||||
node.children = children
|
||||
return node
|
||||
|
||||
elif isinstance(node, literal_block):
|
||||
# literal block => replace it
|
||||
return self._wrap_literal_block(node)
|
||||
|
||||
else:
|
||||
# no idea what that is => leave it alone
|
||||
return node
|
||||
|
||||
# replace all created literal_blocks with literal_block_ext instances
|
||||
return map(find_and_wrap_literal_block, code_block)
|
||||
|
||||
def _wrap_literal_block(self, node):
|
||||
literal = literal_block_ext.from_literal_block(node)
|
||||
literal["whitespace"] = "whitespace" in self.options
|
||||
return literal
|
||||
|
||||
class PygmentsBridgeExt(object):
|
||||
"""
|
||||
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
|
||||
which calls the parent implementation for lexer selection, then
|
||||
"""
|
||||
|
||||
def __init__(self, bridge, whitespace):
|
||||
self._bridge = bridge
|
||||
self._whitespace = whitespace
|
||||
|
||||
def __getattr__(self, item):
|
||||
return getattr(self._bridge, item)
|
||||
|
||||
def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs):
|
||||
if not self._whitespace:
|
||||
return self._bridge.highlight_block(source, lang, opts=opts, warn=warn, force=force, **kwargs)
|
||||
|
||||
# We are still here => we need to basically do everything the parent implementation does (and does so in a very
|
||||
# unextensible way...), but inject the whitespace filter into the used lexer just before the highlighting run
|
||||
# and remove it afterwards so the lexer can be safely reused.
|
||||
#
|
||||
# For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to
|
||||
# include the whitespace filter.
|
||||
|
||||
class whitespace(object):
|
||||
def __init__(self, lexer):
|
||||
self._lexer = lexer
|
||||
self._orig_filters = lexer.filters
|
||||
self._orig_tabsize = lexer.tabsize
|
||||
|
||||
def __enter__(self):
|
||||
new_filters = list(self._orig_filters)
|
||||
new_filters.append(VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=self._lexer.tabsize))
|
||||
self._lexer.filters = new_filters
|
||||
self._lexer.tabsize = 0
|
||||
return self._lexer
|
||||
|
||||
def __exit__(self, type, value, traceback):
|
||||
self._lexer.filters = self._orig_filters
|
||||
self._lexer.tabsize = self._orig_tabsize
|
||||
|
||||
# Then a ton of copy-pasted code follows. Sadly, we need to do this since we have no way to inject ourselves
|
||||
# into the highlighting call otherwise - lexer selection and actual call are tightly coupled in the original
|
||||
# "highlight_block" method, with no means for external code to inject different functionality.
|
||||
#
|
||||
# Unless otherwise marked ("MODIFIED"), any code in this method after this line is copied verbatim from the
|
||||
# implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright
|
||||
# lies with the respective authors.
|
||||
|
||||
if not isinstance(source, text_type):
|
||||
source = source.decode()
|
||||
|
||||
# find out which lexer to use
|
||||
if lang in ('py', 'python'):
|
||||
if source.startswith('>>>'):
|
||||
# interactive session
|
||||
lexer = sphinx.highlighting.lexers['pycon']
|
||||
elif not force:
|
||||
# maybe Python -- try parsing it
|
||||
if self.try_parse(source):
|
||||
lexer = sphinx.highlighting.lexers['python']
|
||||
else:
|
||||
lexer = sphinx.highlighting.lexers['none']
|
||||
else:
|
||||
lexer = sphinx.highlighting.lexers['python']
|
||||
elif lang in ('python3', 'py3') and source.startswith('>>>'):
|
||||
# for py3, recognize interactive sessions, but do not try parsing...
|
||||
lexer = sphinx.highlighting.lexers['pycon3']
|
||||
elif lang == 'guess':
|
||||
try:
|
||||
lexer = sphinx.highlighting.guess_lexer(source)
|
||||
except Exception:
|
||||
lexer = sphinx.highlighting.lexers['none']
|
||||
else:
|
||||
if lang in sphinx.highlighting.lexers:
|
||||
lexer = sphinx.highlighting.lexers[lang]
|
||||
else:
|
||||
try:
|
||||
lexer = sphinx.highlighting.lexers[lang] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {})
|
||||
except ClassNotFound:
|
||||
if warn:
|
||||
warn('Pygments lexer name %r is not known' % lang)
|
||||
lexer = sphinx.highlighting.lexers['none']
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
lexer.add_filter('raiseonerror')
|
||||
|
||||
if not isinstance(source, text_type):
|
||||
source = source.decode()
|
||||
|
||||
# trim doctest options if wanted
|
||||
if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags:
|
||||
source = doctest.blankline_re.sub('', source)
|
||||
source = doctest.doctestopt_re.sub('', source)
|
||||
|
||||
# highlight via Pygments
|
||||
formatter = self._bridge.get_formatter(**kwargs)
|
||||
try:
|
||||
# MODIFIED: replaced by whitespace wrapped call
|
||||
with whitespace(lexer) as l:
|
||||
hlsource = highlight(source, l, formatter)
|
||||
# /MODIFIED
|
||||
except ErrorToken:
|
||||
# this is most probably not the selected language,
|
||||
# so let it pass unhighlighted
|
||||
|
||||
# MODIFIED: replaced by whitespace wrapped call
|
||||
with whitespace(sphinx.highlighting.lexers["none"]) as l:
|
||||
hlsource = highlight(source, l, formatter)
|
||||
# /MODIFIED
|
||||
if self._bridge.dest == 'html':
|
||||
return hlsource
|
||||
else:
|
||||
if not isinstance(hlsource, text_type): # Py2 / Pygments < 1.6
|
||||
hlsource = hlsource.decode()
|
||||
return hlsource.translate(tex_hl_escape_map_new)
|
||||
|
||||
|
||||
class whitespace_highlighter(object):
|
||||
"""
|
||||
Context manager for adapting the used highlighter on a translator for a given node's whitespace properties.
|
||||
"""
|
||||
def __init__(self, translator, node):
|
||||
self.translator = translator
|
||||
self.node = node
|
||||
|
||||
self._orig_highlighter = self.translator.highlighter
|
||||
|
||||
def __enter__(self):
|
||||
whitespace = self.node["whitespace"] if "whitespace" in self.node else False
|
||||
if whitespace:
|
||||
self.translator.highlighter = PygmentsBridgeExt(self._orig_highlighter, whitespace)
|
||||
return self.translator
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.translator.highlighter = self._orig_highlighter
|
||||
|
||||
|
||||
def visit_literal_block_ext(translator, node):
|
||||
"""
|
||||
When our custom code block is visited, we temporarily exchange the highlighter used in the translator, call the
|
||||
visitor for regular literal blocks, then switch back again.
|
||||
"""
|
||||
with whitespace_highlighter(translator, node):
|
||||
translator.visit_literal_block(node)
|
||||
|
||||
|
||||
def depart_literal_block_ext(translator, node):
|
||||
"""
|
||||
Just call the depart function for regular literal blocks.
|
||||
"""
|
||||
with whitespace_highlighter(translator, node):
|
||||
translator.depart_literal_block(node)
|
||||
|
||||
|
||||
def setup(app):
|
||||
# custom directive
|
||||
app.add_directive("code-block-ext", CodeBlockExt)
|
||||
|
||||
# custom node type
|
||||
handler = (visit_literal_block_ext, depart_literal_block_ext)
|
||||
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
|
||||
|
||||
return dict(version="0.1")
|
||||
@@ -1,15 +0,0 @@
|
||||
flask==0.9
|
||||
werkzeug==0.8.3
|
||||
tornado==3.0.2
|
||||
sockjs-tornado>=1.0.0
|
||||
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
|
||||
watchdog
|
||||
sarge
|
||||
|
||||
sphinxcontrib-httpdomain
|
||||
sphinx_rtd_theme
|
||||
@@ -1,5 +0,0 @@
|
||||
mock>=1.0.1
|
||||
nose>=1.3.0
|
||||
sphinxcontrib-httpdomain
|
||||
sphinx_rtd_theme
|
||||
po2json
|
||||
@@ -1,13 +1,10 @@
|
||||
flask==0.9
|
||||
werkzeug==0.8.3
|
||||
tornado==4.0.1
|
||||
sockjs-tornado>=1.0.0
|
||||
PyYAML==3.10
|
||||
Flask-Login==0.2.2
|
||||
Flask-Principal==0.3.5
|
||||
Flask-Babel==0.9
|
||||
pyserial
|
||||
netaddr
|
||||
watchdog
|
||||
sarge
|
||||
netifaces
|
||||
###
|
||||
# This file is only here to make sure that something like
|
||||
#
|
||||
# pip install -e .[develop]
|
||||
#
|
||||
# works as expected. Requirements can be found in setup.py in the
|
||||
# variables INSTALL_REQUIRES and EXTRA_REQUIRES.
|
||||
###
|
||||
|
||||
.
|
||||
@@ -1,7 +1,64 @@
|
||||
# coding=utf-8
|
||||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
|
||||
from setuptools import setup, find_packages, Command
|
||||
import os
|
||||
import shutil
|
||||
import glob
|
||||
import versioneer
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
# Requirements for out application
|
||||
INSTALL_REQUIRES = [
|
||||
"flask==0.9",
|
||||
"werkzeug==0.8.3",
|
||||
"tornado==4.0.1",
|
||||
"sockjs-tornado>=1.0.0",
|
||||
"PyYAML==3.10",
|
||||
"Flask-Login==0.2.2",
|
||||
"Flask-Principal==0.3.5",
|
||||
"Flask-Babel==0.9",
|
||||
"pyserial",
|
||||
"netaddr",
|
||||
"watchdog",
|
||||
"sarge>=0.1.4",
|
||||
"netifaces",
|
||||
"pylru",
|
||||
"rsa",
|
||||
"pkginfo"
|
||||
]
|
||||
|
||||
# Requirements for developing etc
|
||||
EXTRA_REQUIRES = dict(
|
||||
develop=[
|
||||
# Testing dependencies
|
||||
"mock>=1.0.1",
|
||||
"nose>=1.3.0",
|
||||
"ddt",
|
||||
|
||||
# Documentation dependencies
|
||||
"sphinx>=1.3",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinx_rtd_theme",
|
||||
|
||||
# Translation dependencies
|
||||
"po2json"
|
||||
]
|
||||
)
|
||||
|
||||
# Dependency links for any of the aforementioned dependencies
|
||||
DEPENDENCY_LINKS = []
|
||||
|
||||
# I18N setup
|
||||
I18N_MAPPING_FILE = "babel.cfg"
|
||||
I18N_DOMAIN = "messages"
|
||||
I18N_INPUT_DIRS = "."
|
||||
I18N_OUTPUT_DIR_PY = os.path.join("src", "octoprint", "translations")
|
||||
I18N_OUTPUT_DIR_JS = os.path.join("src", "octoprint", "static", "js", "i18n")
|
||||
I18N_POT_FILE = os.path.join(I18N_OUTPUT_DIR_PY, "messages.pot")
|
||||
|
||||
# Versioneer configuration
|
||||
versioneer.VCS = 'git'
|
||||
versioneer.versionfile_source = 'src/octoprint/_version.py'
|
||||
versioneer.versionfile_build = 'octoprint/_version.py'
|
||||
@@ -9,17 +66,8 @@ versioneer.tag_prefix = ''
|
||||
versioneer.parentdir_prefix = ''
|
||||
versioneer.lookupfile = '.versioneer-lookup'
|
||||
|
||||
from setuptools import setup, find_packages, Command
|
||||
import os
|
||||
import shutil
|
||||
import glob
|
||||
|
||||
I18N_MAPPING_FILE = "babel.cfg"
|
||||
I18N_DOMAIN = "messages"
|
||||
I18N_INPUT_DIRS = "."
|
||||
I18N_OUTPUT_DIR_PY = os.path.join("src", "octoprint", "translations")
|
||||
I18N_OUTPUT_DIR_JS = os.path.join("src", "octoprint", "static", "js", "i18n")
|
||||
I18N_POT_FILE = os.path.join(I18N_OUTPUT_DIR_PY, "messages.pot")
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
# Anything below here is just command setup and general setup configuration
|
||||
|
||||
def package_data_dirs(source, sub_folders):
|
||||
dirs = []
|
||||
@@ -33,6 +81,26 @@ def package_data_dirs(source, sub_folders):
|
||||
return dirs
|
||||
|
||||
|
||||
def _recursively_handle_files(directory, file_matcher, folder_handler=None, file_handler=None):
|
||||
applied_handler = False
|
||||
|
||||
for filename in os.listdir(directory):
|
||||
path = os.path.join(directory, filename)
|
||||
|
||||
if file_handler is not None and file_matcher(filename):
|
||||
file_handler(path)
|
||||
applied_handler = True
|
||||
|
||||
elif os.path.isdir(path):
|
||||
sub_applied_handler = _recursively_handle_files(path, file_matcher, folder_handler=folder_handler, file_handler=file_handler)
|
||||
if sub_applied_handler:
|
||||
applied_handler = True
|
||||
|
||||
if folder_handler is not None:
|
||||
folder_handler(path, sub_applied_handler)
|
||||
|
||||
return applied_handler
|
||||
|
||||
class CleanCommand(Command):
|
||||
description = "clean build artifacts"
|
||||
user_options = []
|
||||
@@ -45,14 +113,57 @@ class CleanCommand(Command):
|
||||
pass
|
||||
|
||||
def run(self):
|
||||
# build folder
|
||||
if os.path.exists('build'):
|
||||
print "Deleting build directory"
|
||||
shutil.rmtree('build')
|
||||
|
||||
# eggs
|
||||
eggs = glob.glob('OctoPrint*.egg-info')
|
||||
for egg in eggs:
|
||||
print "Deleting %s directory" % egg
|
||||
shutil.rmtree(egg)
|
||||
|
||||
# pyc files
|
||||
def delete_folder_if_empty(path, applied_handler):
|
||||
if not applied_handler:
|
||||
return
|
||||
if len(os.listdir(path)) == 0:
|
||||
shutil.rmtree(path)
|
||||
print "Deleted %s since it was empty" % path
|
||||
|
||||
def delete_file(path):
|
||||
os.remove(path)
|
||||
print "Deleted %s" % path
|
||||
|
||||
import fnmatch
|
||||
_recursively_handle_files(
|
||||
os.path.abspath("src"),
|
||||
lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"),
|
||||
folder_handler=delete_folder_if_empty,
|
||||
file_handler=delete_file
|
||||
)
|
||||
|
||||
# pyc files
|
||||
def delete_folder_if_empty(path, applied_handler):
|
||||
if not applied_handler:
|
||||
return
|
||||
if len(os.listdir(path)) == 0:
|
||||
shutil.rmtree(path)
|
||||
print "Deleted %s since it was empty" % path
|
||||
|
||||
def delete_file(path):
|
||||
os.remove(path)
|
||||
print "Deleted %s" % path
|
||||
|
||||
import fnmatch
|
||||
_recursively_handle_files(
|
||||
os.path.abspath("src"),
|
||||
lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"),
|
||||
folder_handler=delete_folder_if_empty,
|
||||
file_handler=delete_file
|
||||
)
|
||||
|
||||
|
||||
class NewTranslation(Command):
|
||||
description = "create a new translation"
|
||||
@@ -131,7 +242,7 @@ class RefreshTranslation(Command):
|
||||
self.babel_extract_messages.copyright_holder = "The OctoPrint Project"
|
||||
self.babel_extract_messages.finalize_options()
|
||||
|
||||
self.babel_update_messages.input_file = I18N_MAPPING_FILE
|
||||
self.babel_update_messages.input_file = I18N_POT_FILE
|
||||
self.babel_update_messages.output_dir = I18N_OUTPUT_DIR_PY
|
||||
self.babel_update_messages.locale = self.locale
|
||||
|
||||
@@ -220,11 +331,23 @@ def params():
|
||||
|
||||
packages = find_packages(where="src")
|
||||
package_dir = {"octoprint": "src/octoprint"}
|
||||
package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates', 'plugins'])}
|
||||
package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates', 'plugins', 'translations'])}
|
||||
|
||||
include_package_data = True
|
||||
zip_safe = False
|
||||
install_requires = open("requirements.txt").read().split("\n")
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
|
||||
if os.environ.get('READTHEDOCS', None) == 'True':
|
||||
# we can't tell read the docs to please perform a pip install -e .[develop], so we help
|
||||
# it a bit here by explicitly adding the development dependencies, which include our
|
||||
# documentation dependencies
|
||||
install_requires = install_requires + extras_require['develop']
|
||||
|
||||
import sys
|
||||
if sys.platform in ("linux2", "darwin"):
|
||||
install_requires += ["monotime"]
|
||||
|
||||
entry_points = {
|
||||
"console_scripts": [
|
||||
@@ -232,10 +355,6 @@ def params():
|
||||
]
|
||||
}
|
||||
|
||||
#scripts = {
|
||||
# "scripts/octoprint.init": "/etc/init.d/octoprint"
|
||||
#}
|
||||
|
||||
return locals()
|
||||
|
||||
setup(**params())
|
||||
@@ -214,7 +214,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose=False):
|
||||
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": ""}
|
||||
return {"version": dirname[len(parentdir_prefix):], "full": "", "branch": ""}
|
||||
|
||||
tag_prefix = ""
|
||||
parentdir_prefix = ""
|
||||
@@ -249,7 +249,7 @@ def parse_lookup_file(root, lookup_path=None):
|
||||
break
|
||||
return lookup
|
||||
|
||||
def get_versions(default={"version": "unknown", "full": ""}, lookup_path=None, verbose=False):
|
||||
def get_versions(default={"version": "unknown", "full": "", "branch": "unknown"}, 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
|
||||
|
||||
@@ -4,7 +4,7 @@ Generic linux daemon base class for python 3.x
|
||||
Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35
|
||||
"""
|
||||
|
||||
import sys, os, time, atexit, signal
|
||||
import sys, os, time, signal
|
||||
|
||||
class Daemon:
|
||||
"""A generic daemon class.
|
||||
@@ -53,14 +53,16 @@ class Daemon:
|
||||
os.dup2(se.fileno(), sys.stderr.fileno())
|
||||
|
||||
# write pidfile
|
||||
atexit.register(self.delpid)
|
||||
|
||||
pid = str(os.getpid())
|
||||
with open(self.pidfile,'w+') as f:
|
||||
f.write(pid + '\n')
|
||||
|
||||
def delpid(self):
|
||||
|
||||
# register listener for SIGTERM
|
||||
signal.signal(signal.SIGTERM, self.term)
|
||||
|
||||
def term(self, _signo, _stack_frame):
|
||||
os.remove(self.pidfile)
|
||||
sys.exit(0)
|
||||
|
||||
def start(self):
|
||||
"""Start the daemon."""
|
||||
|
||||
@@ -20,7 +20,7 @@ _instance = None
|
||||
|
||||
|
||||
def all_events():
|
||||
return [name for name in Events.__dict__ if not name.startswith("__")]
|
||||
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")]
|
||||
|
||||
|
||||
class Events(object):
|
||||
@@ -42,6 +42,7 @@ class Events(object):
|
||||
UPDATED_FILES = "UpdatedFiles"
|
||||
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
|
||||
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
|
||||
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
|
||||
|
||||
# SD Upload
|
||||
TRANSFER_STARTED = "TransferStarted"
|
||||
@@ -62,11 +63,13 @@ class Events(object):
|
||||
HOME = "Home"
|
||||
Z_CHANGE = "ZChange"
|
||||
WAITING = "Waiting"
|
||||
DWELL = "Dwelling"
|
||||
COOLING = "Cooling"
|
||||
ALERT = "Alert"
|
||||
CONVEYOR = "Conveyor"
|
||||
EJECT = "Eject"
|
||||
E_STOP = "EStop"
|
||||
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
|
||||
|
||||
# Timelapse
|
||||
CAPTURE_START = "CaptureStart"
|
||||
@@ -79,6 +82,10 @@ class Events(object):
|
||||
SLICING_STARTED = "SlicingStarted"
|
||||
SLICING_DONE = "SlicingDone"
|
||||
SLICING_FAILED = "SlicingFailed"
|
||||
SLICING_CANCELLED = "SlicingCancelled"
|
||||
|
||||
# Settings
|
||||
SETTINGS_UPDATED = "SettingsUpdated"
|
||||
|
||||
|
||||
def eventManager():
|
||||
@@ -103,22 +110,25 @@ class EventManager(object):
|
||||
self._worker.start()
|
||||
|
||||
def _work(self):
|
||||
while True:
|
||||
(event, payload) = self._queue.get(True)
|
||||
try:
|
||||
while True:
|
||||
(event, payload) = self._queue.get(True)
|
||||
|
||||
eventListeners = self._registeredListeners[event]
|
||||
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
|
||||
eventListeners = self._registeredListeners[event]
|
||||
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))
|
||||
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))
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=[event, payload])
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=[event, payload])
|
||||
except:
|
||||
self._logger.exception("Ooops, the event bus worker loop crashed")
|
||||
|
||||
def fire(self, event, payload=None):
|
||||
"""
|
||||
@@ -133,6 +143,15 @@ class EventManager(object):
|
||||
|
||||
self._queue.put((event, payload), 0)
|
||||
|
||||
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
|
||||
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
|
||||
# TODO v1.3.0 Remove again
|
||||
import copy
|
||||
legacy_payload = copy.deepcopy(payload)
|
||||
legacy_payload["type"] = "gcode"
|
||||
self._queue.put((event, legacy_payload), 0)
|
||||
|
||||
|
||||
def subscribe(self, event, callback):
|
||||
"""
|
||||
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
|
||||
@@ -293,7 +312,7 @@ class CommandTrigger(GenericEventListener):
|
||||
def _executeGcodeCommand(self, command):
|
||||
commands = [command]
|
||||
if isinstance(command, (list, tuple, set)):
|
||||
self.logger.debug("Executing GCode commands: %r" % command)
|
||||
self._logger.debug("Executing GCode commands: %r" % command)
|
||||
commands = list(command)
|
||||
else:
|
||||
self._logger.debug("Executing GCode command: %s" % command)
|
||||
@@ -322,7 +341,7 @@ class CommandTrigger(GenericEventListener):
|
||||
"__now": datetime.datetime.now().isoformat()
|
||||
}
|
||||
|
||||
currentData = self._printer.getCurrentData()
|
||||
currentData = self._printer.get_current_data()
|
||||
|
||||
if "currentZ" in currentData.keys() and currentData["currentZ"] is not None:
|
||||
params["__currentZ"] = str(currentData["currentZ"])
|
||||
|
||||
@@ -1,3 +1,382 @@
|
||||
# coding=utf-8
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.events import eventManager, Events
|
||||
|
||||
from .destinations import FileDestinations
|
||||
from .analysis import QueueEntry, AnalysisQueue
|
||||
from .storage import LocalFileStorage
|
||||
|
||||
extensions = dict(
|
||||
# extensions for 3d model files
|
||||
model=dict(
|
||||
stl=["stl"]
|
||||
),
|
||||
# extensions for printable machine code
|
||||
machinecode=dict(
|
||||
gcode=["gcode", "gco", "g"]
|
||||
)
|
||||
)
|
||||
|
||||
def get_extensions(type, subtree=None):
|
||||
if not subtree:
|
||||
subtree = extensions
|
||||
|
||||
for key, value in subtree.items():
|
||||
if key == type:
|
||||
return get_all_extensions(subtree=value)
|
||||
elif isinstance(value, dict):
|
||||
sub_extensions = get_extensions(type, subtree=value)
|
||||
if sub_extensions:
|
||||
return sub_extensions
|
||||
|
||||
return None
|
||||
|
||||
def get_all_extensions(subtree=None):
|
||||
if not subtree:
|
||||
subtree = extensions
|
||||
|
||||
result = []
|
||||
if isinstance(subtree, dict):
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, dict):
|
||||
result += get_all_extensions(value)
|
||||
elif isinstance(value, (list, tuple)):
|
||||
result += value
|
||||
elif isinstance(subtree, (list, tuple)):
|
||||
result = subtree
|
||||
return result
|
||||
|
||||
def get_path_for_extension(extension, subtree=None):
|
||||
if not subtree:
|
||||
subtree = extensions
|
||||
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, (list, tuple)) and extension in value:
|
||||
return [key]
|
||||
elif isinstance(value, dict):
|
||||
path = get_path_for_extension(extension, subtree=value)
|
||||
if path:
|
||||
return [key] + path
|
||||
|
||||
return None
|
||||
|
||||
all_extensions = get_all_extensions()
|
||||
|
||||
def valid_extension(extension, type=None):
|
||||
if not type:
|
||||
return extension in all_extensions
|
||||
else:
|
||||
extensions = get_extensions(type)
|
||||
if extensions:
|
||||
return extension in extensions
|
||||
|
||||
def valid_file_type(filename, type=None):
|
||||
_, extension = os.path.splitext(filename)
|
||||
extension = extension[1:].lower()
|
||||
return valid_extension(extension, type=type)
|
||||
|
||||
def get_file_type(filename):
|
||||
_, extension = os.path.splitext(filename)
|
||||
extension = extension[1:].lower()
|
||||
return get_path_for_extension(extension)
|
||||
|
||||
|
||||
class NoSuchStorage(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class FileManager(object):
|
||||
def __init__(self, analysis_queue, slicing_manager, printer_profile_manager, initial_storage_managers=None):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._analysis_queue = analysis_queue
|
||||
self._analysis_queue.register_finish_callback(self._on_analysis_finished)
|
||||
|
||||
self._storage_managers = dict()
|
||||
if initial_storage_managers:
|
||||
self._storage_managers.update(initial_storage_managers)
|
||||
|
||||
self._slicing_manager = slicing_manager
|
||||
self._printer_profile_manager = printer_profile_manager
|
||||
|
||||
import threading
|
||||
self._slicing_jobs = dict()
|
||||
self._slicing_jobs_mutex = threading.Lock()
|
||||
|
||||
self._slicing_progress_callbacks = []
|
||||
self._last_slicing_progress = None
|
||||
|
||||
self._progress_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.ProgressPlugin)
|
||||
|
||||
for storage_type, storage_manager in self._storage_managers.items():
|
||||
self._determine_analysis_backlog(storage_type, storage_manager)
|
||||
|
||||
def register_slicingprogress_callback(self, callback):
|
||||
self._slicing_progress_callbacks.append(callback)
|
||||
|
||||
def unregister_slicingprogress_callback(self, callback):
|
||||
self._slicing_progress_callbacks.remove(callback)
|
||||
|
||||
def _determine_analysis_backlog(self, storage_type, storage_manager):
|
||||
self._logger.info("Adding backlog items from {storage_type} to analysis queue".format(**locals()))
|
||||
for entry, path, printer_profile in storage_manager.analysis_backlog:
|
||||
file_type = get_file_type(path)[-1]
|
||||
|
||||
# we'll use the default printer profile for the backlog since we don't know better
|
||||
queue_entry = QueueEntry(entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=False)
|
||||
|
||||
def add_storage(self, storage_type, storage_manager):
|
||||
self._storage_managers[storage_type] = storage_manager
|
||||
self._determine_analysis_backlog(storage_type, storage_manager)
|
||||
|
||||
def remove_storage(self, type):
|
||||
if not type in self._storage_managers:
|
||||
return
|
||||
del self._storage_managers[type]
|
||||
|
||||
@property
|
||||
def slicing_enabled(self):
|
||||
return self._slicing_manager.slicing_enabled
|
||||
|
||||
@property
|
||||
def registered_slicers(self):
|
||||
return self._slicing_manager.registered_slicers
|
||||
|
||||
@property
|
||||
def default_slicer(self):
|
||||
return self._slicing_manager.default_slicer
|
||||
|
||||
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
|
||||
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
|
||||
absolute_source_path = self.path_on_disk(source_location, source_path)
|
||||
|
||||
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
|
||||
try:
|
||||
if _error:
|
||||
eventManager().fire(Events.SLICING_FAILED, {"stl": source_path, "gcode": dest_path, "reason": _error})
|
||||
elif _cancelled:
|
||||
eventManager().fire(Events.SLICING_CANCELLED, {"stl": source_path, "gcode": dest_path})
|
||||
else:
|
||||
source_meta = self.get_metadata(source_location, source_path)
|
||||
hash = source_meta["hash"]
|
||||
|
||||
class Wrapper(object):
|
||||
def __init__(self, stl_name, temp_path, hash):
|
||||
self.stl_name = stl_name
|
||||
self.temp_path = temp_path
|
||||
self.hash = hash
|
||||
|
||||
def save(self, absolute_dest_path):
|
||||
with open(absolute_dest_path, "w") as d:
|
||||
d.write(";Generated from {stl_name} {hash}\r".format(**vars(self)))
|
||||
with open(tmp_path, "r") as s:
|
||||
import shutil
|
||||
shutil.copyfileobj(s, d)
|
||||
|
||||
links = [("model", dict(name=source_path))]
|
||||
_, stl_name = self.split_path(source_location, source_path)
|
||||
file_obj = Wrapper(stl_name, temp_path, hash)
|
||||
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis)
|
||||
|
||||
end_time = time.time()
|
||||
eventManager().fire(Events.SLICING_DONE, {"stl": source_path, "gcode": dest_path, "time": end_time - start_time})
|
||||
|
||||
if callback is not None:
|
||||
if callback_args is None:
|
||||
callback_args = ()
|
||||
callback(*callback_args)
|
||||
finally:
|
||||
os.remove(tmp_path)
|
||||
|
||||
source_job_key = (source_location, source_path)
|
||||
dest_job_key = (dest_location, dest_path)
|
||||
|
||||
with self._slicing_jobs_mutex:
|
||||
if source_job_key in self._slicing_jobs:
|
||||
del self._slicing_jobs[source_job_key]
|
||||
if dest_job_key in self._slicing_jobs:
|
||||
del self._slicing_jobs[dest_job_key]
|
||||
|
||||
slicer = self._slicing_manager.get_slicer(slicer_name)
|
||||
|
||||
import time
|
||||
start_time = time.time()
|
||||
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path, "progressAvailable": slicer.get_slicer_properties()["progress_report"] if slicer else False})
|
||||
|
||||
import tempfile
|
||||
f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False)
|
||||
temp_path = f.name
|
||||
f.close()
|
||||
|
||||
with self._slicing_jobs_mutex:
|
||||
source_job_key = (source_location, source_path)
|
||||
dest_job_key = (dest_location, dest_path)
|
||||
if dest_job_key in self._slicing_jobs:
|
||||
job_slicer_name, job_absolute_source_path, job_temp_path = self._slicing_jobs[dest_job_key]
|
||||
|
||||
self._slicing_manager.cancel_slicing(job_slicer_name, job_absolute_source_path, job_temp_path)
|
||||
del self._slicing_jobs[dest_job_key]
|
||||
|
||||
self._slicing_jobs[dest_job_key] = self._slicing_jobs[source_job_key] = (slicer_name, absolute_source_path, temp_path)
|
||||
|
||||
args = (source_location, source_path, temp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args)
|
||||
return self._slicing_manager.slice(
|
||||
slicer_name,
|
||||
absolute_source_path,
|
||||
temp_path,
|
||||
profile,
|
||||
stlProcessed,
|
||||
position=position,
|
||||
callback_args=args,
|
||||
overrides=overrides,
|
||||
printer_profile_id=printer_profile_id,
|
||||
on_progress=self.on_slicing_progress,
|
||||
on_progress_args=(slicer_name, source_location, source_path, dest_location, dest_path))
|
||||
|
||||
def on_slicing_progress(self, slicer, source_location, source_path, dest_location, dest_path, _progress=None):
|
||||
if not _progress:
|
||||
return
|
||||
|
||||
progress_int = int(_progress * 100)
|
||||
if self._last_slicing_progress != progress_int:
|
||||
self._last_slicing_progress = progress_int
|
||||
for callback in self._slicing_progress_callbacks:
|
||||
try: callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
|
||||
except: self._logger.exception("Exception while pushing slicing progress")
|
||||
|
||||
if progress_int:
|
||||
def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
for name, plugin in self._progress_plugins.items():
|
||||
try:
|
||||
plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress)
|
||||
except:
|
||||
self._logger.exception("Exception while sending slicing progress to plugin %s" % name)
|
||||
|
||||
import threading
|
||||
thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int))
|
||||
thread.daemon = False
|
||||
thread.start()
|
||||
|
||||
|
||||
def get_busy_files(self):
|
||||
return self._slicing_jobs.keys()
|
||||
|
||||
def file_exists(self, destination, path):
|
||||
return self._storage(destination).file_exists(path)
|
||||
|
||||
def list_files(self, destinations=None, path=None, filter=None, recursive=None):
|
||||
if not destinations:
|
||||
destinations = self._storage_managers.keys()
|
||||
if isinstance(destinations, (str, unicode, basestring)):
|
||||
destinations = [destinations]
|
||||
|
||||
result = dict()
|
||||
for dst in destinations:
|
||||
result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive)
|
||||
return result
|
||||
|
||||
def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None):
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
absolute_path = self._storage(destination).path_on_disk(file_path)
|
||||
|
||||
if analysis is None:
|
||||
file_type = get_file_type(absolute_path)
|
||||
if file_type:
|
||||
queue_entry = QueueEntry(file_path, file_type[-1], destination, absolute_path, printer_profile)
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
else:
|
||||
self._add_analysis_result(destination, path, analysis)
|
||||
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
return file_path
|
||||
|
||||
def remove_file(self, destination, path):
|
||||
self._storage(destination).remove_file(path)
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def add_folder(self, destination, path, ignore_existing=True):
|
||||
folder_path = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
return folder_path
|
||||
|
||||
def remove_folder(self, destination, path, recursive=True):
|
||||
self._storage(destination).remove_folder(path, recursive=recursive)
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def get_metadata(self, destination, path):
|
||||
return self._storage(destination).get_metadata(path)
|
||||
|
||||
def add_link(self, destination, path, rel, data):
|
||||
self._storage(destination).add_link(path, rel, data)
|
||||
|
||||
def remove_link(self, destination, path, rel, data):
|
||||
self._storage(destination).remove_link(path, rel, data)
|
||||
|
||||
def log_print(self, destination, path, timestamp, print_time, success, printer_profile):
|
||||
try:
|
||||
if success:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
|
||||
else:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
|
||||
eventManager().fire(Events.METADATA_STATISTICS_UPDATED, dict(storage=destination, path=path))
|
||||
except NoSuchStorage:
|
||||
# if there's no storage configured where to log the print, we'll just not log it
|
||||
pass
|
||||
|
||||
def set_additional_metadata(self, destination, path, key, data, overwrite=False, merge=False):
|
||||
self._storage(destination).set_additional_metadata(path, key, data, overwrite=overwrite, merge=merge)
|
||||
|
||||
def remove_additional_metadata(self, destination, path, key):
|
||||
self._storage(destination).remove_additional_metadata(path, key)
|
||||
|
||||
def path_on_disk(self, destination, path):
|
||||
return self._storage(destination).path_on_disk(path)
|
||||
|
||||
def sanitize(self, destination, path):
|
||||
return self._storage(destination).sanitize(path)
|
||||
|
||||
def sanitize_name(self, destination, name):
|
||||
return self._storage(destination).sanitize_name(name)
|
||||
|
||||
def sanitize_path(self, destination, path):
|
||||
return self._storage(destination).sanitize_path(path)
|
||||
|
||||
def split_path(self, destination, path):
|
||||
return self._storage(destination).split_path(path)
|
||||
|
||||
def join_path(self, destination, *path):
|
||||
return self._storage(destination).join_path(*path)
|
||||
|
||||
def path_in_storage(self, destination, path):
|
||||
return self._storage(destination).path_in_storage(path)
|
||||
|
||||
def _storage(self, destination):
|
||||
if not destination in self._storage_managers:
|
||||
raise NoSuchStorage("No storage configured for destination {destination}".format(**locals()))
|
||||
return self._storage_managers[destination]
|
||||
|
||||
def _add_analysis_result(self, destination, path, result):
|
||||
if not destination in self._storage_managers:
|
||||
return
|
||||
|
||||
storage_manager = self._storage_managers[destination]
|
||||
storage_manager.set_additional_metadata(path, "analysis", result)
|
||||
|
||||
def _on_analysis_finished(self, entry, result):
|
||||
self._add_analysis_result(entry.location, entry.path, result)
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import logging
|
||||
import Queue as queue
|
||||
import os
|
||||
import threading
|
||||
import collections
|
||||
|
||||
from octoprint.events import Events, eventManager
|
||||
|
||||
import octoprint.util.gcodeInterpreter as gcodeInterpreter
|
||||
|
||||
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "path, type, location, absolute_path, printer_profile")):
|
||||
def __str__(self):
|
||||
return "{location}:{path}".format(location=self.location, path=self.path)
|
||||
|
||||
|
||||
class AnalysisQueue(object):
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._callbacks = []
|
||||
self._queues = dict(
|
||||
gcode=GcodeAnalysisQueue(self._analysis_finished)
|
||||
)
|
||||
|
||||
def register_finish_callback(self, callback):
|
||||
self._callbacks.append(callback)
|
||||
|
||||
def unregister_finish_callback(self, callback):
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def enqueue(self, entry, high_priority=False):
|
||||
if not entry.type in self._queues:
|
||||
return
|
||||
|
||||
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
|
||||
|
||||
def pause(self):
|
||||
for queue in self._queues.values():
|
||||
queue.pause()
|
||||
|
||||
def resume(self):
|
||||
for queue in self._queues.values():
|
||||
queue.resume()
|
||||
|
||||
def _analysis_finished(self, entry, result):
|
||||
for callback in self._callbacks:
|
||||
callback(entry, result)
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": entry.path, "result": result})
|
||||
|
||||
class AbstractAnalysisQueue(object):
|
||||
def __init__(self, finished_callback):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._finished_callback = finished_callback
|
||||
|
||||
self._active = threading.Event()
|
||||
self._active.set()
|
||||
|
||||
self._currentFile = None
|
||||
self._currentProgress = None
|
||||
|
||||
self._queue = queue.PriorityQueue()
|
||||
self._current = None
|
||||
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def enqueue(self, entry, high_priority=False):
|
||||
if high_priority:
|
||||
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
|
||||
prio = 0
|
||||
else:
|
||||
self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry))
|
||||
prio = 100
|
||||
|
||||
self._queue.put((prio, entry))
|
||||
|
||||
def pause(self):
|
||||
self._logger.debug("Pausing analysis")
|
||||
self._active.clear()
|
||||
if self._current is not None:
|
||||
self._logger.debug("Aborting running analysis, will restart when analyzer is resumed")
|
||||
self._do_abort()
|
||||
|
||||
def resume(self):
|
||||
self._logger.debug("Resuming analyzer")
|
||||
self._active.set()
|
||||
|
||||
def _work(self):
|
||||
aborted = None
|
||||
while True:
|
||||
if aborted is not None:
|
||||
entry = aborted
|
||||
aborted = None
|
||||
self._logger.debug("Got an aborted analysis job for entry {entry}, processing this instead of first item in queue".format(**locals()))
|
||||
else:
|
||||
(priority, entry) = self._queue.get()
|
||||
self._logger.debug("Processing entry {entry} from queue (priority {priority})".format(**locals()))
|
||||
|
||||
self._active.wait()
|
||||
|
||||
try:
|
||||
self._analyze(entry)
|
||||
self._queue.task_done()
|
||||
except gcodeInterpreter.AnalysisAborted:
|
||||
aborted = entry
|
||||
self._logger.debug("Running analysis of entry {entry} aborted".format(**locals()))
|
||||
|
||||
def _analyze(self, entry):
|
||||
path = entry.absolute_path
|
||||
if path is None or not os.path.exists(path):
|
||||
return
|
||||
|
||||
self._current = entry
|
||||
self._current_progress = 0
|
||||
|
||||
try:
|
||||
self._logger.debug("Starting analysis of {entry}".format(**locals()))
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"file": entry.path, "type": entry.type})
|
||||
result = self._do_analysis()
|
||||
self._logger.debug("Analysis of entry {entry} finished, notifying callback".format(**locals()))
|
||||
self._finished_callback(self._current, result)
|
||||
finally:
|
||||
self._current = None
|
||||
self._current_progress = None
|
||||
|
||||
def _do_analysis(self):
|
||||
return None
|
||||
|
||||
def _do_abort(self):
|
||||
pass
|
||||
|
||||
|
||||
class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
|
||||
def _do_analysis(self):
|
||||
try:
|
||||
self._gcode = gcodeInterpreter.gcode()
|
||||
self._gcode.load(self._current.absolute_path, self._current.printer_profile)
|
||||
|
||||
result = dict()
|
||||
if self._gcode.totalMoveTimeMinute:
|
||||
result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60
|
||||
if self._gcode.extrusionAmount:
|
||||
result["filament"] = dict()
|
||||
for i in range(len(self._gcode.extrusionAmount)):
|
||||
result["filament"]["tool%d" % i] = {
|
||||
"length": self._gcode.extrusionAmount[i],
|
||||
"volume": self._gcode.extrusionVolume[i]
|
||||
}
|
||||
return result
|
||||
finally:
|
||||
self._gcode = None
|
||||
|
||||
def _do_abort(self):
|
||||
if self._gcode:
|
||||
self._gcode.abort()
|
||||
@@ -1,615 +0,0 @@
|
||||
# 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 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
|
||||
|
||||
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._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(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
|
||||
|
||||
fileData = self.getFileData(filename)
|
||||
if fileData is not None and "gcodeAnalysis" in fileData.keys():
|
||||
continue
|
||||
|
||||
self._metadataAnalyzer.addFileToBacklog(filename)
|
||||
|
||||
def _onMetadataAnalysisFinished(self, filename, gcode):
|
||||
if filename is None or gcode is None:
|
||||
return
|
||||
|
||||
basename = os.path.basename(filename)
|
||||
|
||||
absolutePath = self.getAbsolutePath(basename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
analysisResult = {}
|
||||
dirty = False
|
||||
if gcode.totalMoveTimeMinute:
|
||||
analysisResult["estimatedPrintTime"] = gcode.totalMoveTimeMinute * 60
|
||||
dirty = True
|
||||
if gcode.extrusionAmount:
|
||||
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:
|
||||
metadata = self.getFileMetadata(basename)
|
||||
metadata["gcodeAnalysis"] = analysisResult
|
||||
self._metadata[basename] = metadata
|
||||
self._metadataDirty = True
|
||||
self._saveMetadata()
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": basename, "result": analysisResult})
|
||||
|
||||
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._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()
|
||||
|
||||
def _getBasicFilename(self, filename):
|
||||
if filename.startswith(self._uploadFolder):
|
||||
return filename[len(self._uploadFolder + os.path.sep):]
|
||||
else:
|
||||
return filename
|
||||
|
||||
#~~ callback handling
|
||||
|
||||
def registerCallback(self, callback):
|
||||
self._callbacks.append(callback)
|
||||
|
||||
def unregisterCallback(self, callback):
|
||||
if callback in self._callbacks:
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def _sendUpdateTrigger(self, type):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendEvent(type)
|
||||
except: pass
|
||||
|
||||
#~~ file handling
|
||||
|
||||
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
|
||||
|
||||
absolutePath = self.getAbsolutePath(file.filename, mustExist=False)
|
||||
if absolutePath is None:
|
||||
return None
|
||||
|
||||
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[filename]
|
||||
self._metadataDirty = True
|
||||
self._saveMetadata()
|
||||
|
||||
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:
|
||||
return None
|
||||
|
||||
absolutePath = self.getAbsolutePath(file.filename, mustExist=False)
|
||||
if absolutePath is None:
|
||||
return None
|
||||
|
||||
return self._getBasicFilename(absolutePath)
|
||||
|
||||
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)
|
||||
|
||||
self.removeFileFromMetadata(filename)
|
||||
|
||||
def removeFileFromMetadata(self, filename):
|
||||
if filename in self._metadata.keys():
|
||||
del self._metadata[filename]
|
||||
self._metadataDirty = True
|
||||
self._saveMetadata()
|
||||
|
||||
def getAbsolutePath(self, filename, mustExist=True):
|
||||
"""
|
||||
Returns the absolute path of the given filename in the correct upload folder.
|
||||
|
||||
Ensures that the file
|
||||
<ul>
|
||||
<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>
|
||||
|
||||
@param filename the name of the file for which to determine the absolute path
|
||||
@param mustExist if set to true, the method also checks if the file exists and is a file
|
||||
@return the absolute path of the file or None if the file is not valid
|
||||
"""
|
||||
filename = self._getBasicFilename(filename)
|
||||
|
||||
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):
|
||||
fileData = self.getFileData(osFile)
|
||||
if fileData is not None:
|
||||
files.append(fileData)
|
||||
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
|
||||
|
||||
statResult = os.stat(absolutePath)
|
||||
fileData = {
|
||||
"name": filename,
|
||||
"size": statResult.st_size,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"date": int(statResult.st_ctime)
|
||||
}
|
||||
|
||||
# enrich with additional metadata from analysis if available
|
||||
if filename in self._metadata.keys():
|
||||
for key in self._metadata[filename].keys():
|
||||
if key == "prints":
|
||||
val = self._metadata[filename][key]
|
||||
last = None
|
||||
if "last" in val and val["last"] is not None:
|
||||
last = {
|
||||
"date": val["last"]["date"],
|
||||
"success": val["last"]["success"]
|
||||
}
|
||||
if "lastPrintTime" in val["last"] and val["last"]["lastPrintTime"] is not None:
|
||||
last["lastPrintTime"] = val["last"]["lastPrintTime"]
|
||||
prints = {
|
||||
"success": val["success"],
|
||||
"failure": val["failure"],
|
||||
"last": last
|
||||
}
|
||||
fileData["prints"] = prints
|
||||
else:
|
||||
fileData[key] = self._metadata[filename][key]
|
||||
|
||||
return fileData
|
||||
|
||||
def getFileMetadata(self, filename):
|
||||
filename = self._getBasicFilename(filename)
|
||||
if filename in self._metadata.keys():
|
||||
return self._metadata[filename]
|
||||
else:
|
||||
return {
|
||||
"prints": {
|
||||
"success": 0,
|
||||
"failure": 0,
|
||||
"last": None
|
||||
}
|
||||
}
|
||||
|
||||
def setFileMetadata(self, filename, metadata):
|
||||
filename = self._getBasicFilename(filename)
|
||||
self._metadata[filename] = metadata
|
||||
self._metadataDirty = True
|
||||
|
||||
#~~ print job data
|
||||
|
||||
def printSucceeded(self, filename, printTime):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
metadata = self.getFileMetadata(filename)
|
||||
metadata["prints"]["success"] += 1
|
||||
metadata["prints"]["last"] = {
|
||||
"date": time.time(),
|
||||
"success": True
|
||||
}
|
||||
|
||||
if printTime is not None:
|
||||
metadata["prints"]["last"]["lastPrintTime"] = printTime
|
||||
|
||||
self.setFileMetadata(filename, metadata)
|
||||
self._saveMetadata()
|
||||
|
||||
def printFailed(self, filename, printTime):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
metadata = self.getFileMetadata(filename)
|
||||
metadata["prints"]["failure"] += 1
|
||||
metadata["prints"]["last"] = {
|
||||
"date": time.time(),
|
||||
"success": False
|
||||
}
|
||||
|
||||
if printTime is not None:
|
||||
metadata["prints"]["last"]["lastPrintTime"] = printTime
|
||||
|
||||
self.setFileMetadata(filename, metadata)
|
||||
self._saveMetadata()
|
||||
|
||||
def changeLastPrintSuccess(self, filename, succeeded):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
metadata = self.getFileMetadata(filename)
|
||||
if metadata is None:
|
||||
return
|
||||
|
||||
if "prints" in metadata.keys():
|
||||
if "last" in metadata.keys() and metadata["prints"]["last"] is not None:
|
||||
currentSucceeded = metadata["prints"]["last"]["success"]
|
||||
if currentSucceeded != succeeded:
|
||||
metadata["prints"]["last"]["success"] = succeeded
|
||||
if currentSucceeded:
|
||||
# last print job was counted as success but actually failed
|
||||
metadata["prints"]["success"] -= 1
|
||||
metadata["prints"]["failure"] += 1
|
||||
else:
|
||||
# last print job was counted as a failure but actually succeeded
|
||||
metadata["prints"]["success"] += 1
|
||||
metadata["prints"]["failure"] -= 1
|
||||
self.setFileMetadata(filename, metadata)
|
||||
self._saveMetadata()
|
||||
|
||||
#~~ analysis control
|
||||
|
||||
def pauseAnalysis(self):
|
||||
self._metadataAnalyzer.pause()
|
||||
|
||||
def resumeAnalysis(self):
|
||||
self._metadataAnalyzer.resume()
|
||||
|
||||
class MetadataAnalyzer:
|
||||
def __init__(self, getPathCallback, loadedCallback):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._getPathCallback = getPathCallback
|
||||
self._loadedCallback = loadedCallback
|
||||
|
||||
self._active = threading.Event()
|
||||
self._active.set()
|
||||
|
||||
self._currentFile = None
|
||||
self._currentProgress = None
|
||||
|
||||
self._queue = Queue.PriorityQueue()
|
||||
self._gcode = None
|
||||
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def addFileToQueue(self, filename):
|
||||
self._logger.debug("Adding file %s to analysis queue (high priority)" % filename)
|
||||
self._queue.put((0, filename))
|
||||
|
||||
def addFileToBacklog(self, filename):
|
||||
self._logger.debug("Adding file %s to analysis backlog (low priority)" % filename)
|
||||
self._queue.put((100, filename))
|
||||
|
||||
def working(self):
|
||||
return self.isActive() and not (self._queue.empty() and self._currentFile is None)
|
||||
|
||||
def isActive(self):
|
||||
return self._active.is_set()
|
||||
|
||||
def pause(self):
|
||||
self._logger.debug("Pausing Gcode analyzer")
|
||||
self._active.clear()
|
||||
if self._gcode is not None:
|
||||
self._logger.debug("Aborting running analysis, will restart when Gcode analyzer is resumed")
|
||||
self._gcode.abort()
|
||||
|
||||
def resume(self):
|
||||
self._logger.debug("Resuming Gcode analyzer")
|
||||
self._active.set()
|
||||
|
||||
def _work(self):
|
||||
aborted = None
|
||||
while True:
|
||||
if aborted is not None:
|
||||
filename = aborted
|
||||
aborted = None
|
||||
self._logger.debug("Got an aborted analysis job for file %s, processing this instead of first item in queue" % filename)
|
||||
else:
|
||||
(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()
|
||||
except gcodeInterpreter.AnalysisAborted:
|
||||
aborted = filename
|
||||
self._logger.debug("Running analysis of file %s aborted" % filename)
|
||||
|
||||
def _analyzeGcode(self, filename):
|
||||
path = self._getPathCallback(filename)
|
||||
if path is None or not os.path.exists(path):
|
||||
return
|
||||
|
||||
self._currentFile = filename
|
||||
self._currentProgress = 0
|
||||
|
||||
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)
|
||||
self._logger.debug("Analysis of file %s finished, notifying callback" % filename)
|
||||
self._loadedCallback(self._currentFile, self._gcode)
|
||||
finally:
|
||||
self._gcode = None
|
||||
self._currentProgress = None
|
||||
self._currentFile = None
|
||||
|
||||
def _onParsingProgress(self, progress):
|
||||
self._currentProgress = progress
|
||||
@@ -1,4 +1,18 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the
|
||||
registered plugin types.
|
||||
|
||||
.. autofunction:: plugin_manager
|
||||
|
||||
.. autofunction:: plugin_settings
|
||||
|
||||
.. autofunction:: call_plugin
|
||||
|
||||
.. autoclass:: PluginSettings
|
||||
:members:
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
@@ -6,17 +20,53 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import os
|
||||
import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
|
||||
from octoprint.plugin.types import *
|
||||
|
||||
from octoprint.util import deprecated
|
||||
|
||||
# singleton
|
||||
_instance = None
|
||||
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None):
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None):
|
||||
"""
|
||||
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
|
||||
singleton.
|
||||
|
||||
Arguments:
|
||||
init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not
|
||||
(False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError`
|
||||
will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to
|
||||
False.
|
||||
plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for
|
||||
potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and
|
||||
``src/plugins`` within OctoPrint's code base.
|
||||
plugin_types (list): A list of recognized plugin types for which to look for provided implementations. If not
|
||||
provided this defaults to the plugin types found in :mod:`octoprint.plugin.types` without
|
||||
:class:`~octoprint.plugin.OctoPrintPlugin`.
|
||||
plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided
|
||||
this defaults to the entry point ``octoprint.plugin``.
|
||||
plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this
|
||||
defaults to all plugins for which ``enabled`` is set to ``False`` in the settings.
|
||||
|
||||
Returns:
|
||||
PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin
|
||||
management tasks.
|
||||
|
||||
Raises:
|
||||
ValueError: ``init`` was True although the plugin manager was already initialized, or it was False although
|
||||
the plugin manager was not yet initialized.
|
||||
"""
|
||||
|
||||
global _instance
|
||||
if _instance is None:
|
||||
if _instance is not None:
|
||||
if init:
|
||||
raise ValueError("Plugin Manager already initialized")
|
||||
|
||||
else:
|
||||
if init:
|
||||
if plugin_folders is None:
|
||||
plugin_folders = (settings().getBaseFolder("plugins"), os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")))
|
||||
@@ -28,21 +78,81 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
SimpleApiPlugin,
|
||||
AssetPlugin,
|
||||
BlueprintPlugin,
|
||||
EventHandlerPlugin]
|
||||
EventHandlerPlugin,
|
||||
SlicerPlugin,
|
||||
AppPlugin,
|
||||
ProgressPlugin]
|
||||
if plugin_entry_points is None:
|
||||
plugin_entry_points = "octoprint.plugin"
|
||||
if plugin_disabled_list is None:
|
||||
all_plugin_settings = settings().get(["plugins"])
|
||||
plugin_disabled_list = []
|
||||
for key in all_plugin_settings:
|
||||
if "enabled" in all_plugin_settings[key] and not all_plugin_settings[key]:
|
||||
plugin_disabled_list.append(key)
|
||||
|
||||
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points)
|
||||
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points, logging_prefix="octoprint.plugins.", plugin_disabled_list=plugin_disabled_list)
|
||||
else:
|
||||
raise ValueError("Plugin Manager not initialized yet")
|
||||
return _instance
|
||||
|
||||
|
||||
def plugin_settings(plugin_key, defaults=None):
|
||||
return PluginSettings(settings(), plugin_key, defaults=defaults)
|
||||
def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
|
||||
"""
|
||||
Factory method for creating a :class:`PluginSettings` instance.
|
||||
|
||||
Arguments:
|
||||
plugin_key (string): The plugin identifier for which to create the settings instance.
|
||||
defaults (dict): The default settings for the plugin.
|
||||
get_preprocessors (dict): The getter preprocessors for the plugin.
|
||||
set_preprocessors (dict): The setter preprocessors for the plugin.
|
||||
|
||||
Returns:
|
||||
PluginSettings: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's
|
||||
settings
|
||||
"""
|
||||
return PluginSettings(settings(), plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors)
|
||||
|
||||
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None):
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None):
|
||||
"""
|
||||
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
|
||||
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
|
||||
and/or failure of each call which can be used to return individual results to the calling code.
|
||||
|
||||
Example:
|
||||
|
||||
.. sourcecode:: python
|
||||
|
||||
def my_success_callback(name, plugin, result):
|
||||
print("{name} was called successfully and returned {result!r}".format(**locals()))
|
||||
|
||||
def my_error_callback(name, plugin, exc):
|
||||
print("{name} raised an exception: {exc!s}".format(**locals()))
|
||||
|
||||
octoprint.plugin.call_plugin(
|
||||
[octoprint.plugin.StartupPlugin],
|
||||
"on_startup",
|
||||
args=(my_host, my_port),
|
||||
callback=my_success_callback,
|
||||
error_callback=my_error_callback
|
||||
)
|
||||
|
||||
Arguments:
|
||||
types (list): A list of plugin implementation types to match against.
|
||||
method (string): Name of the method to call on all matching implementations.
|
||||
args (tuple): A tuple containing the arguments to supply to the called ``method``. Optional.
|
||||
kwargs (dict): A dictionary containing the keyword arguments to supply to the called ``method``. Optional.
|
||||
callback (function): A callback to invoke after an implementation has been called successfully. Will be called
|
||||
with the three arguments ``name``, ``plugin`` and ``result``. ``name`` will be the plugin identifier,
|
||||
``plugin`` the plugin implementation instance itself and ``result`` the result returned from the
|
||||
``method`` invocation.
|
||||
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
|
||||
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
|
||||
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
|
||||
|
||||
"""
|
||||
|
||||
if not isinstance(types, (list, tuple)):
|
||||
types = [types]
|
||||
if args is None:
|
||||
@@ -53,13 +163,80 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None):
|
||||
plugins = plugin_manager().get_implementations(*types)
|
||||
for name, plugin in plugins.items():
|
||||
if hasattr(plugin, method):
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
if callback:
|
||||
callback(name, plugin, result)
|
||||
try:
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
if callback:
|
||||
callback(name, plugin, result)
|
||||
except Exception as exc:
|
||||
logging.getLogger(__name__).exception("Error while calling plugin %s" % name)
|
||||
if error_callback:
|
||||
error_callback(name, plugin, exc)
|
||||
|
||||
|
||||
class PluginSettings(object):
|
||||
def __init__(self, settings, plugin_key, defaults=None):
|
||||
"""
|
||||
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
|
||||
|
||||
It provides a couple of convenience methods for directly accessing plugin settings via the regular
|
||||
:class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations.
|
||||
|
||||
All getter and setter methods will ensure that plugin settings are stored in their correct location within the
|
||||
settings structure by modifying the supplied paths accordingly.
|
||||
|
||||
Arguments:
|
||||
settings (Settings): The :class:`~octoprint.settings.Settings` instance on which to operate.
|
||||
plugin_key (str): The plugin identifer of the plugin for which to create this instance.
|
||||
defaults (dict): The plugin's defaults settings, will be used to determine valid paths within the plugin's
|
||||
settings structure
|
||||
|
||||
.. method:: get(path, merged=False, asdict=False)
|
||||
|
||||
Retrieves a raw value from the settings for ``path``, optionally merging the raw value with the default settings
|
||||
if ``merged`` is set to True.
|
||||
|
||||
:param path: The path for which to retrieve the value.
|
||||
:type path: list, tuple
|
||||
:param boolean merged: Whether to merge the returned result with the default settings (True) or not (False,
|
||||
default).
|
||||
:returns: The retrieved settings value.
|
||||
:rtype: object
|
||||
|
||||
.. method:: get_int(path)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``int``.
|
||||
|
||||
.. method:: get_float(path)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``float``.
|
||||
|
||||
.. method:: get_boolean(path)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``boolean``.
|
||||
|
||||
.. method:: set(path, value, force=False)
|
||||
|
||||
Sets the raw value on the settings for ``path``.
|
||||
|
||||
:param path: The path for which to retrieve the value.
|
||||
:type path: list, tuple
|
||||
:param object value: The value to set.
|
||||
:param boolean force: If set to True, the modified configuration will even be written back to disk if
|
||||
the value didn't change.
|
||||
|
||||
.. method:: set_int(path, value, force=False)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it.
|
||||
|
||||
.. method:: set_float(path, value, force=False)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it.
|
||||
|
||||
.. method:: set_boolean(path, value, force=False)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it.
|
||||
"""
|
||||
|
||||
def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
|
||||
self.settings = settings
|
||||
self.plugin_key = plugin_key
|
||||
|
||||
@@ -68,6 +245,16 @@ class PluginSettings(object):
|
||||
self.defaults = dict(plugins=dict())
|
||||
self.defaults["plugins"][plugin_key] = defaults
|
||||
|
||||
if get_preprocessors is None:
|
||||
get_preprocessors = dict()
|
||||
self.get_preprocessors = dict(plugins=dict())
|
||||
self.get_preprocessors["plugins"][plugin_key] = get_preprocessors
|
||||
|
||||
if set_preprocessors is None:
|
||||
set_preprocessors = dict()
|
||||
self.set_preprocessors = dict(plugins=dict())
|
||||
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
|
||||
|
||||
def prefix_path(path):
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
@@ -84,38 +271,172 @@ class PluginSettings(object):
|
||||
result.extend(args_after)
|
||||
return result
|
||||
|
||||
def add_defaults_to_kwargs(kwargs):
|
||||
kwargs.update(dict(defaults=self.defaults))
|
||||
def add_getter_kwargs(kwargs):
|
||||
kwargs.update(defaults=self.defaults, preprocessors=self.get_preprocessors)
|
||||
return kwargs
|
||||
|
||||
self.access_methods = {
|
||||
'get': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getInt': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getFloat': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getBoolean': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'set': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setInt': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setFloat': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setBoolean': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs))
|
||||
}
|
||||
def add_setter_kwargs(kwargs):
|
||||
kwargs.update(defaults=self.defaults, preprocessors=self.set_preprocessors)
|
||||
return kwargs
|
||||
|
||||
def globalGet(self, path):
|
||||
return self.settings.get(path)
|
||||
self.access_methods = dict(
|
||||
get =("get", prefix_path_in_args, add_getter_kwargs),
|
||||
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
|
||||
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
|
||||
get_boolean=("getBoolean", prefix_path_in_args, add_getter_kwargs),
|
||||
set =("set", prefix_path_in_args, add_setter_kwargs),
|
||||
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
|
||||
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
|
||||
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs)
|
||||
)
|
||||
self.deprecated_access_methods = dict(
|
||||
getInt ="get_int",
|
||||
getFloat ="get_float",
|
||||
getBoolean="get_boolean",
|
||||
setInt ="set_int",
|
||||
setFloat ="set_float",
|
||||
setBoolean="set_boolean"
|
||||
)
|
||||
|
||||
def globalGetInt(self, path):
|
||||
return self.settings.getInt(path)
|
||||
def global_get(self, path, **kwargs):
|
||||
"""
|
||||
Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this
|
||||
to access global settings outside of your plugin.
|
||||
|
||||
def globalGetFloat(self, path):
|
||||
return self.settings.getFloat(path)
|
||||
Directly forwards to :func:`octoprint.settings.Settings.get`.
|
||||
"""
|
||||
return self.settings.get(path, **kwargs)
|
||||
|
||||
def globalGetBoolean(self, path):
|
||||
return self.settings.getBoolean(path)
|
||||
def global_get_int(self, path, **kwargs):
|
||||
"""
|
||||
Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getInt`.
|
||||
"""
|
||||
return self.settings.getInt(path, **kwargs)
|
||||
|
||||
def global_get_float(self, path, **kwargs):
|
||||
"""
|
||||
Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getFloat`.
|
||||
"""
|
||||
return self.settings.getFloat(path, **kwargs)
|
||||
|
||||
def global_get_boolean(self, path, **kwargs):
|
||||
"""
|
||||
Like :func:`global_get` but directly orwards to :func:`octoprint.settings.Settings.getBoolean`.
|
||||
"""
|
||||
return self.settings.getBoolean(path, **kwargs)
|
||||
|
||||
def global_set(self, path, value, **kwargs):
|
||||
"""
|
||||
Setter for modifying settings not managed by the plugin itself on the core settings structure. Use this
|
||||
to modify global settings outside of your plugin.
|
||||
|
||||
Directly forwards to :func:`octoprint.settings.Settings.set`.
|
||||
"""
|
||||
self.settings.set(path, value, **kwargs)
|
||||
|
||||
def global_set_int(self, path, value, **kwargs):
|
||||
"""
|
||||
Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setInt`.
|
||||
"""
|
||||
self.settings.setInt(path, value, **kwargs)
|
||||
|
||||
def global_set_float(self, path, value, **kwargs):
|
||||
"""
|
||||
Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setFloat`.
|
||||
"""
|
||||
self.settings.setFloat(path, value, **kwargs)
|
||||
|
||||
def global_set_boolean(self, path, value, **kwargs):
|
||||
"""
|
||||
Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setBoolean`.
|
||||
"""
|
||||
self.settings.setBoolean(path, value, **kwargs)
|
||||
|
||||
def global_get_basefolder(self, folder_type, **kwargs):
|
||||
"""
|
||||
Retrieves a globally defined basefolder of the given ``folder_type``. Directly forwards to
|
||||
:func:`octoprint.settings.Settings.getBaseFolder`.
|
||||
"""
|
||||
return self.settings.getBaseFolder(folder_type, **kwargs)
|
||||
|
||||
def get_plugin_logfile_path(self, postfix=None):
|
||||
"""
|
||||
Retrieves the path to a logfile specifically for the plugin. If ``postfix`` is not supplied, the logfile
|
||||
will be named ``plugin_<plugin identifier>.log`` and located within the configured ``logs`` folder. If a
|
||||
postfix is supplied, the name will be ``plugin_<plugin identifier>_<postfix>.log`` at the same location.
|
||||
|
||||
Plugins may use this for specific logging tasks. For example, a :class:`~octoprint.plugin.SlicingPlugin` might
|
||||
want to create a log file for logging the output of the slicing engine itself if some debug flag is set.
|
||||
|
||||
Arguments:
|
||||
postfix (str): Postfix of the logfile for which to create the path. If set, the file name of the log file
|
||||
will be ``plugin_<plugin identifier>_<postfix>.log``, if not it will be
|
||||
``plugin_<plugin identifier>.log``.
|
||||
|
||||
Returns:
|
||||
str: Absolute path to the log file, directly usable by the plugin.
|
||||
"""
|
||||
filename = "plugin_" + self.plugin_key
|
||||
if postfix is not None:
|
||||
filename += "_" + postfix
|
||||
filename += ".log"
|
||||
return os.path.join(self.settings.getBaseFolder("logs"), filename)
|
||||
|
||||
def __getattr__(self, item):
|
||||
if item in self.access_methods and hasattr(self.settings, item) and callable(getattr(self.settings, item)):
|
||||
orig_item = getattr(self.settings, item)
|
||||
args_mapper, kwargs_mapper = self.access_methods[item]
|
||||
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
|
||||
if item in all_access_methods:
|
||||
decorator = None
|
||||
if item in self.deprecated_access_methods:
|
||||
new = self.deprecated_access_methods[item]
|
||||
decorator = deprecated("{old} has been renamed to {new}".format(old=item, new=new), stacklevel=2)
|
||||
item = new
|
||||
|
||||
return lambda *args, **kwargs: orig_item(*args_mapper(args), **kwargs_mapper(kwargs))
|
||||
else:
|
||||
return getattr(self.settings, item)
|
||||
settings_name, args_mapper, kwargs_mapper = self.access_methods[item]
|
||||
if hasattr(self.settings, settings_name) and callable(getattr(self.settings, settings_name)):
|
||||
orig_func = getattr(self.settings, settings_name)
|
||||
if decorator is not None:
|
||||
orig_func = decorator(orig_func)
|
||||
|
||||
def _func(*args, **kwargs):
|
||||
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
|
||||
_func.__name__ = item
|
||||
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
|
||||
|
||||
return _func
|
||||
|
||||
return getattr(self.settings, item)
|
||||
|
||||
##~~ deprecated methods follow
|
||||
|
||||
# TODO: Remove with release of 1.2.0
|
||||
|
||||
globalGet = deprecated("globalGet has been renamed to global_get",
|
||||
includedoc="Replaced by :func:`global_get`",
|
||||
since="1.2.0-dev-546")(global_get)
|
||||
globalGetInt = deprecated("globalGetInt has been renamed to global_get_int",
|
||||
includedoc="Replaced by :func:`global_get_int`",
|
||||
since="1.2.0-dev-546")(global_get_int)
|
||||
globalGetFloat = deprecated("globalGetFloat has been renamed to global_get_float",
|
||||
includedoc="Replaced by :func:`global_get_float`",
|
||||
since="1.2.0-dev-546")(global_get_float)
|
||||
globalGetBoolean = deprecated("globalGetBoolean has been renamed to global_get_boolean",
|
||||
includedoc="Replaced by :func:`global_get_boolean`",
|
||||
since="1.2.0-dev-546")(global_get_boolean)
|
||||
globalSet = deprecated("globalSet has been renamed to global_set",
|
||||
includedoc="Replaced by :func:`global_set`",
|
||||
since="1.2.0-dev-546")(global_set)
|
||||
globalSetInt = deprecated("globalSetInt has been renamed to global_set_int",
|
||||
includedoc="Replaced by :func:`global_set_int`",
|
||||
since="1.2.0-dev-546")(global_set_int)
|
||||
globalSetFloat = deprecated("globalSetFloat has been renamed to global_set_float",
|
||||
includedoc="Replaced by :func:`global_set_float`",
|
||||
since="1.2.0-dev-546")(global_set_float)
|
||||
globalSetBoolean = deprecated("globalSetBoolean has been renamed to global_set_boolean",
|
||||
includedoc="Replaced by :func:`global_set_boolean`",
|
||||
since="1.2.0-dev-546")(global_set_boolean)
|
||||
globalGetBaseFolder = deprecated("globalGetBaseFolder has been renamed to global_get_basefolder",
|
||||
includedoc="Replaced by :func:`global_get_basefolder`",
|
||||
since="1.2.0-dev-546")(global_get_basefolder)
|
||||
getPluginLogfilePath = deprecated("getPluginLogfilePath has been renamed to get_plugin_logfile_path",
|
||||
includedoc="Replaced by :func:`get_plugin_logfile_path`",
|
||||
since="1.2.0-dev-546")(get_plugin_logfile_path)
|
||||
@@ -1,4 +1,16 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
In this module resides the core data structures and logic of the plugin system. It is implemented in an OctoPrint-agnostic
|
||||
way and could be extracted into a separate Python module in the future.
|
||||
|
||||
.. autoclass:: PluginManager
|
||||
|
||||
.. autoclass:: PluginInfo
|
||||
|
||||
.. autoclass:: Plugin
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
@@ -13,6 +25,15 @@ import logging
|
||||
|
||||
|
||||
class PluginInfo(object):
|
||||
"""
|
||||
The :class:`PluginInfo` class wraps all available information about a registered plugin.
|
||||
|
||||
This includes its meta data (like name, description, version, etc) as well as the actual plugin extensions like
|
||||
implementations, hooks and helpers.
|
||||
|
||||
It works on Python module objects and extracts the relevant data from those via accessing the
|
||||
:ref:`control properties <sec-plugins-infrastructure-controlproperties>`.
|
||||
"""
|
||||
|
||||
attr_name = '__plugin_name__'
|
||||
|
||||
@@ -20,6 +41,12 @@ class PluginInfo(object):
|
||||
|
||||
attr_version = '__plugin_version__'
|
||||
|
||||
attr_author = '__plugin_author__'
|
||||
|
||||
attr_url = '__plugin_url__'
|
||||
|
||||
attr_license = '__plugin_license__'
|
||||
|
||||
attr_hooks = '__plugin_hooks__'
|
||||
|
||||
attr_implementations = '__plugin_implementations__'
|
||||
@@ -30,12 +57,20 @@ class PluginInfo(object):
|
||||
|
||||
attr_init = '__plugin_init__'
|
||||
|
||||
def __init__(self, key, location, instance, version=None):
|
||||
def __init__(self, key, location, instance, name=None, version=None, description=None, author=None, url=None, license=None):
|
||||
self.key = key
|
||||
self.location = location
|
||||
self.instance = instance
|
||||
self.origin = None
|
||||
self.enabled = True
|
||||
self.bundled = False
|
||||
|
||||
self._name = name
|
||||
self._version = version
|
||||
self._description = description
|
||||
self._author = author
|
||||
self._url = url
|
||||
self._license = license
|
||||
|
||||
def __str__(self):
|
||||
return "{name} ({version})".format(name=self.name, version=self.version if self.version else "unknown")
|
||||
@@ -58,15 +93,27 @@ class PluginInfo(object):
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_name, default=None)
|
||||
return self._get_instance_attribute(self.__class__.attr_name, defaults=(self._name, self.key))
|
||||
|
||||
@property
|
||||
def description(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_description, default=None)
|
||||
return self._get_instance_attribute(self.__class__.attr_description, default=self._description)
|
||||
|
||||
@property
|
||||
def version(self):
|
||||
return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=None)
|
||||
return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=self._version)
|
||||
|
||||
@property
|
||||
def author(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_author, default=self._author)
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_url, default=self._url)
|
||||
|
||||
@property
|
||||
def license(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_license, default=self._license)
|
||||
|
||||
@property
|
||||
def hooks(self):
|
||||
@@ -88,17 +135,29 @@ class PluginInfo(object):
|
||||
def init(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_init, default=lambda: True)
|
||||
|
||||
def _get_instance_attribute(self, attr, default=None):
|
||||
def _get_instance_attribute(self, attr, default=None, defaults=None):
|
||||
if not hasattr(self.instance, attr):
|
||||
if defaults is not None:
|
||||
for value in defaults:
|
||||
if value is not None:
|
||||
return value
|
||||
return default
|
||||
return getattr(self.instance, attr)
|
||||
|
||||
|
||||
class PluginManager(object):
|
||||
"""
|
||||
The :class:`PluginManager` is the central component for finding, loading and accessing plugins provided to the
|
||||
system.
|
||||
|
||||
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=None):
|
||||
It is able to discover plugins both through possible file system locations as well as customizable entry points.
|
||||
"""
|
||||
|
||||
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
if logging_prefix is None:
|
||||
logging_prefix = ""
|
||||
if plugin_disabled_list is None:
|
||||
plugin_disabled_list = []
|
||||
|
||||
@@ -106,23 +165,37 @@ class PluginManager(object):
|
||||
self.plugin_types = plugin_types
|
||||
self.plugin_entry_points = plugin_entry_points
|
||||
self.plugin_disabled_list = plugin_disabled_list
|
||||
self.logging_prefix = logging_prefix
|
||||
|
||||
self.plugins = dict()
|
||||
self.plugin_hooks = defaultdict(list)
|
||||
self.plugin_implementations = defaultdict(list)
|
||||
self.plugin_implementations = defaultdict(set)
|
||||
self.plugin_implementations_by_type = defaultdict(list)
|
||||
|
||||
self.disabled_plugins = dict()
|
||||
|
||||
self.registered_clients = []
|
||||
|
||||
self.reload_plugins()
|
||||
|
||||
def _find_plugins(self):
|
||||
plugins = dict()
|
||||
disabled_plugins = dict()
|
||||
if self.plugin_folders:
|
||||
self._add_plugins_from_folders(self.plugin_folders, plugins)
|
||||
self._add_plugins_from_folders(self.plugin_folders, plugins, disabled_plugins)
|
||||
if self.plugin_entry_points:
|
||||
self._add_plugins_from_entry_points(self.plugin_entry_points, plugins)
|
||||
return plugins
|
||||
self._add_plugins_from_entry_points(self.plugin_entry_points, plugins, disabled_plugins)
|
||||
return plugins, disabled_plugins
|
||||
|
||||
def _add_plugins_from_folders(self, folders, plugins):
|
||||
def _add_plugins_from_folders(self, folders, plugins, disabled_plugins):
|
||||
for folder in folders:
|
||||
readonly = False
|
||||
if isinstance(folder, (list, tuple)):
|
||||
if len(folder) == 2:
|
||||
folder, readonly = folder
|
||||
else:
|
||||
continue
|
||||
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
continue
|
||||
@@ -137,22 +210,27 @@ class PluginManager(object):
|
||||
else:
|
||||
continue
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
# plugin is disabled, ignore it
|
||||
continue
|
||||
|
||||
if key in plugins:
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
plugin = self._load_plugin_from_module(key, folder=folder)
|
||||
if plugin:
|
||||
plugins[key] = plugin
|
||||
plugin.origin = ("folder", folder)
|
||||
if readonly:
|
||||
plugin.bundled = True
|
||||
|
||||
return plugins
|
||||
if self._is_plugin_disabled(key):
|
||||
plugin.enabled = False
|
||||
disabled_plugins[key] = plugin
|
||||
else:
|
||||
plugins[key] = plugin
|
||||
|
||||
def _add_plugins_from_entry_points(self, groups, plugins):
|
||||
return plugins, disabled_plugins
|
||||
|
||||
def _add_plugins_from_entry_points(self, groups, plugins, disabled_plugins):
|
||||
import pkg_resources
|
||||
import pkginfo
|
||||
|
||||
if not isinstance(groups, (list, tuple)):
|
||||
groups = [groups]
|
||||
@@ -163,42 +241,62 @@ class PluginManager(object):
|
||||
module_name = entry_point.module_name
|
||||
version = entry_point.dist.version
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
# plugin is disabled, ignore it
|
||||
continue
|
||||
|
||||
if key in plugins:
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
plugin = self._load_plugin_from_module(key, module_name=module_name, version=version)
|
||||
kwargs = dict(module_name=module_name, version=version)
|
||||
try:
|
||||
module_pkginfo = pkginfo.Installed(module_name)
|
||||
except:
|
||||
self.logger.exception("Something went wrong while retrieving package info data for module %s" % module_name)
|
||||
else:
|
||||
kwargs.update(dict(
|
||||
name=module_pkginfo.name,
|
||||
summary=module_pkginfo.summary,
|
||||
author=module_pkginfo.author,
|
||||
url=module_pkginfo.home_page,
|
||||
license=module_pkginfo.license
|
||||
))
|
||||
|
||||
plugin = self._load_plugin_from_module(key, **kwargs)
|
||||
if plugin:
|
||||
plugins[key] = plugin
|
||||
plugin.origin = ("entry_point", group, module_name)
|
||||
|
||||
return plugins
|
||||
if self._is_plugin_disabled(key):
|
||||
plugin.enabled = False
|
||||
disabled_plugins[key] = plugin
|
||||
else:
|
||||
plugins[key] = plugin
|
||||
|
||||
def _load_plugin_from_module(self, key, folder=None, module_name=None, version=None):
|
||||
return plugins, disabled_plugins
|
||||
|
||||
def _load_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None):
|
||||
# TODO error handling
|
||||
if folder:
|
||||
module = imp.find_module(key, [folder])
|
||||
elif module_name:
|
||||
module = imp.find_module(module_name)
|
||||
else:
|
||||
try:
|
||||
if folder:
|
||||
module = imp.find_module(key, [folder])
|
||||
elif module_name:
|
||||
module = imp.find_module(module_name)
|
||||
else:
|
||||
return None
|
||||
except:
|
||||
self.logger.warn("Could not locate plugin {key}")
|
||||
return None
|
||||
|
||||
plugin = self._load_plugin(key, *module, version=version)
|
||||
plugin = self._load_plugin(key, *module, name=name, version=version, summary=summary, author=author, url=url, license=license)
|
||||
if plugin:
|
||||
if plugin.check():
|
||||
return plugin
|
||||
else:
|
||||
self.logger.warn("Plugin \"{plugin}\" did not pass check, disabling it".format(plugin=str(plugin)))
|
||||
self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin)))
|
||||
return None
|
||||
|
||||
|
||||
def _load_plugin(self, key, f, filename, description, version=None):
|
||||
|
||||
def _load_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None):
|
||||
try:
|
||||
instance = imp.load_module(key, f, filename, description)
|
||||
return PluginInfo(key, filename, instance, version=version)
|
||||
return PluginInfo(key, filename, instance, name=name, version=version, description=summary, author=author, url=url, license=license)
|
||||
except:
|
||||
self.logger.exception("Error loading plugin {key}, disabling it".format(key=key))
|
||||
return None
|
||||
@@ -208,26 +306,82 @@ class PluginManager(object):
|
||||
|
||||
def reload_plugins(self):
|
||||
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(folders=", ".join(self.plugin_folders)))
|
||||
self.plugins = self._find_plugins()
|
||||
self.plugins, self.disabled_plugins = self._find_plugins()
|
||||
|
||||
for name, plugin in self.plugins.items():
|
||||
# initialize the plugin
|
||||
plugin.init()
|
||||
try:
|
||||
# initialize the plugin
|
||||
plugin.init()
|
||||
|
||||
# evaluate registered hooks
|
||||
for hook, callback in plugin.hooks.items():
|
||||
self.plugin_hooks[hook].append((name, callback))
|
||||
# evaluate registered hooks
|
||||
for hook, callback in plugin.hooks.items():
|
||||
self.plugin_hooks[hook].append((name, callback))
|
||||
|
||||
# evaluate registered implementations
|
||||
for plugin_type in self.plugin_types:
|
||||
implementations = plugin.get_implementations(plugin_type)
|
||||
self.plugin_implementations[plugin_type] += ( (name, implementation) for implementation in implementations )
|
||||
# evaluate registered implementations
|
||||
for plugin_type in self.plugin_types:
|
||||
implementations = plugin.get_implementations(plugin_type)
|
||||
self.plugin_implementations_by_type[plugin_type] += ( (name, implementation) for implementation in implementations )
|
||||
|
||||
plugin_implementations = plugin.get_implementations()
|
||||
if len(plugin_implementations):
|
||||
self.plugin_implementations[name].update(plugin_implementations)
|
||||
except:
|
||||
self.logger.exception("There was an error loading plugin %s" % name)
|
||||
|
||||
self.log_registered_plugins()
|
||||
|
||||
def initialize_implementations(self, additional_injects=None, additional_inject_factories=None):
|
||||
if additional_injects is None:
|
||||
additional_injects = dict()
|
||||
if additional_inject_factories is None:
|
||||
additional_inject_factories = []
|
||||
|
||||
for name, implementations in self.plugin_implementations.items():
|
||||
plugin = self.plugins[name]
|
||||
for implementation in implementations:
|
||||
try:
|
||||
kwargs = dict(additional_injects)
|
||||
|
||||
kwargs.update(dict(
|
||||
identifier=name,
|
||||
plugin_name=plugin.name,
|
||||
plugin_version=plugin.version,
|
||||
basefolder=os.path.realpath(plugin.location),
|
||||
logger=logging.getLogger(self.logging_prefix + name),
|
||||
))
|
||||
|
||||
# inject the additional_injects
|
||||
for arg, value in kwargs.items():
|
||||
setattr(implementation, "_" + arg, value)
|
||||
|
||||
# inject any injects produced in the additional_inject_factories
|
||||
for factory in additional_inject_factories:
|
||||
try:
|
||||
return_value = factory(name, implementation)
|
||||
except:
|
||||
self.logger.exception("Exception while executing injection factory %r" % factory)
|
||||
else:
|
||||
if return_value is not None:
|
||||
if isinstance(return_value, dict):
|
||||
for arg, value in return_value.items():
|
||||
setattr(implementation, "_" + arg, value)
|
||||
|
||||
implementation.initialize()
|
||||
except:
|
||||
self.logger.exception("Exception while initializing plugin")
|
||||
# TODO disable plugin!
|
||||
|
||||
self.logger.info("Initialized {count} plugin(s)".format(count=len(self.plugin_implementations)))
|
||||
|
||||
def log_registered_plugins(self):
|
||||
if len(self.plugins) <= 0:
|
||||
self.logger.info("No plugins found")
|
||||
else:
|
||||
self.logger.info("Found {count} plugin(s): {plugins}".format(count=len(self.plugins), plugins=", ".join(map(lambda x: str(x), self.plugins.values()))))
|
||||
|
||||
if len(self.disabled_plugins) > 0:
|
||||
self.logger.info("{count} plugin(s) currently disabled: {plugins}".format(count=len(self.disabled_plugins), plugins=", ".join(map(lambda x: str(x), self.disabled_plugins.values()))))
|
||||
|
||||
def get_plugin(self, name):
|
||||
if not name in self.plugins:
|
||||
return None
|
||||
@@ -235,21 +389,21 @@ class PluginManager(object):
|
||||
|
||||
def get_hooks(self, hook):
|
||||
if not hook in self.plugin_hooks:
|
||||
return []
|
||||
return dict()
|
||||
return {hook[0]: hook[1] for hook in self.plugin_hooks[hook]}
|
||||
|
||||
def get_implementations(self, *types):
|
||||
result = None
|
||||
|
||||
for t in types:
|
||||
implementations = self.plugin_implementations[t]
|
||||
implementations = self.plugin_implementations_by_type[t]
|
||||
if result is None:
|
||||
result = set(implementations)
|
||||
else:
|
||||
result = result.intersection(implementations)
|
||||
|
||||
if result is None:
|
||||
return set()
|
||||
return dict()
|
||||
return {impl[0]: impl[1] for impl in result}
|
||||
|
||||
def get_helpers(self, name, *helpers):
|
||||
@@ -263,6 +417,49 @@ class PluginManager(object):
|
||||
else:
|
||||
return all_helpers
|
||||
|
||||
def register_client(self, client):
|
||||
if client is None:
|
||||
return
|
||||
self.registered_clients.append(client)
|
||||
|
||||
def unregister_client(self, client):
|
||||
self.registered_clients.remove(client)
|
||||
|
||||
def send_plugin_message(self, plugin, data):
|
||||
for client in self.registered_clients:
|
||||
try: client.sendPluginMessage(plugin, data)
|
||||
except: self.logger.exception("Exception while sending plugin data to client")
|
||||
|
||||
|
||||
class Plugin(object):
|
||||
pass
|
||||
"""
|
||||
The parent class of all plugin implementations.
|
||||
|
||||
.. attribute:: _identifier
|
||||
|
||||
The identifier of the plugin. Injected by the plugin core system upon initialization of the implementation.
|
||||
|
||||
.. attribute:: _plugin_name
|
||||
|
||||
The name of the plugin. Injected by the plugin core system upon initialization of the implementation.
|
||||
|
||||
.. attribute:: _plugin_version
|
||||
|
||||
The version of the plugin. Injected by the plugin core system upon initialization of the implementation.
|
||||
|
||||
.. attribute:: _basefolder
|
||||
|
||||
The base folder of the plugin. Injected by the plugin core system upon initialization of the implementation.
|
||||
|
||||
.. attribute:: _logger
|
||||
|
||||
The logger instance to use, with the logging name set to the :attr:`PluginManager.logging_prefix` of the
|
||||
:class:`PluginManager` concatenated with :attr:`_identifier`. Injected by the plugin core system upon
|
||||
initialization of the implementation.
|
||||
"""
|
||||
|
||||
def initialize(self):
|
||||
"""
|
||||
Called by the plugin core after performing all injections.
|
||||
"""
|
||||
pass
|
||||
@@ -0,0 +1,421 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import flask
|
||||
import math
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.util
|
||||
import octoprint.slicing
|
||||
import octoprint.settings
|
||||
|
||||
from .profile import Profile
|
||||
|
||||
class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.StartupPlugin):
|
||||
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger("octoprint.plugins.cura")
|
||||
self._cura_logger = logging.getLogger("octoprint.plugins.cura.engine")
|
||||
|
||||
# setup job tracking across threads
|
||||
import threading
|
||||
self._slicing_commands = dict()
|
||||
self._cancelled_jobs = []
|
||||
self._job_mutex = threading.Lock()
|
||||
|
||||
##~~ StartupPlugin API
|
||||
|
||||
def on_startup(self, host, port):
|
||||
# setup our custom logger
|
||||
cura_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), maxBytes=2*1024*1024)
|
||||
cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
|
||||
cura_logging_handler.setLevel(logging.DEBUG)
|
||||
|
||||
self._cura_logger.addHandler(cura_logging_handler)
|
||||
self._cura_logger.setLevel(logging.DEBUG if self._settings.get_boolean(["debug_logging"]) else logging.CRITICAL)
|
||||
self._cura_logger.propagate = False
|
||||
|
||||
##~~ BlueprintPlugin API
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"])
|
||||
def import_cura_profile(self):
|
||||
import datetime
|
||||
import tempfile
|
||||
|
||||
from octoprint.server import slicingManager
|
||||
|
||||
input_name = "file"
|
||||
input_upload_name = input_name + "." + self._settings.global_get(["server", "uploads", "nameSuffix"])
|
||||
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
|
||||
|
||||
if input_upload_name in flask.request.values and input_upload_path in flask.request.values:
|
||||
filename = flask.request.values[input_upload_name]
|
||||
try:
|
||||
profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path])
|
||||
except Exception as e:
|
||||
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
|
||||
|
||||
elif input_name in flask.request.files:
|
||||
temp_file = tempfile.NamedTemporaryFile("wb", delete=False)
|
||||
try:
|
||||
temp_file.close()
|
||||
upload = flask.request.files[input_name]
|
||||
upload.save(temp_file.name)
|
||||
profile_dict = Profile.from_cura_ini(temp_file.name)
|
||||
except Exception as e:
|
||||
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
|
||||
finally:
|
||||
os.remove(temp_file)
|
||||
|
||||
filename = upload.filename
|
||||
|
||||
else:
|
||||
return flask.make_response("No file included", 400)
|
||||
|
||||
if profile_dict is None:
|
||||
return flask.make_response("Could not convert Cura profile", 400)
|
||||
|
||||
name, _ = os.path.splitext(filename)
|
||||
|
||||
# default values for name, display name and description
|
||||
profile_name = _sanitize_name(name)
|
||||
profile_display_name = name
|
||||
profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now()))
|
||||
profile_allow_overwrite = False
|
||||
|
||||
# overrides
|
||||
if "name" in flask.request.values:
|
||||
profile_name = flask.request.values["name"]
|
||||
if "displayName" in flask.request.values:
|
||||
profile_display_name = flask.request.values["displayName"]
|
||||
if "description" in flask.request.values:
|
||||
profile_description = flask.request.values["description"]
|
||||
if "allowOverwrite" in flask.request.values:
|
||||
from octoprint.server.api import valid_boolean_trues
|
||||
profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues
|
||||
|
||||
slicingManager.save_profile("cura",
|
||||
profile_name,
|
||||
profile_dict,
|
||||
allow_overwrite=profile_allow_overwrite,
|
||||
display_name=profile_display_name,
|
||||
description=profile_description)
|
||||
|
||||
result = dict(
|
||||
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
|
||||
displayName=profile_display_name,
|
||||
description=profile_description
|
||||
)
|
||||
r = flask.make_response(flask.jsonify(result), 201)
|
||||
r.headers["Location"] = result["resource"]
|
||||
return r
|
||||
|
||||
##~~ AssetPlugin API
|
||||
|
||||
def get_assets(self):
|
||||
return {
|
||||
"js": ["js/cura.js"],
|
||||
"less": ["less/cura.less"],
|
||||
"css": ["css/cura.css"]
|
||||
}
|
||||
|
||||
##~~ SettingsPlugin API
|
||||
|
||||
def on_settings_save(self, data):
|
||||
old_debug_logging = self._settings.get_boolean(["debug_logging"])
|
||||
|
||||
super(CuraPlugin, self).on_settings_save(data)
|
||||
|
||||
new_debug_logging = self._settings.get_boolean(["debug_logging"])
|
||||
if old_debug_logging != new_debug_logging:
|
||||
if new_debug_logging:
|
||||
self._cura_logger.setLevel(logging.DEBUG)
|
||||
else:
|
||||
self._cura_logger.setLevel(logging.CRITICAL)
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(
|
||||
cura_engine=None,
|
||||
default_profile=None,
|
||||
debug_logging=False
|
||||
)
|
||||
|
||||
##~~ SlicerPlugin API
|
||||
|
||||
def is_slicer_configured(self):
|
||||
cura_engine = self._settings.get(["cura_engine"])
|
||||
if cura_engine is not None and os.path.exists(cura_engine):
|
||||
return True
|
||||
else:
|
||||
self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine)
|
||||
|
||||
def get_slicer_properties(self):
|
||||
return dict(
|
||||
type="cura",
|
||||
name="CuraEngine",
|
||||
same_device=True,
|
||||
progress_report=True
|
||||
)
|
||||
|
||||
def get_slicer_default_profile(self):
|
||||
path = self._settings.get(["default_profile"])
|
||||
if not path:
|
||||
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "profiles", "default.profile.yaml")
|
||||
return self.get_slicer_profile(path)
|
||||
|
||||
def get_slicer_profile(self, path):
|
||||
profile_dict = self._load_profile(path)
|
||||
|
||||
display_name = None
|
||||
description = None
|
||||
if "_display_name" in profile_dict:
|
||||
display_name = profile_dict["_display_name"]
|
||||
del profile_dict["_display_name"]
|
||||
if "_description" in profile_dict:
|
||||
description = profile_dict["_description"]
|
||||
del profile_dict["_description"]
|
||||
|
||||
properties = self.get_slicer_properties()
|
||||
return octoprint.slicing.SlicingProfile(properties["type"], "unknown", profile_dict, display_name=display_name, description=description)
|
||||
|
||||
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
|
||||
new_profile = Profile.merge_profile(profile.data, overrides=overrides)
|
||||
|
||||
if profile.display_name is not None:
|
||||
new_profile["_display_name"] = profile.display_name
|
||||
if profile.description is not None:
|
||||
new_profile["_description"] = profile.description
|
||||
|
||||
self._save_profile(path, new_profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
|
||||
try:
|
||||
with self._job_mutex:
|
||||
if not profile_path:
|
||||
profile_path = self._settings.get(["default_profile"])
|
||||
if not machinecode_path:
|
||||
path, _ = os.path.splitext(model_path)
|
||||
machinecode_path = path + ".gco"
|
||||
|
||||
if position and isinstance(position, dict) and "x" in position and "y" in position:
|
||||
posX = position["x"]
|
||||
posY = position["y"]
|
||||
else:
|
||||
posX = None
|
||||
posY = None
|
||||
|
||||
if on_progress:
|
||||
if not on_progress_args:
|
||||
on_progress_args = ()
|
||||
if not on_progress_kwargs:
|
||||
on_progress_kwargs = dict()
|
||||
|
||||
self._cura_logger.info("### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
|
||||
|
||||
engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
|
||||
|
||||
executable = self._settings.get(["cura_engine"])
|
||||
if not executable:
|
||||
return False, "Path to CuraEngine is not configured "
|
||||
|
||||
working_dir, _ = os.path.split(executable)
|
||||
args = ['"%s"' % executable, '-v', '-p']
|
||||
for k, v in engine_settings.items():
|
||||
args += ["-s", '"%s=%s"' % (k, str(v))]
|
||||
args += ['-o', '"%s"' % machinecode_path, '"%s"' % model_path]
|
||||
|
||||
import sarge
|
||||
command = " ".join(args)
|
||||
self._logger.info("Running %r in %s" % (command, working_dir))
|
||||
|
||||
p = sarge.run(command, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p.wait_events()
|
||||
self._slicing_commands[machinecode_path] = p.commands[0]
|
||||
|
||||
try:
|
||||
layer_count = None
|
||||
step_factor = dict(
|
||||
inset=0,
|
||||
skin=1,
|
||||
export=2
|
||||
)
|
||||
analysis = None
|
||||
while p.returncode is None:
|
||||
line = p.stderr.readline(timeout=0.5)
|
||||
if not line:
|
||||
p.commands[0].poll()
|
||||
continue
|
||||
|
||||
self._cura_logger.debug(line.strip())
|
||||
|
||||
if on_progress is not None:
|
||||
# The Cura slicing process has three individual steps, each consisting of <layer_count> substeps:
|
||||
#
|
||||
# - inset
|
||||
# - skin
|
||||
# - export
|
||||
#
|
||||
# So each layer will be processed three times, once for each step, resulting in a total amount of
|
||||
# substeps of 3 * <layer_count>.
|
||||
#
|
||||
# The CuraEngine reports the calculated layer count and the continuous progress on stderr.
|
||||
# The layer count gets reported right at the beginning in a line of the format:
|
||||
#
|
||||
# Layer count: <layer_count>
|
||||
#
|
||||
# The individual progress per each of the three steps gets reported on stderr in a line of
|
||||
# the format:
|
||||
#
|
||||
# Progress:<step>:<current_layer>:<layer_count>
|
||||
#
|
||||
# Thus, for determining the overall progress the following formula applies:
|
||||
#
|
||||
# progress = <step_factor> * <layer_count> + <current_layer> / <layer_count> * 3
|
||||
#
|
||||
# with <step_factor> being 0 for "inset", 1 for "skin" and 2 for "export".
|
||||
|
||||
if line.startswith("Layer count:") and layer_count is None:
|
||||
try:
|
||||
layer_count = float(line[len("Layer count:"):].strip())
|
||||
except:
|
||||
pass
|
||||
|
||||
elif line.startswith("Progress:"):
|
||||
split_line = line[len("Progress:"):].strip().split(":")
|
||||
if len(split_line) == 3:
|
||||
step, current_layer, _ = split_line
|
||||
try:
|
||||
current_layer = float(current_layer)
|
||||
except:
|
||||
pass
|
||||
else:
|
||||
if not step in step_factor:
|
||||
continue
|
||||
on_progress_kwargs["_progress"] = (step_factor[step] * layer_count + current_layer) / (layer_count * 3)
|
||||
on_progress(*on_progress_args, **on_progress_kwargs)
|
||||
|
||||
elif line.startswith("Print time:"):
|
||||
try:
|
||||
print_time = int(line[len("Print time:"):].strip())
|
||||
if analysis is None:
|
||||
analysis = dict()
|
||||
analysis["estimatedPrintTime"] = print_time
|
||||
except:
|
||||
pass
|
||||
|
||||
elif line.startswith("Filament:") or line.startswith("Filament2:"):
|
||||
if line.startswith("Filament:"):
|
||||
filament_str = line[len("Filament:"):].strip()
|
||||
tool_key = "tool0"
|
||||
else:
|
||||
filament_str = line[len("Filament2:"):].strip()
|
||||
tool_key = "tool1"
|
||||
|
||||
try:
|
||||
filament = int(filament_str)
|
||||
if analysis is None:
|
||||
analysis = dict()
|
||||
if not "filament" in analysis:
|
||||
analysis["filament"] = dict()
|
||||
if not tool_key in analysis["filament"]:
|
||||
analysis["filament"][tool_key] = dict()
|
||||
analysis["filament"][tool_key]["length"] = filament
|
||||
if "filamentDiameter" in engine_settings:
|
||||
radius_in_cm = float(int(engine_settings["filamentDiameter"]) / 10000.0) / 2.0
|
||||
filament_in_cm = filament / 10.0
|
||||
analysis["filament"][tool_key]["volume"] = filament_in_cm * math.pi * radius_in_cm * radius_in_cm
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
p.close()
|
||||
|
||||
with self._job_mutex:
|
||||
if machinecode_path in self._cancelled_jobs:
|
||||
self._cura_logger.info("### Cancelled")
|
||||
raise octoprint.slicing.SlicingCancelled()
|
||||
|
||||
self._cura_logger.info("### Finished, returncode %d" % p.returncode)
|
||||
if p.returncode == 0:
|
||||
return True, dict(analysis=analysis)
|
||||
else:
|
||||
self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode)
|
||||
return False, "Got returncode %r" % p.returncode
|
||||
|
||||
except octoprint.slicing.SlicingCancelled as e:
|
||||
raise e
|
||||
except:
|
||||
self._logger.exception("Could not slice via Cura, got an unknown error")
|
||||
return False, "Unknown error, please consult the log file"
|
||||
|
||||
finally:
|
||||
with self._job_mutex:
|
||||
if machinecode_path in self._cancelled_jobs:
|
||||
self._cancelled_jobs.remove(machinecode_path)
|
||||
if machinecode_path in self._slicing_commands:
|
||||
del self._slicing_commands[machinecode_path]
|
||||
|
||||
self._cura_logger.info("-" * 40)
|
||||
|
||||
def cancel_slicing(self, machinecode_path):
|
||||
with self._job_mutex:
|
||||
if machinecode_path in self._slicing_commands:
|
||||
self._cancelled_jobs.append(machinecode_path)
|
||||
command = self._slicing_commands[machinecode_path]
|
||||
if command is not None:
|
||||
command.terminate()
|
||||
self._logger.info("Cancelled slicing of %s" % machinecode_path)
|
||||
|
||||
def _load_profile(self, path):
|
||||
import yaml
|
||||
profile_dict = dict()
|
||||
with open(path, "r") as f:
|
||||
try:
|
||||
profile_dict = yaml.safe_load(f)
|
||||
except:
|
||||
raise IOError("Couldn't read profile from {path}".format(path=path))
|
||||
return profile_dict
|
||||
|
||||
def _save_profile(self, path, profile, allow_overwrite=True):
|
||||
if not allow_overwrite and os.path.exists(path):
|
||||
raise IOError("Cannot overwrite {path}".format(path=path))
|
||||
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
|
||||
profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
|
||||
return profile.convert_to_engine()
|
||||
|
||||
def _sanitize_name(name):
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
import string
|
||||
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
|
||||
sanitized_name = ''.join(c for c in name if c in valid_chars)
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name.lower()
|
||||
|
||||
__plugin_name__ = "CuraEngine"
|
||||
__plugin_version__ = "0.1"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
|
||||
__plugin_description__ = "Adds support for slicing via CuraEngine from within OctoPrint"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementations__ = [CuraPlugin()]
|
||||
@@ -0,0 +1,975 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import re
|
||||
|
||||
class SupportLocationTypes(object):
|
||||
NONE = "none"
|
||||
TOUCHING_BUILDPLATE = "buildplate"
|
||||
EVERYWHERE = "everywhere"
|
||||
|
||||
class SupportDualTypes(object):
|
||||
BOTH = "both"
|
||||
FIRST = "first"
|
||||
SECOND = "second"
|
||||
|
||||
class SupportTypes(object):
|
||||
GRID = "grid"
|
||||
LINES = "lines"
|
||||
|
||||
class PlatformAdhesionTypes(object):
|
||||
NONE = "none"
|
||||
BRIM = "brim"
|
||||
RAFT = "raft"
|
||||
|
||||
class MachineShapeTypes(object):
|
||||
SQUARE = "square"
|
||||
CIRCULAR = "circular"
|
||||
|
||||
class GcodeFlavors(object):
|
||||
REPRAP = "reprap"
|
||||
REPRAP_VOLUME = "reprap_volume"
|
||||
ULTIGCODE = "ultigcode"
|
||||
MAKERBOT = "makerbot"
|
||||
BFB = "bfb"
|
||||
MACH3 = "mach3"
|
||||
|
||||
|
||||
defaults = dict(
|
||||
layer_height=0.1,
|
||||
wall_thickness=0.8,
|
||||
solid_layer_thickness=0.6,
|
||||
print_temperature=[220, 0, 0, 0],
|
||||
print_bed_temperature=70,
|
||||
platform_adhesion=PlatformAdhesionTypes.NONE,
|
||||
filament_diameter=[2.85, 0, 0, 0],
|
||||
filament_flow=100.0,
|
||||
bottom_thickness=0.3,
|
||||
first_layer_width_factor=100.0,
|
||||
object_sink=0.0,
|
||||
|
||||
fill_density=20,
|
||||
solid_top=True,
|
||||
solid_bottom=True,
|
||||
fill_overlap=15,
|
||||
|
||||
# speeds
|
||||
print_speed=50.0,
|
||||
travel_speed=150.0,
|
||||
bottom_layer_speed=20.0,
|
||||
infill_speed=0.0,
|
||||
outer_shell_speed=0.0,
|
||||
inner_shell_speed=0.0,
|
||||
|
||||
# dual extrusion
|
||||
overlap_dual=0.15,
|
||||
wipe_tower=False,
|
||||
wipe_tower_volume=15,
|
||||
ooze_shield=False,
|
||||
|
||||
# retraction
|
||||
retraction_enable=True,
|
||||
retraction_speed=40.0,
|
||||
retraction_amount=4.5,
|
||||
retraction_dual_amount=16.5,
|
||||
retraction_min_travel=1.5,
|
||||
retraction_combing=True,
|
||||
retraction_minimal_extrusion=0.02,
|
||||
retraction_hop=0.0,
|
||||
|
||||
# cooling
|
||||
cool_min_layer_time=5,
|
||||
fan_enabled=True,
|
||||
fan_full_height=0.5,
|
||||
fan_speed=100,
|
||||
fan_speed_max=100,
|
||||
cool_min_feedrate=10,
|
||||
cool_head_lift=False,
|
||||
|
||||
# support
|
||||
support=SupportLocationTypes.NONE,
|
||||
support_type=SupportTypes.GRID,
|
||||
support_angle=60.0,
|
||||
support_fill_rate=15,
|
||||
support_xy_distance=0.7,
|
||||
support_z_distance=0.15,
|
||||
support_dual_extrusion=SupportDualTypes.BOTH,
|
||||
|
||||
# platform adhesion
|
||||
skirt_line_count=1,
|
||||
skirt_gap=3.0,
|
||||
skirt_minimal_length=150.0,
|
||||
brim_line_count=20,
|
||||
raft_margin=5.0,
|
||||
raft_line_spacing=3.0,
|
||||
raft_base_thickness=0.3,
|
||||
raft_base_linewidth=1.0,
|
||||
raft_interface_thickness=0.27,
|
||||
raft_interface_linewidth=0.4,
|
||||
raft_airgap=0.22,
|
||||
raft_surface_layers=2,
|
||||
|
||||
# repairing
|
||||
fix_horrible_union_all_type_a=True,
|
||||
fix_horrible_union_all_type_b=False,
|
||||
fix_horrible_use_open_bits=False,
|
||||
fix_horrible_extensive_stitching=False,
|
||||
|
||||
# extras
|
||||
spiralize=False,
|
||||
follow_surface=False,
|
||||
|
||||
machine_width=205,
|
||||
machine_depth=205,
|
||||
machine_center_is_zero=False,
|
||||
has_heated_bed=False,
|
||||
gcode_flavor=GcodeFlavors.REPRAP,
|
||||
extruder_amount=1,
|
||||
steps_per_e=0,
|
||||
start_gcode=[
|
||||
# 1 extruder
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M109 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M82 ;set extruder to absolute mode
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E3 ;extrude 3mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
""",
|
||||
# 2 extruders
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M104 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
T1 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T0 ;Switch to the first extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
""",
|
||||
# 3 extruders
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M104 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
T2 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T1 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T0 ;Switch to the first extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
""",
|
||||
# 4 extruders
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M104 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
;M109 T2 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
T3 ;Switch to the 4th extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T2 ;Switch to the 3th extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T1 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T0 ;Switch to the first extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
"""
|
||||
],
|
||||
end_gcode=[
|
||||
# 1 extruder
|
||||
""";End GCode
|
||||
M104 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
""",
|
||||
# 2 extruders
|
||||
""";End GCode
|
||||
M104 T0 S0 ;extruder heater off
|
||||
M104 T1 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
""",
|
||||
# 3 extruders
|
||||
""";End GCode
|
||||
M104 T0 S0 ;extruder heater off
|
||||
M104 T1 S0 ;extruder heater off
|
||||
M104 T2 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
""",
|
||||
# 4 extruders
|
||||
""";End GCode
|
||||
M104 T0 S0 ;extruder heater off
|
||||
M104 T1 S0 ;extruder heater off
|
||||
M104 T2 S0 ;extruder heater off
|
||||
M104 T3 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
"""
|
||||
],
|
||||
preSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders.
|
||||
;This code is added before the T(n)
|
||||
""",
|
||||
postSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders.
|
||||
;This code is added after the T(n)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
class Profile(object):
|
||||
|
||||
regex_extruder_offset = re.compile("extruder_offset_([xy])(\d)")
|
||||
regex_filament_diameter = re.compile("filament_diameter(\d?)")
|
||||
regex_print_temperature = re.compile("print_temperature(\d?)")
|
||||
regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE)
|
||||
|
||||
@classmethod
|
||||
def from_cura_ini(cls, path):
|
||||
import os
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
return None
|
||||
|
||||
import ConfigParser
|
||||
config = ConfigParser.ConfigParser()
|
||||
try:
|
||||
config.read(path)
|
||||
except:
|
||||
return None
|
||||
|
||||
arrayified_options = ["print_temperature", "filament_diameter", "start.gcode", "end.gcode"]
|
||||
translated_options = dict(
|
||||
inset0_speed="outer_shell_speed",
|
||||
insetx_speed="inner_shell_speed",
|
||||
layer0_width_factor="first_layer_width_factor",
|
||||
simple_mode="follow_surface",
|
||||
)
|
||||
translated_options["start.gcode"] = "start_gcode"
|
||||
translated_options["end.gcode"] = "end_gcode"
|
||||
value_conversions = dict(
|
||||
platform_adhesion={
|
||||
"None": PlatformAdhesionTypes.NONE,
|
||||
"Brim": PlatformAdhesionTypes.BRIM,
|
||||
"Raft": PlatformAdhesionTypes.RAFT
|
||||
},
|
||||
support={
|
||||
"None": SupportLocationTypes.NONE,
|
||||
"Touching buildplate": SupportLocationTypes.TOUCHING_BUILDPLATE,
|
||||
"Everywhere": SupportLocationTypes.EVERYWHERE
|
||||
},
|
||||
support_type={
|
||||
"Lines": SupportTypes.LINES,
|
||||
"Grid": SupportTypes.GRID
|
||||
},
|
||||
support_dual_extrusion={
|
||||
"Both": SupportDualTypes.BOTH,
|
||||
"First extruder": SupportDualTypes.FIRST,
|
||||
"Second extruder": SupportDualTypes.SECOND
|
||||
}
|
||||
)
|
||||
|
||||
result = dict()
|
||||
for section in config.sections():
|
||||
if not section in ("profile", "alterations"):
|
||||
continue
|
||||
|
||||
for option in config.options(section):
|
||||
ignored = False
|
||||
key = option
|
||||
|
||||
# try to fetch the value in the correct type
|
||||
try:
|
||||
value = config.getboolean(section, option)
|
||||
except:
|
||||
# no boolean, try int
|
||||
try:
|
||||
value = config.getint(section, option)
|
||||
except:
|
||||
# no int, try float
|
||||
try:
|
||||
value = config.getfloat(section, option)
|
||||
except:
|
||||
# no float, use str
|
||||
value = config.get(section, option)
|
||||
index = None
|
||||
|
||||
for opt in arrayified_options:
|
||||
if key.startswith(opt):
|
||||
if key == opt:
|
||||
index = 0
|
||||
else:
|
||||
try:
|
||||
# try to convert the target index, e.g. print_temperature2 => print_temperature[1]
|
||||
index = int(key[len(opt):]) - 1
|
||||
except ValueError:
|
||||
# ignore entries for which that fails
|
||||
ignored = True
|
||||
key = opt
|
||||
break
|
||||
if ignored:
|
||||
continue
|
||||
|
||||
if key in translated_options:
|
||||
# if the key has to be translated to a new value, do that now
|
||||
key = translated_options[key]
|
||||
|
||||
if key in value_conversions and value in value_conversions[key]:
|
||||
value = value_conversions[key][value]
|
||||
|
||||
if index is not None:
|
||||
# if we have an array to fill, make sure the target array exists and has the right size
|
||||
if not key in result:
|
||||
result[key] = []
|
||||
if len(result[key]) <= index:
|
||||
for n in xrange(index - len(result[key]) + 1):
|
||||
result[key].append(None)
|
||||
result[key][index] = value
|
||||
else:
|
||||
# just set the value if there's no array to fill
|
||||
result[key] = value
|
||||
|
||||
# merge it with our default settings, the imported profile settings taking precedence
|
||||
return cls.merge_profile(result)
|
||||
|
||||
|
||||
@classmethod
|
||||
def merge_profile(cls, profile, overrides=None):
|
||||
result = dict()
|
||||
for key in defaults.keys():
|
||||
r = cls.merge_profile_key(key, profile, overrides=overrides)
|
||||
if r is not None:
|
||||
result[key] = r
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def merge_profile_key(cls, key, profile, overrides=None):
|
||||
profile_value = None
|
||||
override_value = None
|
||||
|
||||
if not key in defaults:
|
||||
return None
|
||||
import copy
|
||||
result = copy.deepcopy(defaults[key])
|
||||
|
||||
if key in profile:
|
||||
profile_value = profile[key]
|
||||
if overrides and key in overrides:
|
||||
override_value = overrides[key]
|
||||
|
||||
if profile_value is None and override_value is None:
|
||||
# neither override nor profile, no need to handle this key further
|
||||
return None
|
||||
|
||||
if key in ("filament_diameter", "print_temperature", "start_gcode", "end_gcode"):
|
||||
# the array fields need some special treatment. Basically something like this:
|
||||
#
|
||||
# override_value: [None, "b"]
|
||||
# profile_value : ["a" , None, "c"]
|
||||
# default_value : ["d" , "e" , "f", "g"]
|
||||
#
|
||||
# should merge to something like this:
|
||||
#
|
||||
# ["a" , "b" , "c", "g"]
|
||||
#
|
||||
# So override > profile > default, if neither override nor profile value are available
|
||||
# the default value should just be left as is
|
||||
|
||||
for x in xrange(len(result)):
|
||||
if override_value is not None and x < len(override_value) and override_value[x] is not None:
|
||||
# we have an override value for this location, so we use it
|
||||
result[x] = override_value[x]
|
||||
elif profile_value is not None and x < len(profile_value) and profile_value[x] is not None:
|
||||
# we have a profile value for this location, so we use it
|
||||
result[x] = profile_value[x]
|
||||
|
||||
else:
|
||||
# just change the result value to the override_value if available, otherwise to the profile_value if
|
||||
# that is given, else just leave as is
|
||||
if override_value is not None:
|
||||
result = override_value
|
||||
elif profile_value is not None:
|
||||
result = profile_value
|
||||
|
||||
return result
|
||||
|
||||
def __init__(self, profile, printer_profile, posX, posY, overrides=None):
|
||||
self._profile = self.__class__.merge_profile(profile, overrides=overrides)
|
||||
self._printer_profile = printer_profile
|
||||
self._posX = posX
|
||||
self._posY = posY
|
||||
|
||||
def profile(self):
|
||||
import copy
|
||||
return copy.deepcopy(self._profile)
|
||||
|
||||
def get(self, key):
|
||||
if key in ("machine_width", "machine_depth", "machine_center_is_zero"):
|
||||
if key == "machine_width":
|
||||
return self._printer_profile["volume"]["width"]
|
||||
elif key == "machine_depth":
|
||||
return self._printer_profile["volume"]["depth"]
|
||||
elif key == "machine_height":
|
||||
return self._printer_profile["volume"]["height"]
|
||||
elif key == "machine_center_is_zero":
|
||||
return self._printer_profile["volume"]["formFactor"] == "circular"
|
||||
else:
|
||||
return None
|
||||
|
||||
elif key == "extruder_amount":
|
||||
return self._printer_profile["extruder"]["count"]
|
||||
|
||||
elif key.startswith("extruder_offset_"):
|
||||
extruder_offsets = self._printer_profile["extruder"]["offsets"]
|
||||
match = Profile.regex_extruder_offset.match(key)
|
||||
if not match:
|
||||
return 0.0
|
||||
|
||||
axis, number = match.groups()
|
||||
axis = axis.lower()
|
||||
number = int(number)
|
||||
|
||||
if not axis in ("x", "y"):
|
||||
return 0.0
|
||||
if number >= len(extruder_offsets):
|
||||
return 0.0
|
||||
|
||||
if axis == "x":
|
||||
return extruder_offsets[number][0]
|
||||
elif axis == "y":
|
||||
return extruder_offsets[number][1]
|
||||
else:
|
||||
return 0.0
|
||||
|
||||
elif key == "has_heated_bed":
|
||||
return self._printer_profile["heatedBed"]
|
||||
|
||||
elif key.startswith("filament_diameter"):
|
||||
match = Profile.regex_filament_diameter.match(key)
|
||||
if not match:
|
||||
return 0.0
|
||||
|
||||
diameters = self._get("filament_diameter")
|
||||
if not match.group(1):
|
||||
return diameters[0]
|
||||
index = int(match.group(1))
|
||||
if index >= len(diameters):
|
||||
return 0.0
|
||||
return diameters[index]
|
||||
|
||||
elif key.startswith("print_temperature"):
|
||||
match = Profile.regex_print_temperature.match(key)
|
||||
if not match:
|
||||
return 0.0
|
||||
|
||||
temperatures = self._get("print_temperature")
|
||||
if not match.group(1):
|
||||
return temperatures[0]
|
||||
index = int(match.group(1))
|
||||
if index >= len(temperatures):
|
||||
return 0.0
|
||||
return temperatures[index]
|
||||
|
||||
else:
|
||||
return self._get(key)
|
||||
|
||||
def _get(self, key):
|
||||
if key in self._profile:
|
||||
return self._profile[key]
|
||||
elif key in defaults:
|
||||
return defaults[key]
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_int(self, key, default=None):
|
||||
value = self.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
def get_float(self, key, default=None):
|
||||
value = self.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
if isinstance(value, (str, unicode, basestring)):
|
||||
value = value.replace(",", ".").strip()
|
||||
|
||||
try:
|
||||
return float(value)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
def get_boolean(self, key, default=None):
|
||||
value = self.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
elif isinstance(value, (str, unicode, basestring)):
|
||||
return value.lower() == "true" or value.lower() == "yes" or value.lower() == "on" or value == "1"
|
||||
elif isinstance(value, (int, float)):
|
||||
return value > 0
|
||||
else:
|
||||
return value == True
|
||||
|
||||
def get_microns(self, key, default=None):
|
||||
value = self.get_float(key, default=None)
|
||||
if value is None:
|
||||
return default
|
||||
return int(value * 1000)
|
||||
|
||||
def get_gcode_template(self, key):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
if key in self._profile:
|
||||
gcode = self._profile[key]
|
||||
else:
|
||||
gcode = defaults[key]
|
||||
|
||||
if key in ("start_gcode", "end_gcode"):
|
||||
return gcode[extruder_count-1]
|
||||
else:
|
||||
return gcode
|
||||
|
||||
def get_profile_string(self):
|
||||
import base64
|
||||
import zlib
|
||||
|
||||
import copy
|
||||
profile = copy.deepcopy(defaults)
|
||||
profile.update(self._profile)
|
||||
for key in ("print_temperature", "print_temperature2", "print_temperature3", "print_temperature4",
|
||||
"filament_diameter", "filament_diameter2", "filament_diameter3", "filament_diameter4"):
|
||||
profile[key] = self.get(key)
|
||||
|
||||
result = []
|
||||
for k, v in profile.items():
|
||||
if isinstance(v, (str, unicode)):
|
||||
result.append("{k}={v}".format(k=k, v=v.encode("utf-8")))
|
||||
else:
|
||||
result.append("{k}={v}".format(k=k, v=v))
|
||||
|
||||
return base64.b64encode(zlib.compress("\b".join(result), 9))
|
||||
|
||||
def replaceTagMatch(self, m):
|
||||
import time
|
||||
|
||||
pre = m.group(1)
|
||||
tag = m.group(2)
|
||||
|
||||
if tag == 'time':
|
||||
return pre + time.strftime('%H:%M:%S')
|
||||
if tag == 'date':
|
||||
return pre + time.strftime('%d-%m-%Y')
|
||||
if tag == 'day':
|
||||
return pre + ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][int(time.strftime('%w'))]
|
||||
if tag == 'profile_string':
|
||||
return pre + 'CURA_OCTO_PROFILE_STRING:%s' % (self.get_profile_string())
|
||||
|
||||
if pre == 'F' and tag == 'max_z_speed':
|
||||
f = self.get_float("travel_speed") * 60
|
||||
elif pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
|
||||
f = self.get_float(tag) * 60
|
||||
elif self.get(tag):
|
||||
f = self.get(tag)
|
||||
else:
|
||||
return '%s?%s?' % (pre, tag)
|
||||
|
||||
if (f % 1) == 0:
|
||||
return pre + str(int(f))
|
||||
|
||||
return pre + str(f)
|
||||
|
||||
def get_gcode(self, key):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
prefix = ""
|
||||
postfix = ""
|
||||
|
||||
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
|
||||
if key == "end_gcode":
|
||||
return "M25 ;Stop reading from this point on.\n;CURA_PROFILE_STRING:%s\n" % (self.get_profile_string())
|
||||
return ""
|
||||
|
||||
if key == "start_gcode":
|
||||
contents = self.get_gcode_template("start_gcode")
|
||||
|
||||
e_steps = self.get_float("steps_per_e")
|
||||
if e_steps > 0:
|
||||
prefix += "M92 E{e_steps}\n" % (e_steps)
|
||||
temp = self.get_float("print_temperature")
|
||||
|
||||
bed_temp = 0
|
||||
if self.get_boolean("has_heated_bed"):
|
||||
bed_temp = self.get_float("print_bed_temperature")
|
||||
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
|
||||
|
||||
if include_bed_temp:
|
||||
prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp)
|
||||
|
||||
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
|
||||
if extruder_count > 0:
|
||||
def temp_line(temp, extruder, template):
|
||||
t = temp
|
||||
if extruder > 0:
|
||||
print_temp = self.get_float("print_temperature%d" % (extruder + 1))
|
||||
if print_temp > 0:
|
||||
t = print_temp
|
||||
return template.format(extruder=extruder, temp=t)
|
||||
|
||||
prefix_preheat = ""
|
||||
prefix_waitheat = ""
|
||||
for n in xrange(0, extruder_count):
|
||||
if n > 0:
|
||||
prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
|
||||
prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
|
||||
prefix += prefix_preheat + prefix_waitheat + "T0\n"
|
||||
else:
|
||||
prefix += "M109 S{temp}\n".format(temp=temp)
|
||||
|
||||
if include_bed_temp:
|
||||
prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp)
|
||||
|
||||
else:
|
||||
contents = self.get_gcode_template(key)
|
||||
|
||||
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
|
||||
|
||||
def calculate_edge_width_and_line_count(self):
|
||||
wall_thickness = self.get_float("wall_thickness")
|
||||
nozzle_size = self._printer_profile["extruder"]["nozzleDiameter"]
|
||||
|
||||
if self.get_boolean("spiralize") or self.get_boolean("follow_surface"):
|
||||
return wall_thickness, 1
|
||||
if wall_thickness < 0.01:
|
||||
return nozzle_size, 0
|
||||
if wall_thickness < nozzle_size:
|
||||
return wall_thickness, 1
|
||||
|
||||
edge_width = None
|
||||
line_count = int(wall_thickness / (nozzle_size - 0.0001))
|
||||
if line_count < 1:
|
||||
edge_width = nozzle_size
|
||||
line_count = 1
|
||||
line_width = wall_thickness / line_count
|
||||
line_width_alt = wall_thickness / (line_count + 1)
|
||||
if line_width > nozzle_size * 1.5:
|
||||
return line_width_alt, line_count + 1
|
||||
if not edge_width:
|
||||
edge_width = line_width
|
||||
return edge_width, line_count
|
||||
|
||||
def calculate_solid_layer_count(self):
|
||||
layer_height = self.get_float("layer_height")
|
||||
solid_thickness = self.get_float("solid_layer_thickness")
|
||||
if layer_height == 0.0:
|
||||
return 1
|
||||
import math
|
||||
return int(math.ceil(solid_thickness / (layer_height - 0.0001)))
|
||||
|
||||
def calculate_minimal_extruder_count(self):
|
||||
extruder_count = self.get("extruder_amount")
|
||||
if extruder_count < 2:
|
||||
return 1
|
||||
if self.get("support") == SupportLocationTypes.NONE:
|
||||
return 1
|
||||
if self.get("support_dual_extrusion") == SupportDualTypes.SECOND:
|
||||
return 2
|
||||
return 1
|
||||
|
||||
def get_pos_x(self):
|
||||
if self._posX:
|
||||
try:
|
||||
return int(float(self._posX) * 1000)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return int(self.get_float("machine_width") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
|
||||
def get_pos_y(self):
|
||||
if self._posY:
|
||||
try:
|
||||
return int(float(self._posY) * 1000)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return int(self.get_float("machine_depth") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
|
||||
def convert_to_engine(self):
|
||||
|
||||
edge_width, line_count = self.calculate_edge_width_and_line_count()
|
||||
solid_layer_count = self.calculate_solid_layer_count()
|
||||
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
minimal_extruder_count = self.calculate_minimal_extruder_count()
|
||||
|
||||
settings = {
|
||||
"layerThickness": self.get_microns("layer_height"),
|
||||
"initialLayerThickness": self.get_microns("bottom_thickness") if self.get_float("bottom_thickness") > 0.0 else self.get_microns("layer_height"),
|
||||
"filamentDiameter": self.get_microns("filament_diameter"),
|
||||
"filamentFlow": self.get_int("filament_flow"),
|
||||
"extrusionWidth": edge_width * 1000,
|
||||
"layer0extrusionWidth": int(edge_width * self.get_float("first_layer_width_factor") / 100 * 1000),
|
||||
"insetCount": line_count,
|
||||
"downSkinCount": solid_layer_count if self.get_boolean("solid_bottom") else 0,
|
||||
"upSkinCount": solid_layer_count if self.get_boolean("solid_top") else 0,
|
||||
"infillOverlap": self.get_int("fill_overlap"),
|
||||
"initialSpeedupLayers": int(4),
|
||||
"initialLayerSpeed": self.get_int("bottom_layer_speed"),
|
||||
"printSpeed": self.get_int("print_speed"),
|
||||
"infillSpeed": self.get_int("infill_speed") if self.get_int("infill_speed") > 0 else self.get_int("print_speed"),
|
||||
"inset0Speed": self.get_int("outer_shell_speed") if self.get_int("outer_shell_speed") > 0 else self.get_int("print_speed"),
|
||||
"insetXSpeed": self.get_int("inner_shell_speed") if self.get_int("inner_shell_speed") > 0 else self.get_int("print_speed"),
|
||||
"moveSpeed": self.get_int("travel_speed"),
|
||||
"fanSpeedMin": self.get_int("fan_speed") if self.get_boolean("fan_enabled") else 0,
|
||||
"fanSpeedMax": self.get_int("fan_speed_max") if self.get_boolean("fan_enabled") else 0,
|
||||
"supportAngle": int(-1) if self.get("support") == SupportLocationTypes.NONE else self.get_int("support_angle"),
|
||||
"supportEverywhere": int(1) if self.get("support") == SupportLocationTypes.EVERYWHERE else int(0),
|
||||
"supportLineDistance": int(100 * edge_width * 1000 / self.get_float("support_fill_rate")) if self.get_float("support_fill_rate") > 0 else -1,
|
||||
"supportXYDistance": int(1000 * self.get_float("support_xy_distance")),
|
||||
"supportZDistance": int(1000 * self.get_float("support_z_distance")),
|
||||
"supportExtruder": 0 if self.get("support_dual_extrusion") == SupportDualTypes.FIRST else (1 if self.get("support_dual_extrusion") == SupportDualTypes.SECOND and minimal_extruder_count > 1 else -1),
|
||||
"retractionAmount": self.get_microns("retraction_amount") if self.get_boolean("retraction_enable") else 0,
|
||||
"retractionSpeed": self.get_int("retraction_speed"),
|
||||
"retractionMinimalDistance": self.get_microns("retraction_min_travel"),
|
||||
"retractionAmountExtruderSwitch": self.get_microns("retraction_dual_amount"),
|
||||
"retractionZHop": self.get_microns("retraction_hop"),
|
||||
"minimalExtrusionBeforeRetraction": self.get_microns("retraction_minimal_extrusion"),
|
||||
"enableCombing": 1 if self.get_boolean("retraction_combing") else 0,
|
||||
"multiVolumeOverlap": self.get_microns("overlap_dual"),
|
||||
"objectSink": max(0, self.get_microns("object_sink")),
|
||||
"minimalLayerTime": self.get_int("cool_min_layer_time"),
|
||||
"minimalFeedrate": self.get_int("cool_min_feedrate"),
|
||||
"coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0,
|
||||
|
||||
# model positioning
|
||||
"posx": self.get_pos_x(),
|
||||
"posy": self.get_pos_y(),
|
||||
|
||||
# gcodes
|
||||
"startCode": self.get_gcode("start_gcode"),
|
||||
"endCode": self.get_gcode("end_gcode"),
|
||||
"preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode"),
|
||||
"postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode"),
|
||||
|
||||
# fixing
|
||||
"fixHorrible": 0,
|
||||
}
|
||||
|
||||
for extruder in range(1, extruder_count):
|
||||
for axis in ("x", "y"):
|
||||
settings["extruderOffset[{extruder}].{axis}".format(extruder=extruder, axis=axis.upper())] = self.get("extruder_offset_{axis}{extruder}".format(extruder=extruder, axis=axis.lower()))
|
||||
|
||||
fanFullHeight = self.get_microns("fan_full_height")
|
||||
settings["fanFullOnLayerNr"] = (fanFullHeight - settings["initialLayerThickness"] - 1) / settings["layerThickness"] + 1
|
||||
if settings["fanFullOnLayerNr"] < 0:
|
||||
settings["fanFullOnLayerNr"] = 0
|
||||
|
||||
if self.get("support_type") == SupportTypes.LINES:
|
||||
settings["supportType"] = 1
|
||||
|
||||
# infill
|
||||
if self.get_float("fill_density") == 0:
|
||||
settings["sparseInfillLineDistance"] = -1
|
||||
|
||||
elif self.get_float("fill_density") == 100:
|
||||
settings["sparseInfillLineDistance"] = settings["extrusionWidth"]
|
||||
settings["downSkinCount"] = 10000
|
||||
settings["upSkinCount"] = 10000
|
||||
|
||||
else:
|
||||
settings["sparseInfillLineDistance"] = int(100 * edge_width * 1000 / self.get_float("fill_density"))
|
||||
|
||||
# brim/raft/skirt
|
||||
if self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM:
|
||||
settings["skirtDistance"] = 0
|
||||
settings["skirtLineCount"] = self.get_int("brim_line_count")
|
||||
|
||||
elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT:
|
||||
settings["skirtDistance"] = 0
|
||||
settings["skirtLineCount"] = 0
|
||||
settings["raftMargin"] = self.get_microns("raft_margin")
|
||||
settings["raftLineSpacing"] = self.get_microns("raft_line_spacing")
|
||||
settings["raftBaseThickness"] = self.get_microns("raft_base_thickness")
|
||||
settings["raftBaseLinewidth"] = self.get_microns("raft_base_linewidth")
|
||||
settings["raftInterfaceThickness"] = self.get_microns("raft_interface_thickness")
|
||||
settings["raftInterfaceLinewidth"] = self.get_microns("raft_interface_linewidth")
|
||||
settings["raftInterfaceLineSpacing"] = self.get_microns("raft_interface_linewidth") * 2
|
||||
settings["raftAirGapLayer0"] = self.get_microns("raft_airgap")
|
||||
settings["raftBaseSpeed"] = self.get_int("bottom_layer_speed")
|
||||
settings["raftFanSpeed"] = 100
|
||||
settings["raftSurfaceThickness"] = settings["raftInterfaceThickness"]
|
||||
settings["raftSurfaceLinewidth"] = int(edge_width * 1000)
|
||||
settings["raftSurfaceLineSpacing"] = int(edge_width * 1000 * 0.9)
|
||||
settings["raftSurfaceLayers"] = self.get_int("raft_surface_layers")
|
||||
settings["raftSurfaceSpeed"] = self.get_int("bottom_layer_speed")
|
||||
|
||||
else:
|
||||
settings["skirtDistance"] = self.get_microns("skirt_gap")
|
||||
settings["skirtLineCount"] = self.get_int("skirt_line_count")
|
||||
settings["skirtMinLength"] = self.get_microns("skirt_minimal_length")
|
||||
|
||||
# fixing
|
||||
if self.get_boolean("fix_horrible_union_all_type_a"):
|
||||
settings["fixHorrible"] |= 0x01
|
||||
if self.get_boolean("fix_horrible_union_all_type_b"):
|
||||
settings["fixHorrible"] |= 0x02
|
||||
if self.get_boolean("fix_horrible_use_open_bits"):
|
||||
settings["fixHorrible"] |= 0x10
|
||||
if self.get_boolean("fix_horrible_extensive_stitching"):
|
||||
settings["fixHorrible"] |= 0x04
|
||||
|
||||
if settings["layerThickness"] <= 0:
|
||||
settings["layerThickness"] = 1000
|
||||
|
||||
# gcode flavor
|
||||
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
|
||||
settings["gcodeFlavor"] = 1
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.MAKERBOT:
|
||||
settings["gcodeFlavor"] = 2
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.BFB:
|
||||
settings["gcodeFlavor"] = 3
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.MACH3:
|
||||
settings["gcodeFlavor"] = 4
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
|
||||
settings["gcodeFlavor"] = 5
|
||||
|
||||
# extras
|
||||
if self.get_boolean("spiralize"):
|
||||
settings["spiralizeMode"] = 1
|
||||
if self.get_boolean("follow_surface"):
|
||||
settings["simpleMode"] = 1
|
||||
|
||||
# dual extrusion
|
||||
if self.get_boolean("wipe_tower") and extruder_count > 1:
|
||||
import math
|
||||
settings["wipeTowerSize"] = int(math.sqrt(self.get_float("wipe_tower_volume") * 1000 * 1000 * 1000 / settings["layerThickness"]))
|
||||
if self.get_boolean("ooze_shield"):
|
||||
settings["enableOozeShield"] = 1
|
||||
|
||||
return settings
|
||||
@@ -0,0 +1,4 @@
|
||||
layer_height: 0.2
|
||||
print_temperature:
|
||||
- 220.0
|
||||
- 220.0
|
||||
@@ -0,0 +1 @@
|
||||
table th.settings_plugin_cura_profiles_key,table td.settings_plugin_cura_profiles_key{text-overflow:ellipsis;text-align:left;width:200px}table th.settings_plugin_cura_profiles_name,table td.settings_plugin_cura_profiles_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_cura_profiles_actions,table td.settings_plugin_cura_profiles_actions{text-align:center;width:100px}table th.settings_plugin_cura_profiles_actions a,table td.settings_plugin_cura_profiles_actions a{text-decoration:none;color:#000}table th.settings_plugin_cura_profiles_actions a.disabled,table td.settings_plugin_cura_profiles_actions a.disabled{color:#ccc;cursor:default}
|
||||
@@ -0,0 +1,195 @@
|
||||
$(function() {
|
||||
function CuraViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settingsViewModel = parameters[1];
|
||||
self.slicingViewModel = parameters[2];
|
||||
|
||||
self.fileName = ko.observable();
|
||||
|
||||
self.placeholderName = ko.observable();
|
||||
self.placeholderDisplayName = ko.observable();
|
||||
self.placeholderDescription = ko.observable();
|
||||
|
||||
self.profileName = ko.observable();
|
||||
self.profileDisplayName = ko.observable();
|
||||
self.profileDescription = ko.observable();
|
||||
self.profileAllowOverwrite = ko.observable(true);
|
||||
|
||||
self.uploadElement = $("#settings-cura-import");
|
||||
self.uploadButton = $("#settings-cura-import-start");
|
||||
|
||||
self.profiles = new ItemListHelper(
|
||||
"plugin_cura_profiles",
|
||||
{
|
||||
"id": function(a, b) {
|
||||
if (a["key"].toLocaleLowerCase() < b["key"].toLocaleLowerCase()) return -1;
|
||||
if (a["key"].toLocaleLowerCase() > b["key"].toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
},
|
||||
"name": function(a, b) {
|
||||
// sorts ascending
|
||||
var aName = a.name();
|
||||
if (aName === undefined) {
|
||||
aName = "";
|
||||
}
|
||||
var bName = b.name();
|
||||
if (bName === undefined) {
|
||||
bName = "";
|
||||
}
|
||||
|
||||
if (aName.toLocaleLowerCase() < bName.toLocaleLowerCase()) return -1;
|
||||
if (aName.toLocaleLowerCase() > bName.toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{},
|
||||
"id",
|
||||
[],
|
||||
[],
|
||||
5
|
||||
);
|
||||
|
||||
self._sanitize = function(name) {
|
||||
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
|
||||
};
|
||||
|
||||
self.uploadElement.fileupload({
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
add: function(e, data) {
|
||||
if (data.files.length == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.fileName(data.files[0].name);
|
||||
|
||||
var name = self.fileName().substr(0, self.fileName().lastIndexOf("."));
|
||||
self.placeholderName(self._sanitize(name).toLowerCase());
|
||||
self.placeholderDisplayName(name);
|
||||
self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));
|
||||
|
||||
self.uploadButton.on("click", function() {
|
||||
var form = {
|
||||
allowOverwrite: self.profileAllowOverwrite()
|
||||
};
|
||||
|
||||
if (self.profileName() !== undefined) {
|
||||
form["name"] = self.profileName();
|
||||
}
|
||||
if (self.profileDisplayName() !== undefined) {
|
||||
form["displayName"] = self.profileDisplayName();
|
||||
}
|
||||
if (self.profileDescription() !== undefined) {
|
||||
form["description"] = self.profileDescription();
|
||||
}
|
||||
|
||||
data.formData = form;
|
||||
data.submit();
|
||||
});
|
||||
},
|
||||
done: function(e, data) {
|
||||
self.fileName(undefined);
|
||||
self.placeholderName(undefined);
|
||||
self.placeholderDisplayName(undefined);
|
||||
self.placeholderDescription(undefined);
|
||||
self.profileName(undefined);
|
||||
self.profileDisplayName(undefined);
|
||||
self.profileDescription(undefined);
|
||||
self.profileAllowOverwrite(true);
|
||||
|
||||
$("#settings_plugin_cura_import").modal("hide");
|
||||
self.requestData();
|
||||
self.slicingViewModel.requestData();
|
||||
}
|
||||
});
|
||||
|
||||
self.removeProfile = function(data) {
|
||||
if (!data.resource) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.profiles.removeItem(function(item) {
|
||||
return (item.key == data.key);
|
||||
});
|
||||
|
||||
$.ajax({
|
||||
url: data.resource(),
|
||||
type: "DELETE",
|
||||
success: function() {
|
||||
self.requestData();
|
||||
self.slicingViewModel.requestData();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.makeProfileDefault = function(data) {
|
||||
if (!data.resource) {
|
||||
return;
|
||||
}
|
||||
|
||||
_.each(self.profiles.items(), function(item) {
|
||||
item.isdefault(false);
|
||||
});
|
||||
var item = self.profiles.getItem(function(item) {
|
||||
return item.key == data.key;
|
||||
});
|
||||
if (item !== undefined) {
|
||||
item.isdefault(true);
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: data.resource(),
|
||||
type: "PATCH",
|
||||
dataType: "json",
|
||||
data: JSON.stringify({default: true}),
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
success: function() {
|
||||
self.requestData();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.showImportProfileDialog = function() {
|
||||
$("#settings_plugin_cura_import").modal("show");
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "slicing/cura/profiles",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: self.fromResponse
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
var profiles = [];
|
||||
_.each(_.keys(data), function(key) {
|
||||
profiles.push({
|
||||
key: key,
|
||||
name: ko.observable(data[key].displayName),
|
||||
description: ko.observable(data[key].description),
|
||||
isdefault: ko.observable(data[key].default),
|
||||
resource: ko.observable(data[key].resource)
|
||||
});
|
||||
});
|
||||
self.profiles.updateItems(profiles);
|
||||
};
|
||||
|
||||
self.onBeforeBinding = function () {
|
||||
self.settings = self.settingsViewModel.settings;
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
CuraViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
|
||||
"#settings_plugin_cura"
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
table {
|
||||
th, td {
|
||||
&.settings_plugin_cura_profiles_key {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
&.settings_plugin_cura_profiles_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&.settings_plugin_cura_profiles_actions {
|
||||
text-align: center;
|
||||
width: 100px;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
<h4>{{ _('General') }}</h4>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to plugin_cura_engine.log') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<h4>{{ _('Profiles') }}</h4>
|
||||
|
||||
<div class="pull-right">
|
||||
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { profiles.changeSorting('id'); }">{{ _('Identifier') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { profiles.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a></small>
|
||||
</div>
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_cura_profiles_key">{{ _('Identifier') }}</th>
|
||||
<th class="settings_plugin_cura_profiles_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_cura_profiles_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: profiles.paginatedItems">
|
||||
<tr data-bind="attr: {title: description}">
|
||||
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
|
||||
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
|
||||
<td class="settings_plugin_cura_profiles_actions">
|
||||
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a> | <a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: profiles.currentPage() === 0}"><a href="#" data-bind="click: profiles.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: profiles.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.profiles.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: profiles.currentPage() === profiles.lastPage()}"><a href="#" data-bind="click: profiles.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
|
||||
|
||||
<div id="settings_plugin_cura_import" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Import Existing Cura Profile') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Profile ini file') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-prepend">
|
||||
<span class="btn fileinput-button">
|
||||
<span>{{ _('Browse...') }}</span>
|
||||
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.import_cura_profile") }}">
|
||||
</span>
|
||||
<span class="add-on" data-bind="text: fileName"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Name') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Description') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" id="settings-cura-import-start">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_cura_edit" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Edit Cura Profile') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="tabbable">
|
||||
<ul class="nav nav-tabs">
|
||||
<li class="active"><a href="#settings_plugin_cura_edit_general" data-toggle="tab">{{ _('General') }}</a></li>
|
||||
<li><a href="#settings_plugin_cura_edit_basic" data-toggle="tab">{{ _('Basic') }}</a></li>
|
||||
<li><a href="#settings_plugin_cura_edit_advanced" data-toggle="tab">{{ _('Advanced') }}</a></li>
|
||||
<li><a href="#settings_plugin_cura_edit_expert" data-toggle="tab">{{ _('Expert') }}</a></li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane active" id="settings_plugin_cura_edit_general">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Name') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Descripton') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="tab-pane" id="settings_plugin_cura_edit_basic">
|
||||
<form class="form-horizontal">
|
||||
<fieldset>
|
||||
<legend>{{ _('Quality') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Layer height (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Shell thickness (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox"> {{ _('Enable retraction') }}
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Fill') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Bottom/top thickness (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Fill density (%%)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Speed and Temperature') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Print speed (mm/s)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Print temperature (°C)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Support') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Support type') }}</label>
|
||||
<select>
|
||||
<option value="none">{{ _('None') }}</option>
|
||||
<option value="buildplate">{{ _('Touching buildplate') }}</option>
|
||||
<option value="everywhere">{{ _('Everywhere') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Platform adhesion type') }}</label>
|
||||
<select>
|
||||
<option value="none">{{ _('None') }}</option>
|
||||
<option value="brim">{{ _('Brim') }}</option>
|
||||
<option value="raft">{{ _('Raft') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Filament') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Diameter (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Flow (%%)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
<div class="tab-pane" id="settings_plugin_cura_edit_advanced"></div>
|
||||
<div class="tab-pane" id="settings_plugin_cura_edit_expert"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.confirmEditProfile() }">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -24,7 +24,10 @@ except:
|
||||
|
||||
__plugin_name__ = "Discovery"
|
||||
__plugin_version__ = "0.1"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery"
|
||||
__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
|
||||
def __plugin_init__():
|
||||
if not pybonjour:
|
||||
@@ -47,93 +50,16 @@ def __plugin_init__():
|
||||
zeroconf_unregister=discovery_plugin.zeroconf_unregister
|
||||
))
|
||||
|
||||
|
||||
default_settings = {
|
||||
"publicHost": None,
|
||||
"publicPort": None,
|
||||
"pathPrefix": None,
|
||||
"httpUsername": None,
|
||||
"httpPassword": None,
|
||||
"upnpUuid": None,
|
||||
"zeroConf": [],
|
||||
"model": {
|
||||
"name": None,
|
||||
"description": None,
|
||||
"number": None,
|
||||
"url": None,
|
||||
"serial": None,
|
||||
"vendor": None,
|
||||
"vendorUrl": None
|
||||
}
|
||||
}
|
||||
s = octoprint.plugin.plugin_settings("discovery", defaults=default_settings)
|
||||
|
||||
def get_uuid():
|
||||
upnpUuid = s.get(["upnpUuid"])
|
||||
if upnpUuid is None:
|
||||
import uuid
|
||||
upnpUuid = str(uuid.uuid4())
|
||||
s.set(["upnpUuid"], upnpUuid)
|
||||
s.save()
|
||||
return upnpUuid
|
||||
UUID = get_uuid()
|
||||
del get_uuid
|
||||
|
||||
|
||||
def get_instance_name():
|
||||
name = s.globalGet(["appearance", "name"])
|
||||
if name:
|
||||
return "OctoPrint instance \"{}\"".format(name)
|
||||
else:
|
||||
import socket
|
||||
return "OctoPrint instance on {}".format(socket.gethostname())
|
||||
|
||||
|
||||
#~~ custom blueprint for providing discovery.xml
|
||||
|
||||
blueprint = flask.Blueprint("plugin.discovery", __name__, template_folder=os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates"))
|
||||
|
||||
@blueprint.route("/discovery.xml")
|
||||
def discovery():
|
||||
logging.getLogger("octoprint.plugins." + __name__).debug("Rendering discovery.xml")
|
||||
|
||||
modelName = s.get(["model", "name"])
|
||||
if not modelName:
|
||||
import octoprint.server
|
||||
modelName = octoprint.server.DISPLAY_VERSION
|
||||
|
||||
vendor = s.get(["model", "vendor"])
|
||||
vendorUrl = s.get(["model", "vendorUrl"])
|
||||
if not vendor:
|
||||
vendor = "The OctoPrint Project"
|
||||
vendorUrl = "http://www.octoprint.org/"
|
||||
|
||||
response = flask.make_response(flask.render_template("discovery.jinja2",
|
||||
friendlyName=get_instance_name(),
|
||||
manufacturer=vendor,
|
||||
manufacturerUrl=vendorUrl,
|
||||
modelName=modelName,
|
||||
modelDescription=s.get(["model", "description"]),
|
||||
modelNumber=s.get(["model", "number"]),
|
||||
modelUrl=s.get(["model", "url"]),
|
||||
serialNumber=s.get(["model", "serial"]),
|
||||
uuid=UUID,
|
||||
presentationUrl=flask.url_for("index", _external=True)))
|
||||
response.headers['Content-Type'] = 'application/xml'
|
||||
return response
|
||||
|
||||
|
||||
class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.ShutdownPlugin,
|
||||
octoprint.plugin.BlueprintPlugin):
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.SettingsPlugin):
|
||||
|
||||
ssdp_multicast_addr = "239.255.255.250"
|
||||
|
||||
ssdp_multicast_port = 1900
|
||||
|
||||
def __init__(self):
|
||||
self.logger = logging.getLogger("octoprint.plugins." + __name__)
|
||||
|
||||
self.host = None
|
||||
self.port = None
|
||||
|
||||
@@ -147,18 +73,69 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
self._ssdp_notify_timeout = 10
|
||||
self._ssdp_last_notify = 0
|
||||
|
||||
##~~ SettingsPlugin API
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return {
|
||||
"publicHost": None,
|
||||
"publicPort": None,
|
||||
"pathPrefix": None,
|
||||
"httpUsername": None,
|
||||
"httpPassword": None,
|
||||
"upnpUuid": None,
|
||||
"zeroConf": [],
|
||||
"model": {
|
||||
"name": None,
|
||||
"description": None,
|
||||
"number": None,
|
||||
"url": None,
|
||||
"serial": None,
|
||||
"vendor": None,
|
||||
"vendorUrl": None
|
||||
}
|
||||
}
|
||||
|
||||
##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML
|
||||
|
||||
def get_blueprint(self):
|
||||
return blueprint
|
||||
@octoprint.plugin.BlueprintPlugin.route("/discovery.xml", methods=["GET"])
|
||||
def discovery(self):
|
||||
self._logger.debug("Rendering discovery.xml")
|
||||
|
||||
modelName = self._settings.get(["model", "name"])
|
||||
if not modelName:
|
||||
import octoprint.server
|
||||
modelName = octoprint.server.DISPLAY_VERSION
|
||||
|
||||
vendor = self._settings.get(["model", "vendor"])
|
||||
vendorUrl = self._settings.get(["model", "vendorUrl"])
|
||||
if not vendor:
|
||||
vendor = "The OctoPrint Project"
|
||||
vendorUrl = "http://www.octoprint.org/"
|
||||
|
||||
response = flask.make_response(flask.render_template("discovery.xml.jinja2",
|
||||
friendlyName=self.get_instance_name(),
|
||||
manufacturer=vendor,
|
||||
manufacturerUrl=vendorUrl,
|
||||
modelName=modelName,
|
||||
modelDescription=self._settings.get(["model", "description"]),
|
||||
modelNumber=self._settings.get(["model", "number"]),
|
||||
modelUrl=self._settings.get(["model", "url"]),
|
||||
serialNumber=self._settings.get(["model", "serial"]),
|
||||
uuid=self.get_uuid(),
|
||||
presentationUrl=flask.url_for("index", _external=True)))
|
||||
response.headers['Content-Type'] = 'application/xml'
|
||||
return response
|
||||
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup
|
||||
|
||||
def on_startup(self, host, port):
|
||||
public_host = s.get(["publicHost"])
|
||||
public_host = self._settings.get(["publicHost"])
|
||||
if public_host:
|
||||
host = public_host
|
||||
public_port = s.get(["publicPort"])
|
||||
public_port = self._settings.get(["publicPort"])
|
||||
if public_port:
|
||||
port = public_port
|
||||
|
||||
@@ -166,13 +143,13 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
self.port = port
|
||||
|
||||
# Zeroconf
|
||||
self.zeroconf_register("_http._tcp", get_instance_name(), txt_record=self._create_http_txt_record_dict())
|
||||
self.zeroconf_register("_octoprint._tcp", get_instance_name(), txt_record=self._create_octoprint_txt_record_dict())
|
||||
for zeroconf in s.get(["zeroConf"]):
|
||||
self.zeroconf_register("_http._tcp", self.get_instance_name(), txt_record=self._create_http_txt_record_dict())
|
||||
self.zeroconf_register("_octoprint._tcp", self.get_instance_name(), txt_record=self._create_octoprint_txt_record_dict())
|
||||
for zeroconf in self._settings.get(["zeroConf"]):
|
||||
if "service" in zeroconf:
|
||||
self.zeroconf_register(
|
||||
zeroconf["service"],
|
||||
zeroconf["name"] if "name" in zeroconf else get_instance_name(),
|
||||
zeroconf["name"] if "name" in zeroconf else self.get_instance_name(),
|
||||
port=zeroconf["port"] if "port" in zeroconf else None,
|
||||
txt_record=zeroconf["txtRecord"] if "txtRecord" in zeroconf else None
|
||||
)
|
||||
@@ -207,7 +184,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
return
|
||||
|
||||
if not name:
|
||||
name = get_instance_name()
|
||||
name = self.get_instance_name()
|
||||
if not port:
|
||||
port = self.port
|
||||
|
||||
@@ -221,7 +198,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
key = (reg_type, port)
|
||||
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
|
||||
self.logger.info("Registered {name} for {reg_type}".format(**locals()))
|
||||
self._logger.info(u"Registered {name} for {reg_type}".format(**locals()))
|
||||
|
||||
def zeroconf_unregister(self, reg_type, port=None):
|
||||
"""
|
||||
@@ -245,9 +222,9 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
sd_ref = self._sd_refs[key]
|
||||
try:
|
||||
sd_ref.close()
|
||||
self.logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
self._logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
except:
|
||||
self.logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
self._logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
|
||||
def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5):
|
||||
"""
|
||||
@@ -311,7 +288,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
name = fullname[:fullname.find(service_type) - 1].replace("\\032", " ")
|
||||
host = hosttarget[:-1]
|
||||
|
||||
self.logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host))
|
||||
self._logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host))
|
||||
result.append(dict(
|
||||
name=name,
|
||||
host=host,
|
||||
@@ -327,7 +304,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
if not (flags & pybonjour.kDNSServiceFlagsAdd):
|
||||
return
|
||||
|
||||
self.logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type))
|
||||
self._logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type))
|
||||
resolve_ref = pybonjour.DNSServiceResolve(0, interface_index, service_name, regtype, reply_domain, resolve_callback)
|
||||
|
||||
try:
|
||||
@@ -342,7 +319,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
finally:
|
||||
resolve_ref.close()
|
||||
|
||||
self.logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type))
|
||||
self._logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type))
|
||||
|
||||
def browse():
|
||||
sd_ref = pybonjour.DNSServiceBrowse(regtype=service_type, callBack=browse_callback)
|
||||
@@ -487,16 +464,16 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
# determine path entry
|
||||
path = "/"
|
||||
if s.get(["pathPrefix"]):
|
||||
path = s.get(["pathPrefix"])
|
||||
if self._settings.get(["pathPrefix"]):
|
||||
path = self._settings.get(["pathPrefix"])
|
||||
else:
|
||||
prefix = s.globalGet(["server", "reverseProxy", "prefixFallback"])
|
||||
prefix = self._settings.global_get(["server", "reverseProxy", "prefixFallback"])
|
||||
if prefix:
|
||||
path = prefix
|
||||
|
||||
# fetch username and password (if set)
|
||||
username = s.get(["httpUsername"])
|
||||
password = s.get(["httpPassword"])
|
||||
username = self._settings.get(["httpUsername"])
|
||||
password = self._settings.get(["httpPassword"])
|
||||
|
||||
entries = dict(
|
||||
path=path
|
||||
@@ -534,10 +511,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
api=octoprint.server.api.VERSION,
|
||||
))
|
||||
|
||||
modelName = s.get(["model", "name"])
|
||||
modelName = self._settings.get(["model", "name"])
|
||||
if modelName:
|
||||
entries.update(dict(model=modelName))
|
||||
vendor = s.get(["model", "vendor"])
|
||||
vendor = self._settings.get(["model", "vendor"])
|
||||
if vendor:
|
||||
entries.update(dict(vendor=vendor))
|
||||
|
||||
@@ -595,7 +572,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
location = "http://{addr}:{port}/plugin/discovery/discovery.xml".format(addr=addr, port=self.port)
|
||||
|
||||
self.logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr))
|
||||
self._logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr))
|
||||
notify_message = "".join([
|
||||
"NOTIFY * HTTP/1.1\r\n",
|
||||
"Server: Python/2.7\r\n",
|
||||
@@ -606,7 +583,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
"USN: uuid:{uuid}::upnp:rootdevice\r\n",
|
||||
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n"
|
||||
])
|
||||
message = notify_message.format(uuid=UUID,
|
||||
message = notify_message.format(uuid=self.get_uuid(),
|
||||
location=location,
|
||||
nts="ssdp:alive" if alive else "ssdp:byebye",
|
||||
mcast_addr=self.__class__.ssdp_multicast_addr,
|
||||
@@ -660,7 +637,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0'))
|
||||
|
||||
self.logger.info("Registered {} for SSDP".format(get_instance_name()))
|
||||
self._logger.info(u"Registered {} for SSDP".format(self.get_instance_name()))
|
||||
|
||||
self._ssdp_notify(alive=True)
|
||||
|
||||
@@ -672,11 +649,11 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"':
|
||||
interface_address = octoprint.util.address_for_client(*address)
|
||||
if not interface_address:
|
||||
self.logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
|
||||
self._logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
|
||||
continue
|
||||
message = location_message.format(uuid=UUID, location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
|
||||
message = location_message.format(uuid=self.get_uuid(), location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
|
||||
sock.sendto(message, address)
|
||||
self.logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
|
||||
self._logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
|
||||
except socket.timeout:
|
||||
pass
|
||||
finally:
|
||||
@@ -687,4 +664,21 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
except:
|
||||
pass
|
||||
|
||||
##~~ helpers
|
||||
|
||||
def get_uuid(self):
|
||||
upnpUuid = self._settings.get(["upnpUuid"])
|
||||
if upnpUuid is None:
|
||||
import uuid
|
||||
upnpUuid = str(uuid.uuid4())
|
||||
self._settings.set(["upnpUuid"], upnpUuid)
|
||||
self._settings.save()
|
||||
return upnpUuid
|
||||
|
||||
def get_instance_name(self):
|
||||
name = self._settings.global_get(["appearance", "name"])
|
||||
if name:
|
||||
return u"OctoPrint instance \"{}\"".format(name)
|
||||
else:
|
||||
import socket
|
||||
return u"OctoPrint instance on {}".format(socket.gethostname())
|
||||
@@ -1,761 +0,0 @@
|
||||
# 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 time
|
||||
import datetime
|
||||
import threading
|
||||
import copy
|
||||
import os
|
||||
import logging
|
||||
|
||||
import octoprint.util.comm as comm
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.events import eventManager, Events
|
||||
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
def getConnectionOptions():
|
||||
"""
|
||||
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
|
||||
"""
|
||||
return {
|
||||
"ports": comm.serialList(),
|
||||
"baudrates": comm.baudrateList(),
|
||||
"portPreference": settings().get(["serial", "port"]),
|
||||
"baudratePreference": settings().getInt(["serial", "baudrate"]),
|
||||
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
|
||||
}
|
||||
|
||||
class Printer():
|
||||
def __init__(self, gcodeManager):
|
||||
from collections import deque
|
||||
|
||||
self._gcodeManager = gcodeManager
|
||||
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 = deque([], 300)
|
||||
self._tempBacklog = []
|
||||
|
||||
self._latestMessage = None
|
||||
self._messages = deque([], 300)
|
||||
self._messageBacklog = []
|
||||
|
||||
self._latestLog = None
|
||||
self._log = deque([], 300)
|
||||
self._logBacklog = []
|
||||
|
||||
self._state = None
|
||||
|
||||
self._currentZ = None
|
||||
|
||||
self._progress = None
|
||||
self._printTime = None
|
||||
self._printTimeLeft = None
|
||||
|
||||
self._printAfterSelect = False
|
||||
|
||||
# sd handling
|
||||
self._sdPrinting = False
|
||||
self._sdStreaming = False
|
||||
self._sdFilelistAvailable = threading.Event()
|
||||
self._streamingFinishedCallback = None
|
||||
|
||||
self._selectedFile = None
|
||||
|
||||
# comm
|
||||
self._comm = None
|
||||
|
||||
# callbacks
|
||||
self._callbacks = []
|
||||
self._lastProgressReport = None
|
||||
|
||||
self._stateMonitor = StateMonitor(
|
||||
ratelimit=0.5,
|
||||
updateCallback=self._sendCurrentDataCallbacks,
|
||||
addTemperatureCallback=self._sendAddTemperatureCallbacks,
|
||||
addLogCallback=self._sendAddLogCallbacks,
|
||||
addMessageCallback=self._sendAddMessageCallbacks
|
||||
)
|
||||
self._stateMonitor.reset(
|
||||
state={"text": self.getStateString(), "flags": self._getStateFlags()},
|
||||
jobData={
|
||||
"file": {
|
||||
"name": None,
|
||||
"size": None,
|
||||
"origin": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"lastPrintTime": None,
|
||||
"filament": {
|
||||
"length": None,
|
||||
"volume": None
|
||||
}
|
||||
},
|
||||
progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
|
||||
currentZ=None
|
||||
)
|
||||
|
||||
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished);
|
||||
|
||||
#~~ callback handling
|
||||
|
||||
def registerCallback(self, callback):
|
||||
self._callbacks.append(callback)
|
||||
self._sendInitialStateUpdate(callback)
|
||||
|
||||
def unregisterCallback(self, callback):
|
||||
if callback in self._callbacks:
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def _sendAddTemperatureCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addTemperature(data)
|
||||
except: pass
|
||||
|
||||
def _sendAddLogCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addLog(data)
|
||||
except: pass
|
||||
|
||||
def _sendAddMessageCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addMessage(data)
|
||||
except: pass
|
||||
|
||||
def _sendCurrentDataCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendCurrentData(copy.deepcopy(data))
|
||||
except: pass
|
||||
|
||||
def _sendTriggerUpdateCallbacks(self, type):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendEvent(type)
|
||||
except: pass
|
||||
|
||||
def _sendFeedbackCommandOutput(self, name, output):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendFeedbackCommandOutput(name, output)
|
||||
except: pass
|
||||
|
||||
#~~ callback from gcodemanager
|
||||
|
||||
def sendUpdateTrigger(self, type):
|
||||
if type == "gcodeFiles" and self._selectedFile:
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
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):
|
||||
"""
|
||||
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
|
||||
will be attempted.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = comm.MachineCom(port, baudrate, callbackObject=self)
|
||||
|
||||
def disconnect(self):
|
||||
"""
|
||||
Closes the connection to the printer.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = None
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
def command(self, command):
|
||||
"""
|
||||
Sends a single gcode command to the printer.
|
||||
"""
|
||||
self.commands([command])
|
||||
|
||||
def commands(self, commands):
|
||||
"""
|
||||
Sends multiple gcode commands (provided as a list) to the printer.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
for command in commands:
|
||||
self._comm.sendCommand(command)
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
self._comm.selectFile(filename, sd)
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def unselectFile(self):
|
||||
if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
return
|
||||
|
||||
self._comm.unselectFile()
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def startPrint(self):
|
||||
"""
|
||||
Starts the currently loaded print job.
|
||||
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
|
||||
"""
|
||||
if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting():
|
||||
return
|
||||
if self._selectedFile is None:
|
||||
return
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint()
|
||||
|
||||
def togglePausePrint(self):
|
||||
"""
|
||||
Pause the current printjob.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.setPause(not self._comm.isPaused())
|
||||
|
||||
def cancelPrint(self, disableMotorsAndHeater=True):
|
||||
"""
|
||||
Cancel the current printjob.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.cancelPrint()
|
||||
|
||||
if disableMotorsAndHeater:
|
||||
# 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)
|
||||
self._setProgressData(None, None, None, None)
|
||||
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime())
|
||||
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
|
||||
self._stateMonitor.setCurrentZ(self._currentZ)
|
||||
|
||||
def _setState(self, state):
|
||||
self._state = state
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def _addLog(self, log):
|
||||
self._log.append(log)
|
||||
self._stateMonitor.addLog(log)
|
||||
|
||||
def _addMessage(self, message):
|
||||
self._messages.append(message)
|
||||
self._stateMonitor.addMessage(message)
|
||||
|
||||
def _setProgressData(self, progress, filepos, printTime, printTimeLeft):
|
||||
self._progress = progress
|
||||
self._printTime = printTime
|
||||
self._printTimeLeft = printTimeLeft
|
||||
|
||||
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
|
||||
})
|
||||
|
||||
def _addTemperatureData(self, temp, bedTemp):
|
||||
currentTimeUtc = int(time.time())
|
||||
|
||||
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._temps.append(data)
|
||||
|
||||
self._temp = temp
|
||||
self._bedTemp = bedTemp
|
||||
|
||||
self._stateMonitor.addTemperature(data)
|
||||
|
||||
def _setJobData(self, filename, filesize, sd):
|
||||
if filename is not None:
|
||||
self._selectedFile = {
|
||||
"filename": filename,
|
||||
"filesize": filesize,
|
||||
"sd": sd
|
||||
}
|
||||
else:
|
||||
self._selectedFile = None
|
||||
|
||||
estimatedPrintTime = None
|
||||
lastPrintTime = None
|
||||
date = None
|
||||
filament = None
|
||||
if filename:
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(filename).st_ctime)
|
||||
|
||||
fileData = self._gcodeManager.getFileData(filename)
|
||||
if fileData is not None:
|
||||
if "gcodeAnalysis" in fileData:
|
||||
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["gcodeAnalysis"]:
|
||||
estimatedPrintTime = fileData["gcodeAnalysis"]["estimatedPrintTime"]
|
||||
if "filament" in fileData["gcodeAnalysis"].keys():
|
||||
filament = fileData["gcodeAnalysis"]["filament"]
|
||||
if "prints" in fileData and fileData["prints"] and "last" in fileData["prints"] and fileData["prints"]["last"] and "lastPrintTime" in fileData["prints"]["last"]:
|
||||
lastPrintTime = fileData["prints"]["last"]["lastPrintTime"]
|
||||
|
||||
self._stateMonitor.setJobData({
|
||||
"file": {
|
||||
"name": os.path.basename(filename) if filename is not None else None,
|
||||
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
"size": filesize,
|
||||
"date": date
|
||||
},
|
||||
"estimatedPrintTime": estimatedPrintTime,
|
||||
"lastPrintTime": lastPrintTime,
|
||||
"filament": filament,
|
||||
})
|
||||
|
||||
def _sendInitialStateUpdate(self, callback):
|
||||
try:
|
||||
data = self._stateMonitor.getCurrentData()
|
||||
data.update({
|
||||
"temps": list(self._temps),
|
||||
"logs": list(self._log),
|
||||
"messages": list(self._messages)
|
||||
})
|
||||
callback.sendHistoryData(data)
|
||||
except Exception, err:
|
||||
import sys
|
||||
sys.stderr.write("ERROR: %s\n" % str(err))
|
||||
pass
|
||||
|
||||
def _getStateFlags(self):
|
||||
return {
|
||||
"operational": self.isOperational(),
|
||||
"printing": self.isPrinting(),
|
||||
"closedOrError": self.isClosedOrError(),
|
||||
"error": self.isError(),
|
||||
"paused": self.isPaused(),
|
||||
"ready": self.isReady(),
|
||||
"sdReady": self.isSdReady()
|
||||
}
|
||||
|
||||
#~~ callbacks triggered from self._comm
|
||||
|
||||
def mcLog(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon log output.
|
||||
"""
|
||||
self._addLog(message)
|
||||
|
||||
def mcTempUpdate(self, temp, bedTemp):
|
||||
self._addTemperatureData(temp, bedTemp)
|
||||
|
||||
def mcStateChange(self, state):
|
||||
"""
|
||||
Callback method for the comm object, called if the connection state changes.
|
||||
"""
|
||||
oldState = self._state
|
||||
|
||||
# forward relevant state changes to gcode manager
|
||||
if self._comm is not None and oldState == self._comm.STATE_PRINTING:
|
||||
if self._selectedFile is not None:
|
||||
if state == self._comm.STATE_OPERATIONAL:
|
||||
self._gcodeManager.printSucceeded(self._selectedFile["filename"], self._comm.getPrintTime())
|
||||
elif state == self._comm.STATE_CLOSED or state == self._comm.STATE_ERROR or state == self._comm.STATE_CLOSED_WITH_ERROR:
|
||||
self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime())
|
||||
self._gcodeManager.resumeAnalysis() # printing done, put those cpu cycles to good use
|
||||
elif self._comm is not None and state == self._comm.STATE_PRINTING:
|
||||
self._gcodeManager.pauseAnalysis() # do not analyse gcode while printing
|
||||
|
||||
self._setState(state)
|
||||
|
||||
def mcMessage(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon message exchanges via serial.
|
||||
Stores the message in the message buffer, truncates buffer to the last 300 lines.
|
||||
"""
|
||||
self._addMessage(message)
|
||||
|
||||
def mcProgress(self):
|
||||
"""
|
||||
Callback method for the comm object, called upon any change in progress of the printjob.
|
||||
Triggers storage of new values for printTime, printTimeLeft and the current progress.
|
||||
"""
|
||||
|
||||
self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getPrintTimeRemainingEstimate())
|
||||
|
||||
def mcZChange(self, newZ):
|
||||
"""
|
||||
Callback method for the comm object, called upon change of the z-layer.
|
||||
"""
|
||||
oldZ = self._currentZ
|
||||
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(Events.Z_CHANGE, {"new": newZ, "old": oldZ})
|
||||
|
||||
self._setCurrentZ(newZ)
|
||||
|
||||
def mcSdStateChange(self, sdReady):
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcSdFiles(self, files):
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
|
||||
self._sdFilelistAvailable.set()
|
||||
|
||||
def mcFileSelected(self, filename, filesize, sd):
|
||||
self._setJobData(filename, filesize, sd)
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
if self._printAfterSelect:
|
||||
self.startPrint()
|
||||
|
||||
def mcPrintjobDone(self):
|
||||
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0)
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcFileTransferStarted(self, filename, filesize):
|
||||
self._sdStreaming = True
|
||||
|
||||
self._setJobData(filename, filesize, True)
|
||||
self._setProgressData(0.0, 0, 0, None)
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcFileTransferDone(self, filename):
|
||||
self._sdStreaming = False
|
||||
|
||||
if self._streamingFinishedCallback is not None:
|
||||
# in case of SD files, both filename and absolutePath are the same, so we set the (remote) filename for
|
||||
# both parameters
|
||||
self._streamingFinishedCallback(filename, filename, FileDestinations.SDCARD)
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcReceivedRegisteredMessage(self, command, output):
|
||||
self._sendFeedbackCommandOutput(command, output)
|
||||
|
||||
#~~ sd file handling
|
||||
|
||||
def getSdFiles(self):
|
||||
if self._comm is None or not self._comm.isSdReady():
|
||||
return []
|
||||
return self._comm.getSdFiles()
|
||||
|
||||
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 = map(lambda x: x[0], self._comm.getSdFiles())
|
||||
|
||||
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():
|
||||
return
|
||||
self._comm.deleteSdFile(filename)
|
||||
|
||||
def initSdCard(self):
|
||||
if not self._comm or self._comm.isSdReady():
|
||||
return
|
||||
self._comm.initSdCard()
|
||||
|
||||
def releaseSdCard(self):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.releaseSdCard()
|
||||
|
||||
def refreshSdFiles(self, blocking=False):
|
||||
"""
|
||||
Refreshs the list of file stored on the SD card attached to printer (if available and printer communication
|
||||
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
|
||||
received (and can be accessed via self._comm.getSdFiles()). Defaults to a asynchronous operation.
|
||||
"""
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._sdFilelistAvailable.clear()
|
||||
self._comm.refreshSdFiles()
|
||||
if blocking:
|
||||
self._sdFilelistAvailable.wait(10000)
|
||||
|
||||
#~~ state reports
|
||||
|
||||
def getStateString(self):
|
||||
"""
|
||||
Returns a human readable string corresponding to the current communication state.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return "Offline"
|
||||
else:
|
||||
return self._comm.getStateString()
|
||||
|
||||
def getCurrentData(self):
|
||||
return self._stateMonitor.getCurrentData()
|
||||
|
||||
def getCurrentJob(self):
|
||||
currentData = self._stateMonitor.getCurrentData()
|
||||
return currentData["job"]
|
||||
|
||||
def getCurrentTemperatures(self):
|
||||
if self._comm is not None:
|
||||
tempOffset, bedTempOffset = self._comm.getOffsets()
|
||||
else:
|
||||
tempOffset = {}
|
||||
bedTempOffset = None
|
||||
|
||||
result = {}
|
||||
if self._temp is not None:
|
||||
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()
|
||||
|
||||
def isOperational(self):
|
||||
return self._comm is not None and self._comm.isOperational()
|
||||
|
||||
def isPrinting(self):
|
||||
return self._comm is not None and self._comm.isPrinting()
|
||||
|
||||
def isPaused(self):
|
||||
return self._comm is not None and self._comm.isPaused()
|
||||
|
||||
def isError(self):
|
||||
return self._comm is not None and self._comm.isError()
|
||||
|
||||
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()
|
||||
|
||||
class StateMonitor(object):
|
||||
def __init__(self, ratelimit, updateCallback, addTemperatureCallback, addLogCallback, addMessageCallback):
|
||||
self._ratelimit = ratelimit
|
||||
self._updateCallback = updateCallback
|
||||
self._addTemperatureCallback = addTemperatureCallback
|
||||
self._addLogCallback = addLogCallback
|
||||
self._addMessageCallback = addMessageCallback
|
||||
|
||||
self._state = None
|
||||
self._jobData = None
|
||||
self._gcodeData = None
|
||||
self._sdUploadData = None
|
||||
self._currentZ = None
|
||||
self._progress = None
|
||||
|
||||
self._offsets = {}
|
||||
|
||||
self._changeEvent = threading.Event()
|
||||
self._stateMutex = threading.Lock()
|
||||
|
||||
self._lastUpdate = time.time()
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def reset(self, state=None, jobData=None, progress=None, currentZ=None):
|
||||
self.setState(state)
|
||||
self.setJobData(jobData)
|
||||
self.setProgress(progress)
|
||||
self.setCurrentZ(currentZ)
|
||||
|
||||
def addTemperature(self, temperature):
|
||||
self._addTemperatureCallback(temperature)
|
||||
self._changeEvent.set()
|
||||
|
||||
def addLog(self, log):
|
||||
self._addLogCallback(log)
|
||||
self._changeEvent.set()
|
||||
|
||||
def addMessage(self, message):
|
||||
self._addMessageCallback(message)
|
||||
self._changeEvent.set()
|
||||
|
||||
def setCurrentZ(self, currentZ):
|
||||
self._currentZ = currentZ
|
||||
self._changeEvent.set()
|
||||
|
||||
def setState(self, state):
|
||||
with self._stateMutex:
|
||||
self._state = state
|
||||
self._changeEvent.set()
|
||||
|
||||
def setJobData(self, jobData):
|
||||
self._jobData = jobData
|
||||
self._changeEvent.set()
|
||||
|
||||
def setProgress(self, progress):
|
||||
self._progress = progress
|
||||
self._changeEvent.set()
|
||||
|
||||
def setTempOffsets(self, offsets):
|
||||
self._offsets = offsets
|
||||
self._changeEvent.set()
|
||||
|
||||
def _work(self):
|
||||
while True:
|
||||
self._changeEvent.wait()
|
||||
|
||||
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()
|
||||
|
||||
def getCurrentData(self):
|
||||
return {
|
||||
"state": self._state,
|
||||
"job": self._jobData,
|
||||
"currentZ": self._currentZ,
|
||||
"progress": self._progress,
|
||||
"offsets": self._offsets
|
||||
}
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
This module defines the interface for communicating with a connected printer.
|
||||
|
||||
The communication is in fact divided in two components, the :class:`PrinterInterface` and a deeper lying
|
||||
communcation layer. However, plugins should only ever need to use the :class:`PrinterInterface` as the
|
||||
abstracted version of the actual printer communiciation.
|
||||
|
||||
.. autofunction:: get_connection_options
|
||||
|
||||
.. autoclass:: PrinterInterface
|
||||
:members:
|
||||
|
||||
.. autoclass:: PrinterCallback
|
||||
:members:
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import re
|
||||
|
||||
import octoprint.util.comm as comm
|
||||
from octoprint.settings import settings
|
||||
|
||||
def get_connection_options():
|
||||
"""
|
||||
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
|
||||
|
||||
Returned ``dict`` has the following structure::
|
||||
|
||||
ports: <list of available serial ports>
|
||||
baudrates: <list of available baudrates>
|
||||
portPreference: <configured default serial port>
|
||||
baudratePreference: <configured default baudrate>
|
||||
autoconnect: <whether autoconnect upon server startup is enabled or not>
|
||||
|
||||
Returns:
|
||||
(dict): A dictionary holding the connection options in the structure specified above
|
||||
"""
|
||||
return {
|
||||
"ports": comm.serialList(),
|
||||
"baudrates": comm.baudrateList(),
|
||||
"portPreference": settings().get(["serial", "port"]),
|
||||
"baudratePreference": settings().getInt(["serial", "baudrate"]),
|
||||
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
|
||||
}
|
||||
|
||||
|
||||
class PrinterInterface(object):
|
||||
"""
|
||||
The :class:`PrinterInterface` represents the developer interface to the :class:`~octoprint.printer.standard.Printer`
|
||||
instance.
|
||||
"""
|
||||
|
||||
valid_axes = ("x", "y", "z", "e")
|
||||
"""Valid axes identifiers."""
|
||||
|
||||
valid_tool_regex = re.compile("^(tool\d+)$")
|
||||
"""Regex for valid tool identifiers."""
|
||||
|
||||
valid_heater_regex = re.compile("^(tool\d+|bed)$")
|
||||
"""Regex for valid heater identifiers."""
|
||||
|
||||
def connect(self, port=None, baudrate=None, profile=None):
|
||||
"""
|
||||
Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a
|
||||
connection is already established, that connection will be closed prior to connecting anew with the provided
|
||||
parameters.
|
||||
|
||||
Arguments:
|
||||
port (str): Name of the serial port to connect to. If not provided, an auto detection will be attempted.
|
||||
baudrate (int): Baudrate to connect with. If not provided, an auto detection will be attempted.
|
||||
profile (str): Name of the printer profile to use for this connection. If not provided, the default
|
||||
will be retrieved from the :class:`PrinterProfileManager`.
|
||||
"""
|
||||
pass
|
||||
|
||||
def disconnect(self):
|
||||
"""
|
||||
Disconnects from the printer. Does nothing if no connection is currently established.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_transport(self):
|
||||
"""
|
||||
Returns the communication layer's transport object, if a connection is currently established.
|
||||
|
||||
Note that this doesn't have to necessarily be a :class:`serial.Serial` instance, it might also be something
|
||||
different, so take care to do instance checks before attempting to access any properties or methods.
|
||||
|
||||
Returns:
|
||||
object: The communication layer's transport object
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def commands(self, commands):
|
||||
"""
|
||||
Sends the provided ``commands`` to the printer.
|
||||
|
||||
Arguments:
|
||||
commands (str, list): The commands to send. Might be a single command provided just as a string or a list
|
||||
of multiple commands to send in order.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def script(self, name, context=None):
|
||||
"""
|
||||
Sends the GCODE script ``name`` to the printer.
|
||||
|
||||
The script will be run through the template engine, the rendering context can be extended by providing a
|
||||
``context`` with additional template variables to use.
|
||||
|
||||
If the script is unknown, an :class:`UnknownScriptException` will be raised.
|
||||
|
||||
Arguments:
|
||||
name (str): The name of the GCODE script to render.
|
||||
context (dict): An optional context of additional template variables to provide to the renderer.
|
||||
|
||||
Raises:
|
||||
UnknownScriptException: There is no GCODE script with name ``name``
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def jog(self, axis, amount):
|
||||
"""
|
||||
Jogs the specified printer ``axis`` by the specified ``amount`` in mm.
|
||||
|
||||
Arguments:
|
||||
axis (str): The axis to jog, will be converted to lower case, one of "x", "y", "z" or "e"
|
||||
amount (int, float): The amount by which to jog in mm
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def home(self, axes):
|
||||
"""
|
||||
Homes the specified printer ``axes``.
|
||||
|
||||
Arguments:
|
||||
axes (str, list): The axis or axes to home, each of which must converted to lower case must match one of
|
||||
"x", "y", "z" and "e"
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def extrude(self, amount):
|
||||
"""
|
||||
Extrude ``amount`` milimeters of material from the tool.
|
||||
|
||||
Arguments:
|
||||
amount (int, float): The amount of material to extrude in mm
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def change_tool(self, tool):
|
||||
"""
|
||||
Switch the currently active ``tool`` (for which extrude commands will apply).
|
||||
|
||||
Arguments:
|
||||
tool (str): The tool to switch to, matching the regex "tool[0-9]+" (e.g. "tool0", "tool1", ...)
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_temperature(self, heater, value):
|
||||
"""
|
||||
Sets the target temperature on the specified ``heater`` to the given ``value`` in celsius.
|
||||
|
||||
Arguments:
|
||||
heater (str): The heater for which to set the target temperature. Either "bed" for setting the bed
|
||||
temperature or something matching the regular expression "tool[0-9]+" (e.g. "tool0", "tool1", ...) for
|
||||
the hotends of the printer
|
||||
value (int, float): The temperature in celsius to set the target temperature to.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_temperature_offset(self, offsets=None):
|
||||
"""
|
||||
Sets the temperature ``offsets`` to apply to target temperatures red from a GCODE file while printing.
|
||||
|
||||
Arguments:
|
||||
offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater``
|
||||
parameter to :func:`set_temperature`, so "bed" for the offset for the bed target temperature and
|
||||
"tool[0-9]+" for the offsets to the hotend target temperatures.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def feed_rate(self, factor):
|
||||
"""
|
||||
Sets the ``factor`` for the printer's feed rate.
|
||||
|
||||
Arguments:
|
||||
factor (int, float): The factor for the feed rate to send to the firmware. Percentage expressed as either an
|
||||
int between 0 and 100 or a float between 0 and 1.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def flow_rate(self, factor):
|
||||
"""
|
||||
Sets the ``factor`` for the printer's flow rate.
|
||||
|
||||
Arguments:
|
||||
factor (int, float): The factor for the flow rate to send to the firmware. Percentage expressed as either an
|
||||
int between 0 and 100 or a float between 0 and 1.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def select_file(self, path, sd, printAfterSelect=False):
|
||||
"""
|
||||
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
|
||||
Optionally can also directly start the print after selecting the file.
|
||||
|
||||
Arguments:
|
||||
path (str): The path to select for printing. Either an absolute path (local file) or a
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def unselect_file(self):
|
||||
"""
|
||||
Unselects and currently selected file.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def start_print(self):
|
||||
"""
|
||||
Starts printing the currently selected file. If no file is currently selected, does nothing.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def toggle_pause_print(self):
|
||||
"""
|
||||
Pauses the current print job if it is currently running or resumes it if it is currently paused.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def cancel_print(self):
|
||||
"""
|
||||
Cancels the current print job.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_state_string(self):
|
||||
"""
|
||||
Returns:
|
||||
(str) A human readable string corresponding to the current communication state.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_current_data(self):
|
||||
"""
|
||||
Returns:
|
||||
(dict) The current state data.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_current_job(self):
|
||||
"""
|
||||
Returns:
|
||||
(dict) The data of the current job.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_current_temperatures(self):
|
||||
"""
|
||||
Returns:
|
||||
(dict) The current temperatures.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_temperature_history(self):
|
||||
"""
|
||||
Returns:
|
||||
(list) The temperature history.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_current_connection(self):
|
||||
"""
|
||||
Returns:
|
||||
(tuple) The current connection information as a 4-tuple ``(connection_string, port, baudrate, printer_profile)``.
|
||||
If the printer is currently not connected, the tuple will be ``("Closed", None, None, None)``.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_closed_or_error(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently disconnected and/or in an error state.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_operational(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently connected and available.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_printing(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently printing.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_paused(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently paused.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_error(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently in an error state.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_ready(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently operational and ready for new print jobs (not printing).
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def register_callback(self, callback):
|
||||
"""
|
||||
Registers a :class:`PrinterCallback` with the instance.
|
||||
|
||||
Arguments:
|
||||
callback (PrinterCallback): The callback object to register.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def unregister_callback(self, callback):
|
||||
"""
|
||||
Unregisters a :class:`PrinterCallback` from the instance.
|
||||
|
||||
Arguments:
|
||||
callback (PrinterCallback): The callback object to unregister.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class PrinterCallback(object):
|
||||
def on_printer_add_log(self, data):
|
||||
"""
|
||||
Called when the :class:`PrinterInterface` receives a new communication log entry from the communication layer.
|
||||
|
||||
Arguments:
|
||||
data (str): The received log line.
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_printer_add_message(self, data):
|
||||
"""
|
||||
Called when the :class:`PrinterInterface` receives a new message from the communication layer.
|
||||
|
||||
Arguments:
|
||||
data (str): The received message.
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_printer_add_temperature(self, data):
|
||||
"""
|
||||
Called when the :class:`PrinterInterface` receives a new temperature data set from the communication layer.
|
||||
|
||||
``data`` is a ``dict`` of the following structure::
|
||||
|
||||
tool0:
|
||||
actual: <temperature of the first hotend, in degC>
|
||||
target: <target temperature of the first hotend, in degC>
|
||||
...
|
||||
bed:
|
||||
actual: <temperature of the bed, in degC>
|
||||
target: <target temperature of the bed, in degC>
|
||||
|
||||
Arguments:
|
||||
data (dict): A dict of all current temperatures in the format as specified above
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_printer_received_registered_message(self, name, output):
|
||||
"""
|
||||
Called when the :class:`PrinterInterface` received a registered message, e.g. from a feedback command.
|
||||
|
||||
Arguments:
|
||||
name (str): Name of the registered message (e.g. the feedback command)
|
||||
output (str): Output for the registered message
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_printer_send_initial_data(self, data):
|
||||
"""
|
||||
Called when registering as a callback with the :class:`PrinterInterface` to receive the initial data (state,
|
||||
log and temperature history etc) from the printer.
|
||||
|
||||
``data`` is a ``dict`` of the following structure::
|
||||
|
||||
temps:
|
||||
- time: <timestamp of the temperature data point>
|
||||
tool0:
|
||||
actual: <temperature of the first hotend, in degC>
|
||||
target: <target temperature of the first hotend, in degC>
|
||||
...
|
||||
bed:
|
||||
actual: <temperature of the bed, in degC>
|
||||
target: <target temperature of the bed, in degC>
|
||||
- ...
|
||||
logs: <list of current communication log lines>
|
||||
messages: <list of current messages from the firmware>
|
||||
|
||||
Arguments:
|
||||
data (dict): The initial data in the format as specified above.
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_printer_send_current_data(self, data):
|
||||
"""
|
||||
Called when the internal state of the :class:`PrinterInterface` changes, due to changes in the printer state,
|
||||
temperatures, log lines, job progress etc. Updates via this method are guaranteed to be throttled to a maximum
|
||||
of 2 calles per second.
|
||||
|
||||
``data`` is a ``dict`` of the following structure::
|
||||
|
||||
state:
|
||||
text: <current state string>
|
||||
flags:
|
||||
operational: <whether the printer is currently connected and responding>
|
||||
printing: <whether the printer is currently printing>
|
||||
closedOrError: <whether the printer is currently disconnected and/or in an error state>
|
||||
error: <whether the printer is currently in an error state>
|
||||
paused: <whether the printer is currently paused>
|
||||
ready: <whether the printer is operational and ready for jobs>
|
||||
sdReady: <whether an SD card is present>
|
||||
job:
|
||||
file:
|
||||
name: <name of the file>,
|
||||
size: <size of the file in bytes>,
|
||||
origin: <origin of the file, "local" or "sdcard">,
|
||||
date: <last modification date of the file>
|
||||
estimatedPrintTime: <estimated print time of the file in seconds>
|
||||
lastPrintTime: <last print time of the file in seconds>
|
||||
filament:
|
||||
length: <estimated length of filament needed for this file, in mm>
|
||||
volume: <estimated volume of filament needed for this file, in ccm>
|
||||
progress:
|
||||
completion: <progress of the print job in percent (0-100)>
|
||||
filepos: <current position in the file in bytes>
|
||||
printTime: <current time elapsed for printing, in seconds>
|
||||
printTimeLeft: <estimated time left to finish printing, in seconds>
|
||||
currentZ: <current position of the z axis, in mm>
|
||||
offsets: <current configured temperature offsets, keys are "bed" or "tool[0-9]+", values the offset in degC>
|
||||
|
||||
Arguments:
|
||||
data (dict): The current data in the format as specified above.
|
||||
"""
|
||||
pass
|
||||
|
||||
class UnknownScript(BaseException):
|
||||
def __init__(self, name, *args, **kwargs):
|
||||
self.name = name
|
||||
@@ -0,0 +1,74 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
class TimeEstimationHelper(object):
|
||||
|
||||
STABLE_THRESHOLD = 0.1
|
||||
STABLE_COUNTDOWN = 250
|
||||
STABLE_ROLLING_WINDOW = 250
|
||||
|
||||
def __init__(self, rolling_window=None, countdown=None, threshold=None):
|
||||
if rolling_window is None:
|
||||
rolling_window = self.__class__.STABLE_ROLLING_WINDOW
|
||||
if countdown is None:
|
||||
countdown = self.__class__.STABLE_COUNTDOWN
|
||||
if threshold is None:
|
||||
threshold = self.__class__.STABLE_THRESHOLD
|
||||
|
||||
self._rolling_window = rolling_window
|
||||
self._countdown = countdown
|
||||
self._threshold = threshold
|
||||
|
||||
import collections
|
||||
self._distances = collections.deque([], self._rolling_window)
|
||||
self._totals = collections.deque([], self._rolling_window)
|
||||
self._sum_total = 0
|
||||
self._count = 0
|
||||
self._stable_counter = None
|
||||
|
||||
def is_stable(self):
|
||||
return self._stable_counter is not None and self._stable_counter >= self._countdown
|
||||
|
||||
def update(self, newEstimate):
|
||||
old_average_total = self.average_total
|
||||
|
||||
self._sum_total += newEstimate
|
||||
self._totals.append(newEstimate)
|
||||
self._count += 1
|
||||
|
||||
if old_average_total:
|
||||
self._distances.append(abs(self.average_total - old_average_total))
|
||||
|
||||
if -1.0 * self._threshold < self.average_distance < self._threshold:
|
||||
if self._stable_counter is None:
|
||||
self._stable_counter = 0
|
||||
else:
|
||||
self._stable_counter += 1
|
||||
else:
|
||||
self._stable_counter = None
|
||||
|
||||
@property
|
||||
def average_total(self):
|
||||
if not self._count:
|
||||
return None
|
||||
else:
|
||||
return self._sum_total / self._count
|
||||
|
||||
@property
|
||||
def average_total_rolling(self):
|
||||
if not self._count or self._count < self._rolling_window:
|
||||
return None
|
||||
else:
|
||||
return sum(self._totals) / len(self._totals)
|
||||
|
||||
@property
|
||||
def average_distance(self):
|
||||
if not self._count or self._count < self._rolling_window + 1:
|
||||
return None
|
||||
else:
|
||||
return sum(self._distances) / len(self._distances)
|
||||
@@ -0,0 +1,402 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import os
|
||||
import copy
|
||||
import re
|
||||
import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import dict_merge, dict_clean, dict_contains_keys
|
||||
|
||||
class SaveError(Exception):
|
||||
pass
|
||||
|
||||
class CouldNotOverwriteError(SaveError):
|
||||
pass
|
||||
|
||||
class InvalidProfileError(Exception):
|
||||
pass
|
||||
|
||||
class BedTypes(object):
|
||||
RECTANGULAR = "rectangular"
|
||||
CIRCULAR = "circular"
|
||||
|
||||
@classmethod
|
||||
def values(cls):
|
||||
return [getattr(cls, name) for name in cls.__dict__ if not name.startswith("__")]
|
||||
|
||||
class PrinterProfileManager(object):
|
||||
"""
|
||||
Manager for printer profiles. Offers methods to select the globally used printer profile and to list, add, remove,
|
||||
load and save printer profiles.
|
||||
|
||||
A printer profile is a ``dict`` of the following structure:
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Type
|
||||
- Description
|
||||
* - ``id``
|
||||
- ``string``
|
||||
- Internal id of the printer profile
|
||||
* - ``name``
|
||||
- ``string``
|
||||
- Human readable name of the printer profile
|
||||
* - ``model``
|
||||
- ``string``
|
||||
- Printer model
|
||||
* - ``color``
|
||||
- ``string``
|
||||
- Color to associate with the printer profile
|
||||
* - ``volume``
|
||||
- ``dict``
|
||||
- Information about the print volume
|
||||
* - ``volume.width``
|
||||
- ``float``
|
||||
- Width of the print volume (X axis)
|
||||
* - ``volume.depth``
|
||||
- ``float``
|
||||
- Depth of the print volume (Y axis)
|
||||
* - ``volume.height``
|
||||
- ``float``
|
||||
- Height of the print volume (Z axis)
|
||||
* - ``volume.formFactor``
|
||||
- ``string``
|
||||
- Form factor of the print bed, either ``rectangular`` or ``circular``
|
||||
* - ``heatedBed``
|
||||
- ``bool``
|
||||
- Whether the printer has a heated bed (``True``) or not (``False``)
|
||||
* - ``extruder``
|
||||
- ``dict``
|
||||
- Information about the printer's extruders
|
||||
* - ``extruder.count``
|
||||
- ``int``
|
||||
- How many extruders the printer has (default 1)
|
||||
* - ``extruder.offsets``
|
||||
- ``list`` of ``tuple``s
|
||||
- Extruder offsets relative to first extruder, list of (x, y) tuples, first is always (0,0)
|
||||
* - ``extruder.nozzleDiameter``
|
||||
- ``float``
|
||||
- Diameter of the printer nozzle
|
||||
* - ``axes``
|
||||
- ``dict``
|
||||
- Information about the printer axes
|
||||
* - ``axes.x``
|
||||
- ``dict``
|
||||
- Information about the printer's X axis
|
||||
* - ``axes.x.speed``
|
||||
- ``float``
|
||||
- Speed of the X axis in mm/s
|
||||
* - ``axes.x.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
|
||||
* - ``axes.y``
|
||||
- ``dict``
|
||||
- Information about the printer's Y axis
|
||||
* - ``axes.y.speed``
|
||||
- ``float``
|
||||
- Speed of the Y axis in mm/s
|
||||
* - ``axes.y.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
|
||||
* - ``axes.z``
|
||||
- ``dict``
|
||||
- Information about the printer's Z axis
|
||||
* - ``axes.z.speed``
|
||||
- ``float``
|
||||
- Speed of the Z axis in mm/s
|
||||
* - ``axes.z.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed (False, default) or towards it (True)
|
||||
* - ``axes.e``
|
||||
- ``dict``
|
||||
- Information about the printer's E axis
|
||||
* - ``axes.e.speed``
|
||||
- ``float``
|
||||
- Speed of the E axis in mm/s
|
||||
* - ``axes.e.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change extrudes (False, default) or retracts (True) filament
|
||||
"""
|
||||
|
||||
default = dict(
|
||||
id = "_default",
|
||||
name = "Default",
|
||||
model = "Generic RepRap Printer",
|
||||
color = "default",
|
||||
volume=dict(
|
||||
width = 200,
|
||||
depth = 200,
|
||||
height = 200,
|
||||
formFactor = BedTypes.RECTANGULAR,
|
||||
),
|
||||
heatedBed = False,
|
||||
extruder=dict(
|
||||
count = 1,
|
||||
offsets = [
|
||||
(0, 0)
|
||||
],
|
||||
nozzleDiameter = 0.4
|
||||
),
|
||||
axes=dict(
|
||||
x = dict(speed=6000, inverted=False),
|
||||
y = dict(speed=6000, inverted=False),
|
||||
z = dict(speed=200, inverted=False),
|
||||
e = dict(speed=300, inverted=False)
|
||||
)
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
self._current = None
|
||||
self._folder = settings().getBaseFolder("printerProfiles")
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
def select(self, identifier):
|
||||
if identifier is None or not self.exists(identifier):
|
||||
self._current = self.get_default()
|
||||
return False
|
||||
else:
|
||||
self._current = self.get(identifier)
|
||||
return True
|
||||
|
||||
def deselect(self):
|
||||
self._current = None
|
||||
|
||||
def get_all(self):
|
||||
return self._load_all()
|
||||
|
||||
def get(self, identifier):
|
||||
try:
|
||||
if identifier == "_default":
|
||||
return self._load_default()
|
||||
elif self.exists(identifier):
|
||||
return self._load_from_path(self._get_profile_path(identifier))
|
||||
else:
|
||||
return None
|
||||
except InvalidProfileError:
|
||||
return None
|
||||
|
||||
def remove(self, identifier):
|
||||
if identifier == "_default":
|
||||
return False
|
||||
return self._remove_from_path(self._get_profile_path(identifier))
|
||||
|
||||
def save(self, profile, allow_overwrite=False, make_default=False):
|
||||
if "id" in profile:
|
||||
identifier = profile["id"]
|
||||
elif "name" in profile:
|
||||
identifier = profile["name"]
|
||||
else:
|
||||
raise InvalidProfileError("profile must contain either id or name")
|
||||
|
||||
identifier = self._sanitize(identifier)
|
||||
profile["id"] = identifier
|
||||
profile = dict_clean(profile, self.__class__.default)
|
||||
|
||||
if identifier == "_default":
|
||||
default_profile = dict_merge(self._load_default(), profile)
|
||||
if not self._ensure_valid_profile(default_profile):
|
||||
raise InvalidProfileError()
|
||||
|
||||
settings().set(["printerProfiles", "defaultProfile"], default_profile, defaults=dict(printerProfiles=dict(defaultProfile=self.__class__.default)))
|
||||
settings().save()
|
||||
else:
|
||||
self._save_to_path(self._get_profile_path(identifier), profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
if make_default:
|
||||
settings().set(["printerProfiles", "default"], identifier)
|
||||
|
||||
return self.get(identifier)
|
||||
|
||||
def get_default(self):
|
||||
default = settings().get(["printerProfiles", "default"])
|
||||
if default is not None and self.exists(default):
|
||||
profile = self.get(default)
|
||||
if profile is not None:
|
||||
return profile
|
||||
|
||||
return self._load_default()
|
||||
|
||||
def set_default(self, identifier):
|
||||
all_identifiers = self._load_all_identifiers().keys()
|
||||
if identifier is not None and not identifier in all_identifiers:
|
||||
return
|
||||
|
||||
settings().set(["printerProfile", "default"], identifier)
|
||||
settings().save()
|
||||
|
||||
def get_current_or_default(self):
|
||||
if self._current is not None:
|
||||
return self._current
|
||||
else:
|
||||
return self.get_default()
|
||||
|
||||
def get_current(self):
|
||||
return self._current
|
||||
|
||||
def exists(self, identifier):
|
||||
if identifier is None:
|
||||
return False
|
||||
elif identifier == "_default":
|
||||
return True
|
||||
else:
|
||||
path = self._get_profile_path(identifier)
|
||||
return os.path.exists(path) and os.path.isfile(path)
|
||||
|
||||
def _load_all(self):
|
||||
all_identifiers = self._load_all_identifiers()
|
||||
results = dict()
|
||||
for identifier, path in all_identifiers.items():
|
||||
try:
|
||||
if identifier == "_default":
|
||||
profile = self._load_default()
|
||||
else:
|
||||
profile = self._load_from_path(path)
|
||||
except InvalidProfileError:
|
||||
continue
|
||||
|
||||
if profile is None:
|
||||
continue
|
||||
|
||||
results[identifier] = dict_merge(self._load_default(), profile)
|
||||
return results
|
||||
|
||||
def _load_all_identifiers(self):
|
||||
results = dict(_default=None)
|
||||
for entry in os.listdir(self._folder):
|
||||
if entry.startswith(".") or not entry.endswith(".profile") or entry == "_default.profile":
|
||||
continue
|
||||
|
||||
path = os.path.join(self._folder, entry)
|
||||
if not os.path.isfile(path):
|
||||
continue
|
||||
|
||||
identifier = entry[:-len(".profile")]
|
||||
results[identifier] = path
|
||||
return results
|
||||
|
||||
def _load_from_path(self, path):
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
return None
|
||||
|
||||
import yaml
|
||||
with open(path) as f:
|
||||
profile = yaml.safe_load(f)
|
||||
profile = self._ensure_valid_profile(profile)
|
||||
if not profile:
|
||||
self._logger.warn("Invalid profile: %s" % path)
|
||||
raise InvalidProfileError()
|
||||
return profile
|
||||
|
||||
def _save_to_path(self, path, profile, allow_overwrite=False):
|
||||
validated_profile = self._ensure_valid_profile(profile)
|
||||
if not validated_profile:
|
||||
raise InvalidProfileError()
|
||||
|
||||
if os.path.exists(path) and not allow_overwrite:
|
||||
raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"])
|
||||
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
try:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except Exception as e:
|
||||
raise SaveError("Cannot save profile %s: %s" % (profile["id"], e.message))
|
||||
|
||||
def _remove_from_path(self, path):
|
||||
try:
|
||||
os.remove(path)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
def _load_default(self):
|
||||
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
|
||||
profile = self._ensure_valid_profile(dict_merge(copy.deepcopy(self.__class__.default), default_overrides))
|
||||
if not profile:
|
||||
self._logger.warn("Invalid default profile after applying overrides")
|
||||
return copy.deepcopy(self.__class__.default)
|
||||
return profile
|
||||
|
||||
def _get_profile_path(self, identifier):
|
||||
return os.path.join(self._folder, "%s.profile" % identifier)
|
||||
|
||||
def _sanitize(self, name):
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
import string
|
||||
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
|
||||
sanitized_name = ''.join(c for c in name if c in valid_chars)
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name
|
||||
|
||||
def _ensure_valid_profile(self, profile):
|
||||
# ensure all keys are present
|
||||
if not dict_contains_keys(self.default, profile):
|
||||
return False
|
||||
|
||||
# conversion helper
|
||||
def convert_value(profile, path, converter):
|
||||
value = profile
|
||||
for part in path[:-1]:
|
||||
if not isinstance(value, dict) or not part in value:
|
||||
raise RuntimeError("%s is not contained in profile" % ".".join(path))
|
||||
value = value[part]
|
||||
|
||||
if not isinstance(value, dict) or not path[-1] in value:
|
||||
raise RuntimeError("%s is not contained in profile" % ".".join(path))
|
||||
|
||||
value[path[-1]] = converter(value[path[-1]])
|
||||
|
||||
# convert ints
|
||||
for path in (("extruder", "count"), ("axes", "x", "speed"), ("axes", "y", "speed"), ("axes", "z", "speed")):
|
||||
try:
|
||||
convert_value(profile, path, int)
|
||||
except:
|
||||
return False
|
||||
|
||||
# convert floats
|
||||
for path in (("volume", "width"), ("volume", "depth"), ("volume", "height"), ("extruder", "nozzleDiameter")):
|
||||
try:
|
||||
convert_value(profile, path, float)
|
||||
except:
|
||||
return False
|
||||
|
||||
# convert booleans
|
||||
for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted")):
|
||||
try:
|
||||
convert_value(profile, path, bool)
|
||||
except:
|
||||
return False
|
||||
|
||||
# validate form factor
|
||||
if not profile["volume"]["formFactor"] in BedTypes.values():
|
||||
return False
|
||||
|
||||
# validate offsets
|
||||
offsets = []
|
||||
for offset in profile["extruder"]["offsets"]:
|
||||
if not len(offset) == 2:
|
||||
return False
|
||||
x_offset, y_offset = offset
|
||||
try:
|
||||
offsets.append((float(x_offset), float(y_offset)))
|
||||
except:
|
||||
return False
|
||||
profile["extruder"]["offsets"] = offsets
|
||||
|
||||
return profile
|
||||
|
||||
@@ -0,0 +1,927 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
This module holds the standard implementation of the :class:`PrinterInterface` and it helpers.
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import copy
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
from octoprint import util as util
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import FileDestinations
|
||||
from octoprint.plugin import plugin_manager, ProgressPlugin
|
||||
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript
|
||||
from octoprint.printer.estimation import TimeEstimationHelper
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import comm as comm
|
||||
|
||||
|
||||
class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
"""
|
||||
Default implementation of the :class:`PrinterInterface`. Manages the communication layer object and registers
|
||||
itself with it as a callback to react to changes on the communication layer.
|
||||
"""
|
||||
|
||||
def __init__(self, fileManager, analysisQueue, printerProfileManager):
|
||||
from collections import deque
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._analysisQueue = analysisQueue
|
||||
self._fileManager = fileManager
|
||||
self._printerProfileManager = printerProfileManager
|
||||
|
||||
# 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 = deque([], 300)
|
||||
self._tempBacklog = []
|
||||
|
||||
self._latestMessage = None
|
||||
self._messages = deque([], 300)
|
||||
self._messageBacklog = []
|
||||
|
||||
self._latestLog = None
|
||||
self._log = deque([], 300)
|
||||
self._logBacklog = []
|
||||
|
||||
self._state = None
|
||||
|
||||
self._currentZ = None
|
||||
|
||||
self._progress = None
|
||||
self._printTime = None
|
||||
self._printTimeLeft = None
|
||||
|
||||
self._printAfterSelect = False
|
||||
|
||||
# sd handling
|
||||
self._sdPrinting = False
|
||||
self._sdStreaming = False
|
||||
self._sdFilelistAvailable = threading.Event()
|
||||
self._streamingFinishedCallback = None
|
||||
|
||||
self._selectedFile = None
|
||||
self._timeEstimationData = None
|
||||
|
||||
# comm
|
||||
self._comm = None
|
||||
|
||||
# callbacks
|
||||
self._callbacks = []
|
||||
|
||||
# progress plugins
|
||||
self._lastProgressReport = None
|
||||
self._progressPlugins = plugin_manager().get_implementations(ProgressPlugin)
|
||||
|
||||
self._stateMonitor = StateMonitor(
|
||||
interval=0.5,
|
||||
on_update=self._sendCurrentDataCallbacks,
|
||||
on_add_temperature=self._sendAddTemperatureCallbacks,
|
||||
on_add_log=self._sendAddLogCallbacks,
|
||||
on_add_message=self._sendAddMessageCallbacks
|
||||
)
|
||||
self._stateMonitor.reset(
|
||||
state={"text": self.get_state_string(), "flags": self._getStateFlags()},
|
||||
job_data={
|
||||
"file": {
|
||||
"name": None,
|
||||
"size": None,
|
||||
"origin": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"lastPrintTime": None,
|
||||
"filament": {
|
||||
"length": None,
|
||||
"volume": None
|
||||
}
|
||||
},
|
||||
progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
|
||||
current_z=None
|
||||
)
|
||||
|
||||
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self._on_event_MetadataAnalysisFinished)
|
||||
eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self._on_event_MetadataStatisticsUpdated)
|
||||
|
||||
#~~ handling of PrinterCallbacks
|
||||
|
||||
def register_callback(self, callback):
|
||||
if not isinstance(callback, PrinterCallback):
|
||||
self._logger.warn("Registering an object as printer callback which doesn't implement the PrinterCallback interface")
|
||||
|
||||
self._callbacks.append(callback)
|
||||
self._sendInitialStateUpdate(callback)
|
||||
|
||||
def unregister_callback(self, callback):
|
||||
if callback in self._callbacks:
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def _sendAddTemperatureCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_add_temperature(data)
|
||||
except: self._logger.exception("Exception while adding temperature data point")
|
||||
|
||||
def _sendAddLogCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_add_log(data)
|
||||
except: self._logger.exception("Exception while adding communication log entry")
|
||||
|
||||
def _sendAddMessageCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_add_message(data)
|
||||
except: self._logger.exception("Exception while adding printer message")
|
||||
|
||||
def _sendCurrentDataCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_send_current_data(copy.deepcopy(data))
|
||||
except: self._logger.exception("Exception while pushing current data")
|
||||
|
||||
#~~ callback from metadata analysis event
|
||||
|
||||
def _on_event_MetadataAnalysisFinished(self, event, data):
|
||||
if self._selectedFile:
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
|
||||
def _on_event_MetadataStatisticsUpdated(self, event, data):
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
|
||||
#~~ progress plugin reporting
|
||||
|
||||
def _reportPrintProgressToPlugins(self, progress):
|
||||
if not progress or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile:
|
||||
return
|
||||
|
||||
storage = "sdcard" if self._selectedFile["sd"] else "local"
|
||||
filename = self._selectedFile["filename"]
|
||||
|
||||
def call_plugins(storage, filename, progress):
|
||||
for name, plugin in self._progressPlugins.items():
|
||||
try:
|
||||
plugin.on_print_progress(storage, filename, progress)
|
||||
except:
|
||||
self._logger.exception("Exception while sending print progress to plugin %s" % name)
|
||||
|
||||
thread = threading.Thread(target=call_plugins, args=(storage, filename, progress))
|
||||
thread.daemon = False
|
||||
thread.start()
|
||||
|
||||
#~~ PrinterInterface implementation
|
||||
|
||||
def connect(self, port=None, baudrate=None, profile=None):
|
||||
"""
|
||||
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
|
||||
will be attempted.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._printerProfileManager.select(profile)
|
||||
self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager)
|
||||
|
||||
def disconnect(self):
|
||||
"""
|
||||
Closes the connection to the printer.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = None
|
||||
self._printerProfileManager.deselect()
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
def get_transport(self):
|
||||
|
||||
if self._comm is None:
|
||||
return None
|
||||
|
||||
return self._comm.getTransport()
|
||||
getTransport = util.deprecated("getTransport has been renamed to get_transport", since="1.2.0-dev-590", includedoc="Replaced by :func:`get_transport`")
|
||||
|
||||
def commands(self, commands):
|
||||
"""
|
||||
Sends one or more gcode commands to the printer.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
if not isinstance(commands, (list, tuple)):
|
||||
commands = [commands]
|
||||
|
||||
for command in commands:
|
||||
self._comm.sendCommand(command)
|
||||
|
||||
def script(self, name, context=None):
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
if name is None or not name:
|
||||
raise ValueError("name must be set")
|
||||
|
||||
result = self._comm.sendGcodeScript(name, replacements=context)
|
||||
if not result:
|
||||
raise UnknownScript(name)
|
||||
|
||||
def jog(self, axis, amount):
|
||||
if not isinstance(axis, (str, unicode)):
|
||||
raise ValueError("axis must be a string: {axis}".format(axis=axis))
|
||||
|
||||
axis = axis.lower()
|
||||
if not axis in PrinterInterface.valid_axes:
|
||||
raise ValueError("axis must be any of {axes}: {axis}".format(axes=", ".join(PrinterInterface.valid_axes), axis=axis))
|
||||
if not isinstance(amount, (int, long, float)):
|
||||
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
|
||||
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
movement_speed = printer_profile["axes"][axis]["speed"]
|
||||
self.commands(["G91", "G1 %s%.4f F%d" % (axis.upper(), amount, movement_speed), "G90"])
|
||||
|
||||
def home(self, axes):
|
||||
if not isinstance(axes, (list, tuple)):
|
||||
if isinstance(axes, (str, unicode)):
|
||||
axes = [axes]
|
||||
else:
|
||||
raise ValueError("axes is neither a list nor a string: {axes}".format(axes=axes))
|
||||
|
||||
validated_axes = filter(lambda x: x in PrinterInterface.valid_axes, map(lambda x: x.lower(), axes))
|
||||
if len(axes) != len(validated_axes):
|
||||
raise ValueError("axes contains invalid axes: {axes}".format(axes=axes))
|
||||
|
||||
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"])
|
||||
|
||||
def extrude(self, amount):
|
||||
if not isinstance(amount, (int, long, float)):
|
||||
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
|
||||
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
extrusion_speed = printer_profile["axes"]["e"]["speed"]
|
||||
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"])
|
||||
|
||||
def change_tool(self, tool):
|
||||
if not PrinterInterface.valid_tool_regex.match(tool):
|
||||
raise ValueError("tool must match \"tool[0-9]+\": {tool}".format(tool=tool))
|
||||
|
||||
tool_num = int(tool[len("tool"):])
|
||||
self.commands("T%d" % tool_num)
|
||||
|
||||
def set_temperature(self, heater, value):
|
||||
if not PrinterInterface.valid_heater_regex.match(heater):
|
||||
raise ValueError("heater must match \"tool[0-9]+\" or \"bed\": {heater}".format(type=heater))
|
||||
|
||||
if not isinstance(value, (int, long, float)) or value < 0:
|
||||
raise ValueError("value must be a valid number >= 0: {value}".format(value=value))
|
||||
|
||||
if heater.startswith("tool"):
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
extruder_count = printer_profile["extruder"]["count"]
|
||||
if extruder_count > 1:
|
||||
toolNum = int(heater[len("tool"):])
|
||||
self.commands("M104 T%d S%f" % (toolNum, value))
|
||||
else:
|
||||
self.commands("M104 S%f" % value)
|
||||
|
||||
elif heater == "bed":
|
||||
self.commands("M140 S%f" % value)
|
||||
|
||||
def set_temperature_offset(self, offsets=None):
|
||||
if offsets is None:
|
||||
offsets = dict()
|
||||
|
||||
if not isinstance(offsets, dict):
|
||||
raise ValueError("offsets must be a dict")
|
||||
|
||||
validated_keys = filter(lambda x: PrinterInterface.valid_heater_regex.match(x), offsets.keys())
|
||||
validated_values = filter(lambda x: isinstance(x, (int, long, float)), offsets.values())
|
||||
|
||||
if len(validated_keys) != len(offsets):
|
||||
raise ValueError("offsets contains invalid keys: {offsets}".format(offsets=offsets))
|
||||
if len(validated_values) != len(offsets):
|
||||
raise ValueError("offsets contains invalid values: {offsets}".format(offsets=offsets))
|
||||
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.setTemperatureOffset(offsets)
|
||||
self._stateMonitor.set_temp_offsets(offsets)
|
||||
|
||||
def _convert_rate_value(self, factor, min=0, max=200):
|
||||
if not isinstance(factor, (int, float, long)):
|
||||
raise ValueError("factor is not a number")
|
||||
|
||||
if isinstance(factor, float):
|
||||
factor = int(factor * 100.0)
|
||||
|
||||
if factor < min or factor > max:
|
||||
raise ValueError("factor must be a value between %f and %f" % (min, max))
|
||||
|
||||
return factor
|
||||
|
||||
def feed_rate(self, factor):
|
||||
factor = self._convert_rate_value(factor, min=50, max=200)
|
||||
self.commands("M220 S%d" % factor)
|
||||
|
||||
def flow_rate(self, factor):
|
||||
factor = self._convert_rate_value(factor, min=75, max=125)
|
||||
self.commands("M221 S%d" % factor)
|
||||
|
||||
def select_file(self, path, sd, printAfterSelect=False):
|
||||
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
self._logger.info("Cannot load file: printer not connected or currently busy")
|
||||
return
|
||||
|
||||
self._printAfterSelect = printAfterSelect
|
||||
self._comm.selectFile("/" + path if sd else path, sd)
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def unselect_file(self):
|
||||
if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
return
|
||||
|
||||
self._comm.unselectFile()
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def start_print(self):
|
||||
"""
|
||||
Starts the currently loaded print job.
|
||||
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
|
||||
"""
|
||||
if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting():
|
||||
return
|
||||
if self._selectedFile is None:
|
||||
return
|
||||
|
||||
rolling_window = None
|
||||
threshold = None
|
||||
countdown = None
|
||||
if self._selectedFile["sd"]:
|
||||
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
|
||||
# by that divided by the sd status polling interval
|
||||
rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"])
|
||||
|
||||
# we are happy if the average of the estimates stays within 60s of the prior one
|
||||
threshold = 60
|
||||
|
||||
# we are happy when one rolling window has been stable
|
||||
countdown = rolling_window
|
||||
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
|
||||
|
||||
self._lastProgressReport = None
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint()
|
||||
|
||||
def toggle_pause_print(self):
|
||||
"""
|
||||
Pause the current printjob.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.setPause(not self._comm.isPaused())
|
||||
|
||||
def cancel_print(self):
|
||||
"""
|
||||
Cancel the current printjob.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.cancelPrint()
|
||||
|
||||
# reset progress, height, print time
|
||||
self._setCurrentZ(None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
payload = {
|
||||
"file": self._selectedFile["filename"],
|
||||
"origin": FileDestinations.LOCAL
|
||||
}
|
||||
if self._selectedFile["sd"]:
|
||||
payload["origin"] = FileDestinations.SDCARD
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
def get_state_string(self):
|
||||
"""
|
||||
Returns a human readable string corresponding to the current communication state.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return "Offline"
|
||||
else:
|
||||
return self._comm.getStateString()
|
||||
|
||||
def get_current_data(self):
|
||||
return self._stateMonitor.get_current_data()
|
||||
|
||||
def get_current_job(self):
|
||||
currentData = self._stateMonitor.get_current_data()
|
||||
return currentData["job"]
|
||||
|
||||
def get_current_temperatures(self):
|
||||
if self._comm is not None:
|
||||
tempOffset, bedTempOffset = self._comm.getOffsets()
|
||||
else:
|
||||
tempOffset = {}
|
||||
bedTempOffset = None
|
||||
|
||||
result = {}
|
||||
if self._temp is not None:
|
||||
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 get_temperature_history(self):
|
||||
return self._temps
|
||||
|
||||
def get_current_connection(self):
|
||||
if self._comm is None:
|
||||
return "Closed", None, None, None
|
||||
|
||||
port, baudrate = self._comm.getConnection()
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
return self._comm.getStateString(), port, baudrate, printer_profile
|
||||
|
||||
def is_closed_or_error(self):
|
||||
return self._comm is None or self._comm.isClosedOrError()
|
||||
|
||||
def is_operational(self):
|
||||
return self._comm is not None and self._comm.isOperational()
|
||||
|
||||
def is_printing(self):
|
||||
return self._comm is not None and self._comm.isPrinting()
|
||||
|
||||
def is_paused(self):
|
||||
return self._comm is not None and self._comm.isPaused()
|
||||
|
||||
def is_error(self):
|
||||
return self._comm is not None and self._comm.isError()
|
||||
|
||||
def is_ready(self):
|
||||
return self.is_operational() and not self._comm.isStreaming()
|
||||
|
||||
def is_sd_ready(self):
|
||||
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
|
||||
return False
|
||||
else:
|
||||
return self._comm.isSdReady()
|
||||
|
||||
#~~ sd file handling
|
||||
|
||||
def get_sd_files(self):
|
||||
if self._comm is None or not self._comm.isSdReady():
|
||||
return []
|
||||
return map(lambda x: (x[0][1:], x[1]), self._comm.getSdFiles())
|
||||
|
||||
def add_sd_file(self, filename, absolutePath, streamingFinishedCallback):
|
||||
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
|
||||
self._logger.error("No connection to printer or printer is busy")
|
||||
return
|
||||
|
||||
self._streamingFinishedCallback = streamingFinishedCallback
|
||||
|
||||
self.refresh_sd_files(blocking=True)
|
||||
existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles())
|
||||
|
||||
remoteName = util.get_dos_filename(filename, existing_filenames=existingSdFiles, extension="gco")
|
||||
self._timeEstimationData = TimeEstimationHelper()
|
||||
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName)
|
||||
|
||||
return remoteName
|
||||
|
||||
def delete_sd_file(self, filename):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.deleteSdFile("/" + filename)
|
||||
|
||||
def init_sd_card(self):
|
||||
if not self._comm or self._comm.isSdReady():
|
||||
return
|
||||
self._comm.initSdCard()
|
||||
|
||||
def release_sd_card(self):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.releaseSdCard()
|
||||
|
||||
def refresh_sd_files(self, blocking=False):
|
||||
"""
|
||||
Refreshs the list of file stored on the SD card attached to printer (if available and printer communication
|
||||
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
|
||||
received (and can be accessed via self._comm.getSdFiles()). Defaults to an asynchronous operation.
|
||||
"""
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._sdFilelistAvailable.clear()
|
||||
self._comm.refreshSdFiles()
|
||||
if blocking:
|
||||
self._sdFilelistAvailable.wait(10000)
|
||||
|
||||
#~~ state monitoring
|
||||
|
||||
def _setCurrentZ(self, currentZ):
|
||||
self._currentZ = currentZ
|
||||
self._stateMonitor.set_current_z(self._currentZ)
|
||||
|
||||
def _setState(self, state):
|
||||
self._state = state
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def _addLog(self, log):
|
||||
self._log.append(log)
|
||||
self._stateMonitor.add_log(log)
|
||||
|
||||
def _addMessage(self, message):
|
||||
self._messages.append(message)
|
||||
self._stateMonitor.add_message(message)
|
||||
|
||||
def _estimateTotalPrintTime(self, progress, printTime):
|
||||
if not progress or not printTime or not self._timeEstimationData:
|
||||
return None
|
||||
|
||||
else:
|
||||
newEstimate = printTime / progress
|
||||
self._timeEstimationData.update(newEstimate)
|
||||
|
||||
result = None
|
||||
if self._timeEstimationData.is_stable():
|
||||
result = self._timeEstimationData.average_total_rolling
|
||||
|
||||
return result
|
||||
|
||||
def _setProgressData(self, progress, filepos, printTime, cleanedPrintTime):
|
||||
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
|
||||
totalPrintTime = estimatedTotalPrintTime
|
||||
|
||||
if self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"]:
|
||||
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
|
||||
if progress and cleanedPrintTime:
|
||||
if estimatedTotalPrintTime is None:
|
||||
totalPrintTime = statisticalTotalPrintTime
|
||||
else:
|
||||
if progress < 0.5:
|
||||
sub_progress = progress * 2
|
||||
else:
|
||||
sub_progress = 1.0
|
||||
totalPrintTime = (1 - sub_progress) * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime
|
||||
|
||||
self._progress = progress
|
||||
self._printTime = printTime
|
||||
self._printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None
|
||||
|
||||
self._stateMonitor.set_progress({
|
||||
"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) if self._printTimeLeft is not None else None
|
||||
})
|
||||
|
||||
if progress:
|
||||
progress_int = int(progress * 100)
|
||||
if self._lastProgressReport != progress_int:
|
||||
self._lastProgressReport = progress_int
|
||||
self._reportPrintProgressToPlugins(progress_int)
|
||||
|
||||
|
||||
def _addTemperatureData(self, temp, bedTemp):
|
||||
currentTimeUtc = int(time.time())
|
||||
|
||||
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._temps.append(data)
|
||||
|
||||
self._temp = temp
|
||||
self._bedTemp = bedTemp
|
||||
|
||||
self._stateMonitor.add_temperature(data)
|
||||
|
||||
def _setJobData(self, filename, filesize, sd):
|
||||
if filename is not None:
|
||||
if sd:
|
||||
path_in_storage = filename
|
||||
path_on_disk = None
|
||||
else:
|
||||
path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename)
|
||||
path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename)
|
||||
self._selectedFile = {
|
||||
"filename": path_in_storage,
|
||||
"filesize": filesize,
|
||||
"sd": sd,
|
||||
"estimatedPrintTime": None
|
||||
}
|
||||
else:
|
||||
self._selectedFile = None
|
||||
self._stateMonitor.set_job_data({
|
||||
"file": {
|
||||
"name": None,
|
||||
"origin": None,
|
||||
"size": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"averagePrintTime": None,
|
||||
"lastPrintTime": None,
|
||||
"filament": None,
|
||||
})
|
||||
return
|
||||
|
||||
estimatedPrintTime = None
|
||||
lastPrintTime = None
|
||||
averagePrintTime = None
|
||||
date = None
|
||||
filament = None
|
||||
if path_on_disk:
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(path_on_disk).st_ctime)
|
||||
|
||||
try:
|
||||
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
|
||||
except:
|
||||
fileData = None
|
||||
if fileData is not None:
|
||||
if "analysis" in fileData:
|
||||
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]:
|
||||
estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"]
|
||||
if "filament" in fileData["analysis"].keys():
|
||||
filament = fileData["analysis"]["filament"]
|
||||
if "statistics" in fileData:
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()["id"]
|
||||
if "averagePrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["averagePrintTime"]:
|
||||
averagePrintTime = fileData["statistics"]["averagePrintTime"][printer_profile]
|
||||
if "lastPrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["lastPrintTime"]:
|
||||
lastPrintTime = fileData["statistics"]["lastPrintTime"][printer_profile]
|
||||
|
||||
if averagePrintTime is not None:
|
||||
self._selectedFile["estimatedPrintTime"] = averagePrintTime
|
||||
elif estimatedPrintTime is not None:
|
||||
# TODO apply factor which first needs to be tracked!
|
||||
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
|
||||
|
||||
self._stateMonitor.set_job_data({
|
||||
"file": {
|
||||
"name": path_in_storage,
|
||||
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
"size": filesize,
|
||||
"date": date
|
||||
},
|
||||
"estimatedPrintTime": estimatedPrintTime,
|
||||
"averagePrintTime": averagePrintTime,
|
||||
"lastPrintTime": lastPrintTime,
|
||||
"filament": filament,
|
||||
})
|
||||
|
||||
def _sendInitialStateUpdate(self, callback):
|
||||
try:
|
||||
data = self._stateMonitor.get_current_data()
|
||||
data.update({
|
||||
"temps": list(self._temps),
|
||||
"logs": list(self._log),
|
||||
"messages": list(self._messages)
|
||||
})
|
||||
callback.on_printer_send_initial_data(data)
|
||||
except Exception, err:
|
||||
import sys
|
||||
sys.stderr.write("ERROR: %s\n" % str(err))
|
||||
pass
|
||||
|
||||
def _getStateFlags(self):
|
||||
return {
|
||||
"operational": self.is_operational(),
|
||||
"printing": self.is_printing(),
|
||||
"closedOrError": self.is_closed_or_error(),
|
||||
"error": self.is_error(),
|
||||
"paused": self.is_paused(),
|
||||
"ready": self.is_ready(),
|
||||
"sdReady": self.is_sd_ready()
|
||||
}
|
||||
|
||||
#~~ comm.MachineComPrintCallback implementation
|
||||
|
||||
def on_comm_log(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon log output.
|
||||
"""
|
||||
self._addLog(message)
|
||||
|
||||
def on_comm_temperature_update(self, temp, bedTemp):
|
||||
self._addTemperatureData(temp, bedTemp)
|
||||
|
||||
def on_comm_state_change(self, state):
|
||||
"""
|
||||
Callback method for the comm object, called if the connection state changes.
|
||||
"""
|
||||
oldState = self._state
|
||||
|
||||
# forward relevant state changes to gcode manager
|
||||
if self._comm is not None and oldState == self._comm.STATE_PRINTING:
|
||||
if self._selectedFile is not None:
|
||||
if state == self._comm.STATE_OPERATIONAL:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), True, self._printerProfileManager.get_current_or_default()["id"])
|
||||
elif state == self._comm.STATE_CLOSED or state == self._comm.STATE_ERROR or state == self._comm.STATE_CLOSED_WITH_ERROR:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
|
||||
elif self._comm is not None and state == self._comm.STATE_PRINTING:
|
||||
self._analysisQueue.pause() # do not analyse files while printing
|
||||
|
||||
self._setState(state)
|
||||
|
||||
def on_comm_message(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon message exchanges via serial.
|
||||
Stores the message in the message buffer, truncates buffer to the last 300 lines.
|
||||
"""
|
||||
self._addMessage(message)
|
||||
|
||||
def on_comm_progress(self):
|
||||
"""
|
||||
Callback method for the comm object, called upon any change in progress of the printjob.
|
||||
Triggers storage of new values for printTime, printTimeLeft and the current progress.
|
||||
"""
|
||||
|
||||
self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getCleanedPrintTime())
|
||||
|
||||
def on_comm_z_change(self, newZ):
|
||||
"""
|
||||
Callback method for the comm object, called upon change of the z-layer.
|
||||
"""
|
||||
oldZ = self._currentZ
|
||||
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(Events.Z_CHANGE, {"new": newZ, "old": oldZ})
|
||||
|
||||
self._setCurrentZ(newZ)
|
||||
|
||||
def on_comm_sd_state_change(self, sdReady):
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_sd_files(self, files):
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
|
||||
self._sdFilelistAvailable.set()
|
||||
|
||||
def on_comm_file_selected(self, filename, filesize, sd):
|
||||
self._setJobData(filename, filesize, sd)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
if self._printAfterSelect:
|
||||
self.start_print()
|
||||
|
||||
def on_comm_print_job_done(self):
|
||||
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_file_transfer_started(self, filename, filesize):
|
||||
self._sdStreaming = True
|
||||
|
||||
self._setJobData(filename, filesize, True)
|
||||
self._setProgressData(0.0, 0, 0, None)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_file_transfer_done(self, filename):
|
||||
self._sdStreaming = False
|
||||
|
||||
if self._streamingFinishedCallback is not None:
|
||||
# in case of SD files, both filename and absolutePath are the same, so we set the (remote) filename for
|
||||
# both parameters
|
||||
self._streamingFinishedCallback(filename, filename, FileDestinations.SDCARD)
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_force_disconnect(self):
|
||||
self.disconnect()
|
||||
|
||||
|
||||
class StateMonitor(object):
|
||||
def __init__(self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None):
|
||||
self._interval = interval
|
||||
self._update_callback = on_update
|
||||
self._on_add_temperature = on_add_temperature
|
||||
self._on_add_log = on_add_log
|
||||
self._on_add_message = on_add_message
|
||||
|
||||
self._state = None
|
||||
self._job_data = None
|
||||
self._gcode_data = None
|
||||
self._sd_upload_data = None
|
||||
self._current_z = None
|
||||
self._progress = None
|
||||
|
||||
self._offsets = {}
|
||||
|
||||
self._change_event = threading.Event()
|
||||
self._state_lock = threading.Lock()
|
||||
|
||||
self._last_update = time.time()
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def reset(self, state=None, job_data=None, progress=None, current_z=None):
|
||||
self.set_state(state)
|
||||
self.set_job_data(job_data)
|
||||
self.set_progress(progress)
|
||||
self.set_current_z(current_z)
|
||||
|
||||
def add_temperature(self, temperature):
|
||||
self._on_add_temperature(temperature)
|
||||
self._change_event.set()
|
||||
|
||||
def add_log(self, log):
|
||||
self._on_add_log(log)
|
||||
self._change_event.set()
|
||||
|
||||
def add_message(self, message):
|
||||
self._on_add_message(message)
|
||||
self._change_event.set()
|
||||
|
||||
def set_current_z(self, current_z):
|
||||
self._current_z = current_z
|
||||
self._change_event.set()
|
||||
|
||||
def set_state(self, state):
|
||||
with self._state_lock:
|
||||
self._state = state
|
||||
self._change_event.set()
|
||||
|
||||
def set_job_data(self, job_data):
|
||||
self._job_data = job_data
|
||||
self._change_event.set()
|
||||
|
||||
def set_progress(self, progress):
|
||||
self._progress = progress
|
||||
self._change_event.set()
|
||||
|
||||
def set_temp_offsets(self, offsets):
|
||||
self._offsets = offsets
|
||||
self._change_event.set()
|
||||
|
||||
def _work(self):
|
||||
while True:
|
||||
self._change_event.wait()
|
||||
|
||||
with self._state_lock:
|
||||
now = time.time()
|
||||
delta = now - self._last_update
|
||||
additional_wait_time = self._interval - delta
|
||||
if additional_wait_time > 0:
|
||||
time.sleep(additional_wait_time)
|
||||
|
||||
data = self.get_current_data()
|
||||
self._update_callback(data)
|
||||
self._last_update = time.time()
|
||||
self._change_event.clear()
|
||||
|
||||
def get_current_data(self):
|
||||
return {
|
||||
"state": self._state,
|
||||
"job": self._job_data,
|
||||
"currentZ": self._current_z,
|
||||
"progress": self._progress,
|
||||
"offsets": self._offsets
|
||||
}
|
||||
|
||||
|
||||
@@ -7,12 +7,13 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import uuid
|
||||
from sockjs.tornado import SockJSRouter
|
||||
from flask import Flask, render_template, send_from_directory, g, request, make_response
|
||||
from flask import Flask, render_template, send_from_directory, g, request, make_response, session, url_for
|
||||
from flask.ext.login import LoginManager
|
||||
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
|
||||
from flask.ext.babel import Babel
|
||||
from flask.ext.babel import Babel, gettext, ngettext
|
||||
from babel import Locale
|
||||
from watchdog.observers import Observer
|
||||
from collections import defaultdict
|
||||
|
||||
import os
|
||||
import logging
|
||||
@@ -27,28 +28,37 @@ babel = Babel(app)
|
||||
debug = False
|
||||
|
||||
printer = None
|
||||
gcodeManager = None
|
||||
printerProfileManager = None
|
||||
fileManager = None
|
||||
slicingManager = None
|
||||
analysisQueue = None
|
||||
userManager = None
|
||||
eventManager = None
|
||||
loginManager = None
|
||||
pluginManager = None
|
||||
appSessionManager = 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.printer import Printer, getConnectionOptions
|
||||
from octoprint.printer import get_connection_options
|
||||
from octoprint.printer.profile import PrinterProfileManager
|
||||
from octoprint.printer.standard import Printer
|
||||
from octoprint.settings import settings
|
||||
import octoprint.gcodefiles as gcodefiles
|
||||
import octoprint.users as users
|
||||
import octoprint.events as events
|
||||
import octoprint.plugin
|
||||
import octoprint.timelapse
|
||||
import octoprint._version
|
||||
import octoprint.util
|
||||
import octoprint.filemanager.storage
|
||||
import octoprint.filemanager.analysis
|
||||
import octoprint.slicing
|
||||
|
||||
from . import util
|
||||
util.tornado.fix_ioloop_scheduling()
|
||||
|
||||
|
||||
UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
|
||||
@@ -81,6 +91,14 @@ LANGUAGES = get_available_locale_identifiers(LOCALES)
|
||||
def before_request():
|
||||
g.locale = get_locale()
|
||||
|
||||
@app.after_request
|
||||
def after_request(response):
|
||||
# send no-cache headers with all POST responses
|
||||
if request.method == "POST":
|
||||
response.cache_control.no_cache = True
|
||||
response.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett")
|
||||
return response
|
||||
|
||||
|
||||
@babel.localeselector
|
||||
def get_locale():
|
||||
@@ -90,39 +108,321 @@ def get_locale():
|
||||
|
||||
|
||||
@app.route("/")
|
||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values)
|
||||
def index():
|
||||
settings_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin, octoprint.plugin.SettingsPlugin)
|
||||
settings_plugin_template_vars = dict()
|
||||
for name, implementation in settings_plugins.items():
|
||||
settings_plugin_template_vars[name] = implementation.get_template_vars()
|
||||
|
||||
#~~ a bunch of settings
|
||||
|
||||
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
|
||||
enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
|
||||
enable_systemmenu = settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0
|
||||
enable_accesscontrol = userManager is not None
|
||||
preferred_stylesheet = settings().get(["devel", "stylesheet"])
|
||||
|
||||
#~~ prepare assets
|
||||
|
||||
supported_stylesheets = ("css", "less")
|
||||
assets = dict(
|
||||
js=[],
|
||||
stylesheets=[]
|
||||
)
|
||||
assets["js"] = [
|
||||
url_for('static', filename='js/app/viewmodels/appearance.js'),
|
||||
url_for('static', filename='js/app/viewmodels/connection.js'),
|
||||
url_for('static', filename='js/app/viewmodels/control.js'),
|
||||
url_for('static', filename='js/app/viewmodels/firstrun.js'),
|
||||
url_for('static', filename='js/app/viewmodels/files.js'),
|
||||
url_for('static', filename='js/app/viewmodels/loginstate.js'),
|
||||
url_for('static', filename='js/app/viewmodels/navigation.js'),
|
||||
url_for('static', filename='js/app/viewmodels/printerstate.js'),
|
||||
url_for('static', filename='js/app/viewmodels/printerprofiles.js'),
|
||||
url_for('static', filename='js/app/viewmodels/settings.js'),
|
||||
url_for('static', filename='js/app/viewmodels/slicing.js'),
|
||||
url_for('static', filename='js/app/viewmodels/temperature.js'),
|
||||
url_for('static', filename='js/app/viewmodels/terminal.js'),
|
||||
url_for('static', filename='js/app/viewmodels/users.js'),
|
||||
url_for('static', filename='js/app/viewmodels/log.js')
|
||||
]
|
||||
if enable_gcodeviewer:
|
||||
assets["js"] += [
|
||||
url_for('static', filename='js/app/viewmodels/gcode.js'),
|
||||
url_for('static', filename='gcodeviewer/js/ui.js'),
|
||||
url_for('static', filename='gcodeviewer/js/gCodeReader.js'),
|
||||
url_for('static', filename='gcodeviewer/js/renderer.js')
|
||||
]
|
||||
if enable_timelapse:
|
||||
assets["js"].append(url_for('static', filename='js/app/viewmodels/timelapse.js'))
|
||||
|
||||
if preferred_stylesheet == "less":
|
||||
assets["stylesheets"].append(("less", url_for('static', filename='less/octoprint.less')))
|
||||
elif preferred_stylesheet == "css":
|
||||
assets["stylesheets"].append(("css", url_for('static', filename='css/octoprint.css')))
|
||||
|
||||
asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin)
|
||||
asset_plugin_urls = dict()
|
||||
for name, implementation in asset_plugins.items():
|
||||
asset_plugin_urls[name] = implementation.get_assets()
|
||||
all_assets = implementation.get_assets()
|
||||
|
||||
return render_template(
|
||||
"index.jinja2",
|
||||
if "js" in all_assets:
|
||||
for asset in all_assets["js"]:
|
||||
assets["js"].append(url_for('plugin_assets', name=name, filename=asset))
|
||||
|
||||
if preferred_stylesheet in all_assets:
|
||||
for asset in all_assets[preferred_stylesheet]:
|
||||
assets["stylesheets"].append((preferred_stylesheet, url_for('plugin_assets', name=name, filename=asset)))
|
||||
else:
|
||||
for stylesheet in supported_stylesheets:
|
||||
if not stylesheet in all_assets:
|
||||
continue
|
||||
|
||||
for asset in all_assets[stylesheet]:
|
||||
assets["stylesheets"].append((stylesheet, url_for('plugin_assets', name=name, filename=asset)))
|
||||
break
|
||||
|
||||
##~~ prepare templates
|
||||
|
||||
templates = dict(
|
||||
navbar=dict(order=[], entries=dict()),
|
||||
sidebar=dict(order=[], entries=dict()),
|
||||
tab=dict(order=[], entries=dict()),
|
||||
settings=dict(order=[], entries=dict()),
|
||||
generic=dict(order=[], entries=dict())
|
||||
)
|
||||
|
||||
# navbar
|
||||
|
||||
templates["navbar"]["entries"] = dict(
|
||||
settings=dict(template="navbar/settings.jinja2", _div="navbar_settings", styles=["display: none"], data_bind="visible: loginState.isAdmin")
|
||||
)
|
||||
if enable_accesscontrol:
|
||||
templates["navbar"]["entries"]["login"] = dict(template="navbar/login.jinja2", _div="navbar_login", classes=["dropdown"], custom_bindings=False)
|
||||
if enable_systemmenu:
|
||||
templates["navbar"]["entries"]["systemmenu"] = dict(template="navbar/systemmenu.jinja2", _div="navbar_systemmenu", styles=["display: none"], classes=["dropdown"], data_bind="visible: loginState.isAdmin", custom_bindings=False)
|
||||
|
||||
# sidebar
|
||||
|
||||
templates["sidebar"]["entries"]= dict(
|
||||
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.isAdmin")),
|
||||
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-sign")),
|
||||
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], header_addon="sidebar/files_header.jinja2"))
|
||||
)
|
||||
|
||||
# tabs
|
||||
|
||||
templates["tab"]["entries"] = dict(
|
||||
temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp")),
|
||||
control=(gettext("Control"), dict(template="tabs/control.jinja2", _div="control")),
|
||||
terminal=(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term")),
|
||||
)
|
||||
if enable_gcodeviewer:
|
||||
templates["tab"]["entries"]["gcodeviewer"] = (gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode"))
|
||||
if enable_timelapse:
|
||||
templates["tab"]["entries"]["timelapse"] = (gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse"))
|
||||
|
||||
# settings dialog
|
||||
|
||||
templates["settings"]["entries"] = dict(
|
||||
section_printer=(gettext("Printer"), None),
|
||||
|
||||
serial=(gettext("Serial Connection"), dict(template="dialogs/settings/serialconnection.jinja2", _div="settings_serialConnection", custom_bindings=False)),
|
||||
printerprofiles=(gettext("Printer Profiles"), dict(template="dialogs/settings/printerprofiles.jinja2", _div="settings_printerProfiles", custom_bindings=False)),
|
||||
temperatures=(gettext("Temperatures"), dict(template="dialogs/settings/temperatures.jinja2", _div="settings_temperature", custom_bindings=False)),
|
||||
terminalfilters=(gettext("Terminal Filters"), dict(template="dialogs/settings/terminalfilters.jinja2", _div="settings_terminalFilters", custom_bindings=False)),
|
||||
gcodescripts=(gettext("GCODE Scripts"), dict(template="dialogs/settings/gcodescripts.jinja2", _div="settings_gcodeScripts", custom_bindings=False)),
|
||||
|
||||
section_features=(gettext("Features"), None),
|
||||
|
||||
features=(gettext("Features"), dict(template="dialogs/settings/features.jinja2", _div="settings_features", custom_bindings=False)),
|
||||
webcam=(gettext("Webcam"), dict(template="dialogs/settings/webcam.jinja2", _div="settings_webcam", custom_bindings=False)),
|
||||
api=(gettext("API"), dict(template="dialogs/settings/api.jinja2", _div="settings_api", custom_bindings=False)),
|
||||
|
||||
section_octoprint=(gettext("OctoPrint"), None),
|
||||
|
||||
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
|
||||
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
|
||||
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
|
||||
)
|
||||
if enable_accesscontrol:
|
||||
templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False))
|
||||
|
||||
# extract data from template plugins
|
||||
|
||||
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
|
||||
|
||||
# rules for transforming template configs to template entries
|
||||
rules = dict(
|
||||
navbar=dict(div=lambda x: "navbar_plugin_" + x, template=lambda x: x + "_navbar.jinja2", to_entry=lambda data: data),
|
||||
sidebar=dict(div=lambda x: "sidebar_plugin_" + x, template=lambda x: x + "_sidebar.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
tab=dict(div=lambda x: "tab_plugin_" + x, template=lambda x: x + "_tab.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
settings=dict(div=lambda x: "settings_plugin_" + x, template=lambda x: x + "_settings.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
generic=dict(template=lambda x: x + ".jinja2", to_entry=lambda data: data)
|
||||
)
|
||||
|
||||
plugin_vars = dict()
|
||||
plugin_names = template_plugins.keys()
|
||||
for name, implementation in template_plugins.items():
|
||||
vars = implementation.get_template_vars()
|
||||
if not isinstance(vars, dict):
|
||||
vars = dict()
|
||||
|
||||
for var_name, var_value in vars.items():
|
||||
plugin_vars["plugin_" + name + "_" + var_name] = var_value
|
||||
|
||||
configs = implementation.get_template_configs()
|
||||
if not isinstance(configs, (list, tuple)):
|
||||
configs = []
|
||||
|
||||
includes = _process_template_configs(name, implementation, configs, rules)
|
||||
|
||||
for t in ("navbar", "sidebar", "tab", "settings", "generic"):
|
||||
for include in includes[t]:
|
||||
if t == "navbar" or t == "generic":
|
||||
data = include
|
||||
else:
|
||||
data = include[1]
|
||||
|
||||
suffix = data["suffix"] if "suffix" in data else ""
|
||||
key = "plugin_" + name + suffix
|
||||
if "replaces" in data:
|
||||
key = data["replaces"]
|
||||
templates[t]["entries"][key] = include
|
||||
|
||||
#~~ order internal templates and plugins
|
||||
|
||||
# make sure that
|
||||
# 1) we only have keys in our ordered list that we have entries for and
|
||||
# 2) we have all entries located somewhere within the order
|
||||
|
||||
for t in ("navbar", "sidebar", "tab", "settings", "generic"):
|
||||
configured_order = settings().get(["appearance", "components", "order", t], merged=True)
|
||||
configured_disabled = settings().get(["appearance", "components", "disabled", t])
|
||||
templates[t]["order"] = [x for x in configured_order if x in templates[t]["entries"] and not x in configured_disabled]
|
||||
|
||||
all_ordered = set(templates[t]["order"])
|
||||
all_disabled = set(configured_disabled)
|
||||
|
||||
missing_in_order = set(templates[t]["entries"].keys()).difference(all_ordered).difference(all_disabled)
|
||||
if len(missing_in_order) == 0:
|
||||
continue
|
||||
|
||||
sorted_missing = list(missing_in_order)
|
||||
if not t == "navbar" and not t == "generic":
|
||||
sorted_missing = sorted(missing_in_order, key=lambda x: templates[t]["entries"][x][0])
|
||||
if t == "navbar":
|
||||
templates[t]["order"] = sorted_missing + templates[t]["order"]
|
||||
elif t == "sidebar" or t == "tab" or t == "generic":
|
||||
templates[t]["order"] += sorted_missing
|
||||
elif t == "settings":
|
||||
templates[t]["entries"]["section_plugins"] = (gettext("Plugins"), None)
|
||||
templates[t]["order"] += ["section_plugins"] + sorted_missing
|
||||
|
||||
#~~ prepare full set of template vars for rendering
|
||||
|
||||
render_kwargs = dict(
|
||||
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"]),
|
||||
uiApiKey=UI_API_KEY,
|
||||
settingsPlugins=settings_plugin_template_vars,
|
||||
assetPlugins=asset_plugin_urls
|
||||
templates=templates,
|
||||
assets=assets,
|
||||
pluginNames=plugin_names
|
||||
)
|
||||
render_kwargs.update(plugin_vars)
|
||||
|
||||
#~~ render!
|
||||
|
||||
return render_template(
|
||||
"index.jinja2",
|
||||
**render_kwargs
|
||||
)
|
||||
|
||||
|
||||
def _process_template_configs(name, implementation, configs, rules):
|
||||
from jinja2.exceptions import TemplateNotFound
|
||||
|
||||
counters = dict(
|
||||
navbar=1,
|
||||
sidebar=1,
|
||||
tab=1,
|
||||
settings=1,
|
||||
generic=1
|
||||
)
|
||||
includes = defaultdict(list)
|
||||
|
||||
for config in configs:
|
||||
if not isinstance(config, dict):
|
||||
continue
|
||||
if not "type" in config:
|
||||
continue
|
||||
|
||||
template_type = config["type"]
|
||||
del config["type"]
|
||||
|
||||
if not template_type in rules:
|
||||
continue
|
||||
rule = rules[template_type]
|
||||
|
||||
data = _process_template_config(name, implementation, rule, config=config, counter=counters[template_type])
|
||||
if data is None:
|
||||
continue
|
||||
|
||||
includes[template_type].append(rule["to_entry"](data))
|
||||
counters[template_type] += 1
|
||||
|
||||
for template_type in rules:
|
||||
if len(includes[template_type]) == 0:
|
||||
# if no template of that type was added by the config, we'll try to use the default template name
|
||||
rule = rules[template_type]
|
||||
data = _process_template_config(name, implementation, rule)
|
||||
if data is not None:
|
||||
try:
|
||||
app.jinja_env.get_or_select_template(data["template"])
|
||||
except TemplateNotFound:
|
||||
pass
|
||||
else:
|
||||
includes[template_type].append(rule["to_entry"](data))
|
||||
|
||||
return includes
|
||||
|
||||
def _process_template_config(name, implementation, rule, config=None, counter=1):
|
||||
if "mandatory" in rule:
|
||||
for mandatory in rule["mandatory"]:
|
||||
if not mandatory in config:
|
||||
return None
|
||||
|
||||
if config is None:
|
||||
config = dict()
|
||||
data = dict(config)
|
||||
|
||||
if "div" in data:
|
||||
data["_div"] = data["div"]
|
||||
elif "div" in rule:
|
||||
data["_div"] = rule["div"](name)
|
||||
if "suffix" in data:
|
||||
data["_div"] += "_" + data["suffix"]
|
||||
elif counter > 1:
|
||||
data["_div"] += "_%d" % counter
|
||||
data["suffix"] = "_%d" % counter
|
||||
else:
|
||||
data["suffix"] = ""
|
||||
if not "template" in data:
|
||||
data["template"] = rule["template"](name)
|
||||
if not "name" in data:
|
||||
data["name"] = implementation._plugin_name
|
||||
if not "custom_bindings" in data or data["custom_bindings"]:
|
||||
data_bind = "allowBindings: true"
|
||||
if "data_bind" in data:
|
||||
data_bind = data_bind + ", " + data["data_bind"]
|
||||
data["data_bind"] = data_bind
|
||||
|
||||
return data
|
||||
|
||||
@app.route("/robots.txt")
|
||||
def robotsTxt():
|
||||
return send_from_directory(app.static_folder, "robots.txt")
|
||||
@@ -133,11 +433,11 @@ def plugin_assets(name, filename):
|
||||
asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin)
|
||||
|
||||
if not name in asset_plugins:
|
||||
return make_response(404)
|
||||
return make_response("Asset not found", 404)
|
||||
asset_plugin = asset_plugins[name]
|
||||
asset_folder = asset_plugin.get_asset_folder()
|
||||
if asset_folder is None:
|
||||
make_response(404)
|
||||
return make_response("Asset not found", 404)
|
||||
|
||||
return send_from_directory(asset_folder, filename)
|
||||
|
||||
@@ -156,8 +456,19 @@ def on_identity_loaded(sender, identity):
|
||||
|
||||
|
||||
def load_user(id):
|
||||
if id == "_api":
|
||||
return users.ApiUser()
|
||||
|
||||
if session and "usersession.id" in session:
|
||||
sessionid = session["usersession.id"]
|
||||
else:
|
||||
sessionid = None
|
||||
|
||||
if userManager is not None:
|
||||
return userManager.findUser(id)
|
||||
if sessionid:
|
||||
return userManager.findUser(username=id, session=sessionid)
|
||||
else:
|
||||
return userManager.findUser(username=id)
|
||||
return users.DummyUser()
|
||||
|
||||
|
||||
@@ -180,32 +491,81 @@ class Server():
|
||||
self._checkForRoot()
|
||||
|
||||
global printer
|
||||
global gcodeManager
|
||||
global printerProfileManager
|
||||
global fileManager
|
||||
global slicingManager
|
||||
global analysisQueue
|
||||
global userManager
|
||||
global eventManager
|
||||
global loginManager
|
||||
global pluginManager
|
||||
global appSessionManager
|
||||
global debug
|
||||
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.web import Application
|
||||
|
||||
import sys
|
||||
|
||||
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)
|
||||
settings(init=True, basedir=self._basedir, configfile=self._configfile)
|
||||
|
||||
# then initialize logging
|
||||
self._initLogging(self._debug, self._logConf)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def exception_logger(exc_type, exc_value, exc_tb):
|
||||
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
|
||||
sys.excepthook = exception_logger
|
||||
logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)
|
||||
|
||||
eventManager = events.eventManager()
|
||||
gcodeManager = gcodefiles.GcodeManager()
|
||||
printer = Printer(gcodeManager)
|
||||
# then initialize the plugin manager
|
||||
pluginManager = octoprint.plugin.plugin_manager(init=True)
|
||||
|
||||
printerProfileManager = PrinterProfileManager()
|
||||
eventManager = events.eventManager()
|
||||
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
|
||||
slicingManager = octoprint.slicing.SlicingManager(settings().getBaseFolder("slicingProfiles"), printerProfileManager)
|
||||
storage_managers = dict()
|
||||
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(settings().getBaseFolder("uploads"))
|
||||
fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
|
||||
printer = Printer(fileManager, analysisQueue, printerProfileManager)
|
||||
appSessionManager = util.flask.AppSessionManager()
|
||||
|
||||
def octoprint_plugin_inject_factory(name, implementation):
|
||||
if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
|
||||
return None
|
||||
return dict(
|
||||
plugin_manager=pluginManager,
|
||||
printer_profile_manager=printerProfileManager,
|
||||
event_bus=eventManager,
|
||||
analysis_queue=analysisQueue,
|
||||
slicing_manager=slicingManager,
|
||||
file_manager=fileManager,
|
||||
printer=printer,
|
||||
app_session_manager=appSessionManager
|
||||
)
|
||||
|
||||
def settings_plugin_inject_factory(name, implementation):
|
||||
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
|
||||
return None
|
||||
default_settings = implementation.get_settings_defaults()
|
||||
get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors()
|
||||
plugin_settings = octoprint.plugin.plugin_settings(name,
|
||||
defaults=default_settings,
|
||||
get_preprocessors=get_preprocessors,
|
||||
set_preprocessors=set_preprocessors)
|
||||
return dict(settings=plugin_settings)
|
||||
|
||||
pluginManager.initialize_implementations(
|
||||
additional_inject_factories=[
|
||||
octoprint_plugin_inject_factory,
|
||||
settings_plugin_inject_factory
|
||||
]
|
||||
)
|
||||
slicingManager.initialize()
|
||||
|
||||
# configure additional template folders for jinja2
|
||||
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
|
||||
additional_template_folders = []
|
||||
@@ -221,6 +581,7 @@ class Server():
|
||||
])
|
||||
app.jinja_loader = jinja_loader
|
||||
del jinja2
|
||||
app.jinja_env.add_extension("jinja2.ext.do")
|
||||
|
||||
# configure timelapse
|
||||
octoprint.timelapse.configureTimelapse()
|
||||
@@ -233,7 +594,7 @@ class Server():
|
||||
if settings().getBoolean(["accessControl", "enabled"]):
|
||||
userManagerName = settings().get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = octoprint.util.getClass(userManagerName)
|
||||
clazz = octoprint.util.get_class(userManagerName)
|
||||
userManager = clazz()
|
||||
except AttributeError, e:
|
||||
logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName)
|
||||
@@ -242,11 +603,21 @@ class Server():
|
||||
app.wsgi_app,
|
||||
settings().get(["server", "reverseProxy", "prefixHeader"]),
|
||||
settings().get(["server", "reverseProxy", "schemeHeader"]),
|
||||
settings().get(["server", "reverseProxy", "hostHeader"]),
|
||||
settings().get(["server", "reverseProxy", "prefixFallback"]),
|
||||
settings().get(["server", "reverseProxy", "prefixScheme"])
|
||||
settings().get(["server", "reverseProxy", "schemeFallback"]),
|
||||
settings().get(["server", "reverseProxy", "hostFallback"])
|
||||
)
|
||||
|
||||
app.secret_key = "k3PuVYgtxNm8DXKKTw2nWmFQQun9qceV"
|
||||
secret_key = settings().get(["server", "secretKey"])
|
||||
if not secret_key:
|
||||
import string
|
||||
from random import choice
|
||||
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
|
||||
secret_key = "".join(choice(chars) for _ in xrange(32))
|
||||
settings().set(["server", "secretKey"], secret_key)
|
||||
settings().save()
|
||||
app.secret_key = secret_key
|
||||
loginManager = LoginManager()
|
||||
loginManager.session_protection = "strong"
|
||||
loginManager.user_callback = load_user
|
||||
@@ -263,21 +634,39 @@ class Server():
|
||||
app.debug = self._debug
|
||||
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.apps import apps
|
||||
|
||||
# register API blueprint
|
||||
app.register_blueprint(api, url_prefix="/api")
|
||||
app.register_blueprint(apps, url_prefix="/apps")
|
||||
|
||||
# also register any blueprints defined in BlueprintPlugins
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.BlueprintPlugin,
|
||||
"get_blueprint",
|
||||
callback=lambda name, _, blueprint: app.register_blueprint(blueprint, url_prefix="/plugin/{name}".format(name=name)))
|
||||
blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.BlueprintPlugin)
|
||||
for name, plugin in blueprint_plugins.items():
|
||||
blueprint = plugin.get_blueprint()
|
||||
if blueprint is None:
|
||||
continue
|
||||
|
||||
if plugin.is_blueprint_protected():
|
||||
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
|
||||
blueprint.before_request(apiKeyRequestHandler)
|
||||
blueprint.after_request(corsResponseHandler)
|
||||
|
||||
url_prefix = "/plugin/{name}".format(name=name)
|
||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||
logger.debug("Registered API of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix))
|
||||
|
||||
## Tornado initialization starts here
|
||||
|
||||
ioloop = IOLoop()
|
||||
ioloop.install()
|
||||
|
||||
self._router = SockJSRouter(self._createSocketConnection, "/sockjs")
|
||||
|
||||
upload_suffixes = dict(name=settings().get(["server", "uploads", "nameSuffix"]), path=settings().get(["server", "uploads", "pathSuffix"]))
|
||||
self._tornado_app = Application(self._router.urls + [
|
||||
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("timelapse"), as_attachment=True)),
|
||||
(r"/downloads/files/local/([^/]*\.(gco|gcode))", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)),
|
||||
(r"/downloads/files/local/([^/]*\.(gco|gcode|g|stl))", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("logs"), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))),
|
||||
(r"/downloads/camera/current", util.tornado.UrlForwardHandler, dict(url=settings().get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
|
||||
(r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp", suffixes=upload_suffixes))
|
||||
@@ -291,18 +680,16 @@ class Server():
|
||||
eventManager.fire(events.Events.STARTUP)
|
||||
if settings().getBoolean(["serial", "autoconnect"]):
|
||||
(port, baudrate) = settings().get(["serial", "port"]), settings().getInt(["serial", "baudrate"])
|
||||
connectionOptions = getConnectionOptions()
|
||||
printer_profile = printerProfileManager.get_default()
|
||||
connectionOptions = get_connection_options()
|
||||
if port in connectionOptions["ports"]:
|
||||
printer.connect(port, baudrate)
|
||||
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
|
||||
|
||||
# start up watchdogs
|
||||
observer = Observer()
|
||||
observer.schedule(util.watchdog.GcodeWatchdogHandler(gcodeManager, printer), settings().getBaseFolder("watched"))
|
||||
observer.schedule(util.watchdog.UploadCleanupWatchdogHandler(gcodeManager), settings().getBaseFolder("uploads"))
|
||||
observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), settings().getBaseFolder("watched"))
|
||||
observer.start()
|
||||
|
||||
ioloop = IOLoop.instance()
|
||||
|
||||
# run our startup plugins
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
|
||||
"on_startup",
|
||||
@@ -342,16 +729,13 @@ class Server():
|
||||
logger.exception("Stacktrace follows:")
|
||||
|
||||
def _createSocketConnection(self, session):
|
||||
global printer, gcodeManager, userManager, eventManager
|
||||
return util.sockjs.PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session)
|
||||
global printer, fileManager, analysisQueue, userManager, eventManager
|
||||
return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, 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, logConf=None):
|
||||
defaultConfig = {
|
||||
"version": 1,
|
||||
@@ -388,6 +772,9 @@ class Server():
|
||||
"level": "CRITICAL",
|
||||
"handlers": ["serialFile"],
|
||||
"propagate": False
|
||||
},
|
||||
"tornado.application": {
|
||||
"level": "ERROR"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
@@ -400,7 +787,7 @@ class Server():
|
||||
defaultConfig["root"]["level"] = "DEBUG"
|
||||
|
||||
if logConf is None:
|
||||
logConf = os.path.join(settings().settings_dir, "logging.yaml")
|
||||
logConf = os.path.join(settings().getBaseFolder("base"), "logging.yaml")
|
||||
|
||||
configFromFile = {}
|
||||
if os.path.exists(logConf) and os.path.isfile(logConf):
|
||||
@@ -410,6 +797,10 @@ class Server():
|
||||
|
||||
config = octoprint.util.dict_merge(defaultConfig, configFromFile)
|
||||
logging.config.dictConfig(config)
|
||||
logging.captureWarnings(True)
|
||||
|
||||
import warnings
|
||||
warnings.simplefilter("always")
|
||||
|
||||
if settings().getBoolean(["serial", "log"]):
|
||||
# enable debug logging to serial.log
|
||||
|
||||
@@ -17,10 +17,10 @@ import octoprint.util as util
|
||||
import octoprint.users
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import admin_permission, NO_CONTENT, UI_API_KEY
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import get_api_key, get_user_for_apikey
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util.flask import restricted_access, get_remote_address, get_json_command_from_request
|
||||
|
||||
|
||||
#~~ init api blueprint, including sub modules
|
||||
@@ -35,78 +35,14 @@ from . import settings as api_settings
|
||||
from . import timelapse as api_timelapse
|
||||
from . import users as api_users
|
||||
from . import log as api_logs
|
||||
from . import slicing as api_slicing
|
||||
from . import printer_profiles as api_printer_profiles
|
||||
|
||||
|
||||
VERSION = "0.1"
|
||||
|
||||
|
||||
def optionsAllowOrigin(request):
|
||||
""" Always reply 200 on OPTIONS request """
|
||||
|
||||
resp = current_app.make_default_options_response()
|
||||
|
||||
# Allow the origin which made the XHR
|
||||
resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
|
||||
# Allow the actual method
|
||||
resp.headers['Access-Control-Allow-Methods'] = request.headers['Access-Control-Request-Method']
|
||||
# Allow for 10 seconds
|
||||
resp.headers['Access-Control-Max-Age'] = "10"
|
||||
|
||||
# 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key)
|
||||
customRequestHeaders = request.headers.get('Access-Control-Request-Headers', None)
|
||||
if customRequestHeaders is not None:
|
||||
# If present => allow them all
|
||||
resp.headers['Access-Control-Allow-Headers'] = customRequestHeaders
|
||||
|
||||
return resp
|
||||
|
||||
@api.before_request
|
||||
def beforeApiRequests():
|
||||
"""
|
||||
All requests in this blueprint need to be made supplying an API key. This may be the UI_API_KEY, in which case
|
||||
the underlying request processing will directly take place, or it may be the global or a user specific case. In any
|
||||
case it has to be present and must be valid, so anything other than the above three types will result in denying
|
||||
the request.
|
||||
"""
|
||||
|
||||
if request.method == 'OPTIONS' and s().getBoolean(["api", "allowCrossOrigin"]):
|
||||
return optionsAllowOrigin(request)
|
||||
|
||||
apikey = get_api_key(request)
|
||||
if apikey is None:
|
||||
# no api key => 401
|
||||
return make_response("No API key provided", 401)
|
||||
|
||||
if apikey == UI_API_KEY:
|
||||
# ui api key => continue regular request processing
|
||||
return
|
||||
|
||||
if not s().get(["api", "enabled"]):
|
||||
# api disabled => 401
|
||||
return make_response("API disabled", 401)
|
||||
|
||||
if apikey == s().get(["api", "key"]):
|
||||
# global api key => continue regular request processing
|
||||
return
|
||||
|
||||
user = get_user_for_apikey(apikey)
|
||||
if user is not None:
|
||||
# user specific api key => continue regular request processing
|
||||
return
|
||||
|
||||
# invalid api key => 401
|
||||
return make_response("Invalid API key", 401)
|
||||
|
||||
@api.after_request
|
||||
def afterApiRequests(resp):
|
||||
|
||||
# Allow crossdomain
|
||||
allowCrossOrigin = s().getBoolean(["api", "allowCrossOrigin"])
|
||||
if request.method != 'OPTIONS' and 'Origin' in request.headers and allowCrossOrigin:
|
||||
resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
|
||||
|
||||
return resp
|
||||
|
||||
api.before_request(apiKeyRequestHandler)
|
||||
api.after_request(corsResponseHandler)
|
||||
|
||||
#~~ data from plugins
|
||||
|
||||
@@ -137,7 +73,7 @@ def pluginCommand(name):
|
||||
if valid_commands is None:
|
||||
return make_response("Method not allowed", 405)
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
@@ -181,14 +117,6 @@ def apiPrinterState():
|
||||
return make_response(("/api/state has been deprecated, use /api/printer instead", 405, []))
|
||||
|
||||
|
||||
@api.route("/version", methods=["GET"])
|
||||
@restricted_access
|
||||
def apiVersion():
|
||||
return jsonify({
|
||||
"server": octoprint.server.VERSION,
|
||||
"api": octoprint.server.api.VERSION
|
||||
})
|
||||
|
||||
@api.route("/version", methods=["GET"])
|
||||
@restricted_access
|
||||
def apiVersion():
|
||||
@@ -243,15 +171,26 @@ def login():
|
||||
else:
|
||||
remember = False
|
||||
|
||||
if "usersession.id" in session:
|
||||
_logout(current_user)
|
||||
|
||||
user = octoprint.server.userManager.findUser(username)
|
||||
if user is not None:
|
||||
if user.check_password(octoprint.users.UserManager.createPasswordHash(password)):
|
||||
if octoprint.server.userManager.checkPassword(username, password):
|
||||
if octoprint.server.userManager is not None:
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
session["usersession.id"] = user.get_session()
|
||||
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 octoprint.server.userManager is not None:
|
||||
user = octoprint.server.userManager.login_user(current_user)
|
||||
else:
|
||||
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())
|
||||
@@ -265,7 +204,7 @@ def login():
|
||||
localNetworks.add(ip)
|
||||
|
||||
try:
|
||||
remoteAddr = util.getRemoteAddress(request)
|
||||
remoteAddr = get_remote_address(request)
|
||||
if netaddr.IPAddress(remoteAddr) in localNetworks:
|
||||
user = octoprint.server.userManager.findUser(autologinAs)
|
||||
if user is not None:
|
||||
@@ -287,7 +226,12 @@ def logout():
|
||||
del session[key]
|
||||
identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
|
||||
|
||||
_logout(current_user)
|
||||
logout_user()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def _logout(user):
|
||||
if "usersession.id" in session:
|
||||
del session["usersession.id"]
|
||||
octoprint.server.userManager.logout_user(user)
|
||||
@@ -8,59 +8,81 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
from flask import request, jsonify, make_response
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.printer import getConnectionOptions
|
||||
from octoprint.server import printer, NO_CONTENT
|
||||
from octoprint.printer import get_connection_options
|
||||
from octoprint.server import printer, printerProfileManager, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
import octoprint.util as util
|
||||
|
||||
|
||||
@api.route("/connection", methods=["GET"])
|
||||
def connectionState():
|
||||
state, port, baudrate = printer.getCurrentConnection()
|
||||
state, port, baudrate, printer_profile = printer.get_current_connection()
|
||||
current = {
|
||||
"state": state,
|
||||
"port": port,
|
||||
"baudrate": baudrate
|
||||
"baudrate": baudrate,
|
||||
"printerProfile": printer_profile["id"] if printer_profile is not None and "id" in printer_profile else "_default"
|
||||
}
|
||||
return jsonify({"current": current, "options": getConnectionOptions()})
|
||||
|
||||
return jsonify({"current": current, "options": _get_options()})
|
||||
|
||||
|
||||
@api.route("/connection", methods=["POST"])
|
||||
@restricted_access
|
||||
def connectionCommand():
|
||||
valid_commands = {
|
||||
"connect": ["autoconnect"],
|
||||
"connect": [],
|
||||
"disconnect": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "connect":
|
||||
options = getConnectionOptions()
|
||||
connection_options = get_connection_options()
|
||||
|
||||
port = None
|
||||
baudrate = None
|
||||
printerProfile = None
|
||||
if "port" in data.keys():
|
||||
port = data["port"]
|
||||
if port not in options["ports"]:
|
||||
if port not in connection_options["ports"]:
|
||||
return make_response("Invalid port: %s" % port, 400)
|
||||
if "baudrate" in data.keys():
|
||||
baudrate = data["baudrate"]
|
||||
if baudrate not in options["baudrates"]:
|
||||
if baudrate not in connection_options["baudrates"]:
|
||||
return make_response("Invalid baudrate: %d" % baudrate, 400)
|
||||
if "printerProfile" in data.keys():
|
||||
printerProfile = data["printerProfile"]
|
||||
if not printerProfileManager.exists(printerProfile):
|
||||
return make_response("Invalid printer profile: %s" % printerProfile, 400)
|
||||
if "save" in data.keys() and data["save"]:
|
||||
settings().set(["serial", "port"], port)
|
||||
settings().setInt(["serial", "baudrate"], baudrate)
|
||||
printerProfileManager.set_default(printerProfile)
|
||||
if "autoconnect" in data.keys():
|
||||
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
|
||||
settings().save()
|
||||
printer.connect(port=port, baudrate=baudrate)
|
||||
printer.connect(port=port, baudrate=baudrate, profile=printerProfile)
|
||||
elif command == "disconnect":
|
||||
printer.disconnect()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def _get_options():
|
||||
connection_options = get_connection_options()
|
||||
profile_options = printerProfileManager.get_all()
|
||||
default_profile = printerProfileManager.get_default()
|
||||
|
||||
options = dict(
|
||||
ports=connection_options["ports"],
|
||||
baudrates=connection_options["baudrates"],
|
||||
printerProfiles=[dict(id=printer_profile["id"], name=printer_profile["name"] if "name" in printer_profile else printer_profile["id"]) for printer_profile in profile_options.values() if "id" in printer_profile],
|
||||
portPreference=connection_options["portPreference"],
|
||||
baudratePreference=connection_options["baudratePreference"],
|
||||
printerProfilePreference=default_profile["id"] if "id" in default_profile else None
|
||||
)
|
||||
|
||||
return options
|
||||
@@ -7,14 +7,14 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
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, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
from octoprint.server.api import api
|
||||
from octoprint.events import Events
|
||||
import octoprint.filemanager
|
||||
|
||||
|
||||
#~~ GCODE file handling
|
||||
@@ -22,9 +22,12 @@ from octoprint.events import Events
|
||||
|
||||
@api.route("/files", methods=["GET"])
|
||||
def readGcodeFiles():
|
||||
files = _getFileList(FileDestinations.LOCAL)
|
||||
filter = None
|
||||
if "filter" in request.values:
|
||||
filter = request.values["filter"]
|
||||
files = _getFileList(FileDestinations.LOCAL, filter=filter)
|
||||
files.extend(_getFileList(FileDestinations.SDCARD))
|
||||
return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads")))
|
||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
||||
|
||||
|
||||
@api.route("/files/<string:origin>", methods=["GET"])
|
||||
@@ -35,7 +38,7 @@ def readGcodeFilesForOrigin(origin):
|
||||
files = _getFileList(origin)
|
||||
|
||||
if origin == FileDestinations.LOCAL:
|
||||
return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads")))
|
||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
||||
else:
|
||||
return jsonify(files=files)
|
||||
|
||||
@@ -48,14 +51,15 @@ def _getFileDetails(origin, filename):
|
||||
return None
|
||||
|
||||
|
||||
def _getFileList(origin):
|
||||
def _getFileList(origin, filter=None):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
sdFileList = printer.getSdFiles()
|
||||
sdFileList = printer.get_sd_files()
|
||||
|
||||
files = []
|
||||
if sdFileList is not None:
|
||||
for sdFile, sdSize in sdFileList:
|
||||
file = {
|
||||
"type": "machinecode",
|
||||
"name": sdFile,
|
||||
"origin": FileDestinations.SDCARD,
|
||||
"refs": {
|
||||
@@ -66,8 +70,42 @@ def _getFileList(origin):
|
||||
file.update({"size": sdSize})
|
||||
files.append(file)
|
||||
else:
|
||||
files = gcodeManager.getAllFileData()
|
||||
filter_func = None
|
||||
if filter:
|
||||
filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(entry, type=filter)
|
||||
files = fileManager.list_files(origin, filter=filter_func, recursive=False)[origin].values()
|
||||
for file in files:
|
||||
file["origin"] = FileDestinations.LOCAL
|
||||
|
||||
if "analysis" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
|
||||
file["gcodeAnalysis"] = file["analysis"]
|
||||
del file["analysis"]
|
||||
|
||||
if "history" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
|
||||
# convert print log
|
||||
history = file["history"]
|
||||
del file["history"]
|
||||
success = 0
|
||||
failure = 0
|
||||
last = None
|
||||
for entry in history:
|
||||
success += 1 if "success" in entry and entry["success"] else 0
|
||||
failure += 1 if "success" in entry and not entry["success"] else 0
|
||||
if not last or ("timestamp" in entry and "timestamp" in last and entry["timestamp"] > last["timestamp"]):
|
||||
last = entry
|
||||
if last:
|
||||
prints = dict(
|
||||
success=success,
|
||||
failure=failure,
|
||||
last=dict(
|
||||
success=last["success"],
|
||||
date=last["timestamp"]
|
||||
)
|
||||
)
|
||||
if "printTime" in last:
|
||||
prints["last"]["printTime"] = last["printTime"]
|
||||
file["prints"] = prints
|
||||
|
||||
file.update({
|
||||
"refs": {
|
||||
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file["name"], _external=True),
|
||||
@@ -79,11 +117,9 @@ def _getFileList(origin):
|
||||
|
||||
def _verifyFileExists(origin, filename):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
availableFiles = map(lambda x: x[0], printer.getSdFiles())
|
||||
return filename in map(lambda x: x[0], printer.get_sd_files())
|
||||
else:
|
||||
availableFiles = gcodeManager.getAllFilenames()
|
||||
|
||||
return filename in availableFiles
|
||||
return fileManager.file_exists(origin, filename)
|
||||
|
||||
|
||||
@api.route("/files/<string:target>", methods=["POST"])
|
||||
@@ -114,15 +150,15 @@ def uploadGcodeFile(target):
|
||||
|
||||
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())):
|
||||
if not (printer.is_operational() and not (printer.is_printing() or printer.is_paused())):
|
||||
return make_response("Can not upload to SD card, printer is either not operational or already busy", 409)
|
||||
if not printer.isSdReady():
|
||||
if not printer.is_sd_ready():
|
||||
return make_response("Can not upload to SD card, not yet initialized", 409)
|
||||
|
||||
# determine current job
|
||||
currentFilename = None
|
||||
currentOrigin = None
|
||||
currentJob = printer.getCurrentJob()
|
||||
currentJob = printer.get_current_job()
|
||||
if currentJob is not None and "file" in currentJob.keys():
|
||||
currentJobFile = currentJob["file"]
|
||||
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
|
||||
@@ -130,12 +166,15 @@ def uploadGcodeFile(target):
|
||||
currentOrigin = currentJobFile["origin"]
|
||||
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
futureFilename = gcodeManager.getFutureFilename(upload)
|
||||
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)):
|
||||
try:
|
||||
futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, upload.filename)
|
||||
except:
|
||||
futureFilename = None
|
||||
if futureFilename is None:
|
||||
return make_response("Can not upload file %s, wrong format?" % upload.filename, 415)
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
if futureFilename == currentFilename and target == currentOrigin and printer.isPrinting() or printer.isPaused():
|
||||
if futureFilename == currentFilename and target == currentOrigin and printer.is_printing() or printer.is_paused():
|
||||
return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409)
|
||||
|
||||
def fileProcessingFinished(filename, absFilename, destination):
|
||||
@@ -145,8 +184,9 @@ def uploadGcodeFile(target):
|
||||
|
||||
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)
|
||||
|
||||
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"):
|
||||
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint)
|
||||
else:
|
||||
selectAndOrPrint(filename, absFilename, destination)
|
||||
return filename
|
||||
@@ -160,12 +200,18 @@ def uploadGcodeFile(target):
|
||||
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
|
||||
exact file is already selected, such reloading it.
|
||||
"""
|
||||
if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination):
|
||||
printer.selectFile(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
|
||||
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)):
|
||||
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
|
||||
|
||||
filename, done = gcodeManager.addFile(upload, target, fileProcessingFinished)
|
||||
if filename is None:
|
||||
added_file = fileManager.add_file(FileDestinations.LOCAL, upload.filename, upload, allow_overwrite=True)
|
||||
if added_file is None:
|
||||
return make_response("Could not upload the file %s" % upload.filename, 500)
|
||||
if octoprint.filemanager.valid_file_type(added_file, "stl"):
|
||||
filename = added_file
|
||||
done = True
|
||||
else:
|
||||
filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target)
|
||||
done = True
|
||||
|
||||
sdFilename = None
|
||||
if isinstance(filename, tuple):
|
||||
@@ -226,18 +272,19 @@ def gcodeFileCommand(filename, target):
|
||||
|
||||
# valid file commands, dict mapping command name to mandatory parameters
|
||||
valid_commands = {
|
||||
"select": []
|
||||
"select": [],
|
||||
"slice": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(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():
|
||||
if "print" in data.keys() and data["print"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||
printAfterLoading = True
|
||||
|
||||
@@ -246,8 +293,112 @@ def gcodeFileCommand(filename, target):
|
||||
filenameToSelect = filename
|
||||
sd = True
|
||||
else:
|
||||
filenameToSelect = gcodeManager.getAbsolutePath(filename)
|
||||
printer.selectFile(filenameToSelect, sd, printAfterLoading)
|
||||
filenameToSelect = fileManager.path_on_disk(target, filename)
|
||||
printer.select_file(filenameToSelect, sd, printAfterLoading)
|
||||
|
||||
elif command == "slice":
|
||||
if "slicer" in data.keys():
|
||||
slicer = data["slicer"]
|
||||
del data["slicer"]
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Slicer {slicer} is not available".format(**locals()), 400)
|
||||
slicer_instance = slicingManager.get_slicer(slicer)
|
||||
elif "cura" in slicingManager.registered_slicers:
|
||||
slicer = "cura"
|
||||
slicer_instance = slicingManager.get_slicer("cura")
|
||||
else:
|
||||
return make_response("Cannot slice {filename}, no slicer available".format(**locals()), 415)
|
||||
|
||||
if not octoprint.filemanager.valid_file_type(filename, type="stl"):
|
||||
return make_response("Cannot slice {filename}, not an STL file".format(**locals()), 415)
|
||||
|
||||
if slicer_instance.get_slicer_properties()["same_device"] and (printer.is_printing() or printer.is_paused()):
|
||||
# slicer runs on same device as OctoPrint, slicing while printing is hence disabled
|
||||
return make_response("Cannot slice on {slicer} while printing due to performance reasons".format(**locals()), 409)
|
||||
|
||||
if "gcode" in data.keys() and data["gcode"]:
|
||||
gcode_name = data["gcode"]
|
||||
del data["gcode"]
|
||||
else:
|
||||
import os
|
||||
name, _ = os.path.splitext(filename)
|
||||
gcode_name = name + ".gco"
|
||||
|
||||
# prohibit overwriting the file that is currently being printed
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename == gcode_name and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
|
||||
make_response("Trying to slice into file that is currently being printed: %s" % gcode_name, 409)
|
||||
|
||||
if "profile" in data.keys() and data["profile"]:
|
||||
profile = data["profile"]
|
||||
del data["profile"]
|
||||
else:
|
||||
profile = None
|
||||
|
||||
if "printerProfile" in data.keys() and data["printerProfile"]:
|
||||
printerProfile = data["printerProfile"]
|
||||
del data["printerProfile"]
|
||||
else:
|
||||
printerProfile = None
|
||||
|
||||
if "position" in data.keys() and data["position"] and isinstance(data["position"], dict) and "x" in data["position"] and "y" in data["position"]:
|
||||
position = data["position"]
|
||||
del data["position"]
|
||||
else:
|
||||
position = None
|
||||
|
||||
select_after_slicing = False
|
||||
if "select" in data.keys() and data["select"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly select for printing", 409)
|
||||
select_after_slicing = True
|
||||
|
||||
print_after_slicing = False
|
||||
if "print" in data.keys() and data["print"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||
select_after_slicing = print_after_slicing = True
|
||||
|
||||
override_keys = [k for k in data if k.startswith("profile.") and data[k] is not None]
|
||||
overrides = dict()
|
||||
for key in override_keys:
|
||||
overrides[key[len("profile."):]] = data[key]
|
||||
|
||||
def slicing_done(target, gcode_name, select_after_slicing, print_after_slicing):
|
||||
if select_after_slicing or print_after_slicing:
|
||||
sd = False
|
||||
if target == FileDestinations.SDCARD:
|
||||
filenameToSelect = gcode_name
|
||||
sd = True
|
||||
else:
|
||||
filenameToSelect = fileManager.path_on_disk(target, gcode_name)
|
||||
printer.select_file(filenameToSelect, sd, print_after_slicing)
|
||||
|
||||
ok, result = fileManager.slice(slicer, target, filename, target, gcode_name,
|
||||
profile=profile,
|
||||
printer_profile_id=printerProfile,
|
||||
position=position,
|
||||
overrides=overrides,
|
||||
callback=slicing_done,
|
||||
callback_args=(target, gcode_name, select_after_slicing, print_after_slicing))
|
||||
|
||||
if ok:
|
||||
files = {}
|
||||
location = url_for(".readGcodeFile", target=target, filename=gcode_name, _external=True)
|
||||
result = {
|
||||
"name": gcode_name,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"refs": {
|
||||
"resource": location,
|
||||
"download": url_for("index", _external=True) + "downloads/files/" + target + "/" + gcode_name
|
||||
}
|
||||
}
|
||||
|
||||
r = make_response(jsonify(result), 202)
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
else:
|
||||
return make_response("Could not slice: {result}".format(result=result), 500)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -261,28 +412,30 @@ def deleteGcodeFile(filename, target):
|
||||
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()):
|
||||
# prohibit deleting files that are currently in use
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename == filename and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
|
||||
make_response("Trying to delete file that is currently being printed: %s" % filename, 409)
|
||||
|
||||
if (target, filename) in fileManager.get_busy_files():
|
||||
make_response("Trying to delete a file that is currently in use: %s" % filename, 409)
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
if currentFilename is not None and filename == currentFilename:
|
||||
printer.unselectFile()
|
||||
printer.unselect_file()
|
||||
|
||||
# delete it
|
||||
if sd:
|
||||
printer.deleteSdFile(filename)
|
||||
if target == FileDestinations.SDCARD:
|
||||
printer.delete_sd_file(filename)
|
||||
else:
|
||||
gcodeManager.removeFile(filename)
|
||||
fileManager.remove_file(target, filename)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def _getCurrentFile():
|
||||
currentJob = printer.get_current_job()
|
||||
if currentJob is not None and "file" in currentJob.keys() and "name" in currentJob["file"] and "origin" in currentJob["file"]:
|
||||
return currentJob["file"]["origin"], currentJob["file"]["name"]
|
||||
else:
|
||||
return None, None
|
||||
|
||||
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
from flask import request, make_response, jsonify
|
||||
|
||||
from octoprint.server import printer, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
from octoprint.server.api import api
|
||||
import octoprint.util as util
|
||||
|
||||
@@ -16,7 +16,7 @@ import octoprint.util as util
|
||||
@api.route("/job", methods=["POST"])
|
||||
@restricted_access
|
||||
def controlJob():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
@@ -26,34 +26,34 @@ def controlJob():
|
||||
"cancel": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
activePrintjob = printer.isPrinting() or printer.isPaused()
|
||||
activePrintjob = printer.is_printing() or printer.is_paused()
|
||||
|
||||
if command == "start":
|
||||
if activePrintjob:
|
||||
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
|
||||
printer.startPrint()
|
||||
printer.start_print()
|
||||
elif command == "restart":
|
||||
if not printer.isPaused():
|
||||
if not printer.is_paused():
|
||||
return make_response("Printer does not have an active print job or is not paused", 409)
|
||||
printer.startPrint()
|
||||
printer.start_print()
|
||||
elif command == "pause":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
|
||||
printer.togglePausePrint()
|
||||
printer.toggle_pause_print()
|
||||
elif command == "cancel":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
|
||||
printer.cancelPrint()
|
||||
printer.cancel_print()
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/job", methods=["GET"])
|
||||
def jobState():
|
||||
currentData = printer.getCurrentData()
|
||||
currentData = printer.get_current_data()
|
||||
return jsonify({
|
||||
"job": currentData["job"],
|
||||
"progress": currentData["progress"],
|
||||
|
||||
@@ -15,7 +15,7 @@ from octoprint.settings import settings
|
||||
from octoprint.server import NO_CONTENT, admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
from octoprint.server.api import api
|
||||
from octoprint.util import getFreeBytes
|
||||
from octoprint.util import get_free_bytes
|
||||
|
||||
|
||||
@api.route("/logs", methods=["GET"])
|
||||
@@ -23,7 +23,7 @@ from octoprint.util import getFreeBytes
|
||||
@admin_permission.require(403)
|
||||
def getLogFiles():
|
||||
files = _getLogFiles()
|
||||
return jsonify(files=files, free=getFreeBytes(settings().getBaseFolder("logs")))
|
||||
return jsonify(files=files, free=get_free_bytes(settings().getBaseFolder("logs")))
|
||||
|
||||
|
||||
@api.route("/logs/<path:filename>", methods=["GET"])
|
||||
|
||||
@@ -6,20 +6,23 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, make_response, Response
|
||||
from flask.exceptions import JSONBadRequest
|
||||
import re
|
||||
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.printer import UnknownScript
|
||||
|
||||
#~~ Printer
|
||||
|
||||
|
||||
@api.route("/printer", methods=["GET"])
|
||||
def printerState():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
# process excludes
|
||||
@@ -37,11 +40,11 @@ def printerState():
|
||||
|
||||
# add sd information
|
||||
if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]):
|
||||
result.update({"sd": {"ready": printer.isSdReady()}})
|
||||
result.update({"sd": {"ready": printer.is_sd_ready()}})
|
||||
|
||||
# add state information
|
||||
if not "state" in excludes:
|
||||
state = printer.getCurrentData()["state"]
|
||||
state = printer.get_current_data()["state"]
|
||||
result.update({"state": state})
|
||||
|
||||
return jsonify(result)
|
||||
@@ -53,16 +56,17 @@ def printerState():
|
||||
@api.route("/printer/tool", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerToolCommand():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
"select": ["tool"],
|
||||
"target": ["targets"],
|
||||
"offset": ["offsets"],
|
||||
"extrude": ["amount"]
|
||||
"extrude": ["amount"],
|
||||
"flowrate": ["factor"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
@@ -76,7 +80,7 @@ def printerToolCommand():
|
||||
if not tool.startswith("tool"):
|
||||
return make_response("Invalid tool for selection: %s" % tool, 400)
|
||||
|
||||
printer.changeTool(tool)
|
||||
printer.change_tool(tool)
|
||||
|
||||
##~~ temperature
|
||||
elif command == "target":
|
||||
@@ -93,7 +97,7 @@ def printerToolCommand():
|
||||
|
||||
# perform the actual temperature commands
|
||||
for tool in validated_values.keys():
|
||||
printer.setTemperature(tool, validated_values[tool])
|
||||
printer.set_temperature(tool, validated_values[tool])
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
@@ -111,11 +115,11 @@ def printerToolCommand():
|
||||
validated_values[tool] = value
|
||||
|
||||
# set the offsets
|
||||
printer.setTemperatureOffset(validated_values)
|
||||
printer.set_temperature_offset(validated_values)
|
||||
|
||||
##~~ extrusion
|
||||
elif command == "extrude":
|
||||
if printer.isPrinting():
|
||||
if printer.is_printing():
|
||||
# do not extrude when a print job is running
|
||||
return make_response("Printer is currently printing", 409)
|
||||
|
||||
@@ -124,12 +128,21 @@ def printerToolCommand():
|
||||
return make_response("Not a number for extrusion amount: %r" % amount, 400)
|
||||
printer.extrude(amount)
|
||||
|
||||
elif command == "flowrate":
|
||||
factor = data["factor"]
|
||||
if not isinstance(factor, (int, long, float)):
|
||||
return make_response("Not a number for flow rate: %r" % factor, 400)
|
||||
try:
|
||||
printer.flow_rate(factor)
|
||||
except ValueError as e:
|
||||
return make_response("Invalid value for flow rate: %s" % e.message, 400)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/tool", methods=["GET"])
|
||||
def printerToolState():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
def deleteBed(x):
|
||||
@@ -148,14 +161,14 @@ def printerToolState():
|
||||
@api.route("/printer/bed", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerBedCommand():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
"target": ["target"],
|
||||
"offset": ["offset"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
@@ -168,7 +181,7 @@ def printerBedCommand():
|
||||
return make_response("Not a number: %r" % target, 400)
|
||||
|
||||
# perform the actual temperature command
|
||||
printer.setTemperature("bed", target)
|
||||
printer.set_temperature("bed", target)
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
@@ -181,14 +194,14 @@ def printerBedCommand():
|
||||
return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
|
||||
|
||||
# set the offsets
|
||||
printer.setTemperatureOffset({"bed": offset})
|
||||
printer.set_temperature_offset({"bed": offset})
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/bed", methods=["GET"])
|
||||
def printerBedState():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
def deleteTools(x):
|
||||
@@ -212,18 +225,19 @@ def printerBedState():
|
||||
@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"]
|
||||
"home": ["axes"],
|
||||
"feedrate": ["factor"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if not printer.is_operational() or (printer.is_printing() and command != "feedrate"):
|
||||
# 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_axes = ["x", "y", "z"]
|
||||
##~~ jog command
|
||||
if command == "jog":
|
||||
@@ -252,6 +266,15 @@ def printerPrintheadCommand():
|
||||
# execute the home command
|
||||
printer.home(validated_values)
|
||||
|
||||
elif command == "feedrate":
|
||||
factor = data["factor"]
|
||||
if not isinstance(factor, (int, long, float)):
|
||||
return make_response("Not a number for feed rate: %r" % factor, 400)
|
||||
try:
|
||||
printer.feed_rate(factor)
|
||||
except ValueError as e:
|
||||
return make_response("Invalid value for feed rate: %s" % e.message, 400)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@@ -264,7 +287,7 @@ 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():
|
||||
if not printer.is_operational() or printer.is_printing() or printer.is_paused():
|
||||
return make_response("Printer is not operational or currently busy", 409)
|
||||
|
||||
valid_commands = {
|
||||
@@ -272,16 +295,16 @@ def printerSdCommand():
|
||||
"refresh": [],
|
||||
"release": []
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "init":
|
||||
printer.initSdCard()
|
||||
printer.init_sd_card()
|
||||
elif command == "refresh":
|
||||
printer.refreshSdFiles()
|
||||
printer.refresh_sd_files()
|
||||
elif command == "release":
|
||||
printer.releaseSdCard()
|
||||
printer.release_sd_card()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -291,7 +314,7 @@ def printerSdState():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD support is disabled", 404)
|
||||
|
||||
return jsonify(ready=printer.isSdReady())
|
||||
return jsonify(ready=printer.is_sd_ready())
|
||||
|
||||
|
||||
##~~ Commands
|
||||
@@ -300,37 +323,58 @@ def printerSdState():
|
||||
@api.route("/printer/command", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerCommand():
|
||||
# TODO: document me
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
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
|
||||
try:
|
||||
data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
parameters = {}
|
||||
if "parameters" in data.keys():
|
||||
if "command" in data and "commands" in data:
|
||||
return make_response("'command' and 'commands' are mutually exclusive", 400)
|
||||
elif ("command" in data or "commands" in data) and "script" in data:
|
||||
return make_response("'command'/'commands' and 'script' are mutually exclusive", 400)
|
||||
elif not ("command" in data or "commands" in data or "script" in data):
|
||||
return make_response("Need one of 'command', 'commands' or 'script'", 400)
|
||||
|
||||
parameters = dict()
|
||||
if "parameters" in data:
|
||||
parameters = data["parameters"]
|
||||
|
||||
commands = []
|
||||
if "command" in data.keys():
|
||||
commands = [data["command"]]
|
||||
elif "commands" in data.keys():
|
||||
commands = data["commands"]
|
||||
if "command" in data or "commands" in data:
|
||||
if "command" in data:
|
||||
commands = [data["command"]]
|
||||
else:
|
||||
if not isinstance(data["commands"], (list, tuple)):
|
||||
return make_response("'commands' needs to be a list", 400)
|
||||
commands = data["commands"]
|
||||
|
||||
commandsToSend = []
|
||||
for command in commands:
|
||||
commandToSend = command
|
||||
if len(parameters) > 0:
|
||||
commandToSend = command % parameters
|
||||
commandsToSend.append(commandToSend)
|
||||
commandsToSend = []
|
||||
for command in commands:
|
||||
commandToSend = command
|
||||
if len(parameters) > 0:
|
||||
commandToSend = command % parameters
|
||||
commandsToSend.append(commandToSend)
|
||||
|
||||
printer.commands(commandsToSend)
|
||||
printer.commands(commandsToSend)
|
||||
|
||||
elif "script" in data:
|
||||
script_name = data["script"]
|
||||
context = dict(parameters=parameters)
|
||||
if "context" in data:
|
||||
context["context"] = data["context"]
|
||||
|
||||
try:
|
||||
printer.script(script_name, context=context)
|
||||
except UnknownScript:
|
||||
return make_response("Unknown script: {script_name}".format(**locals()), 404)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/command/custom", methods=["GET"])
|
||||
def getCustomControls():
|
||||
# TODO: document me
|
||||
@@ -339,13 +383,13 @@ def getCustomControls():
|
||||
|
||||
|
||||
def _getTemperatureData(filter):
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
tempData = printer.getCurrentTemperatures()
|
||||
tempData = printer.get_current_temperatures()
|
||||
|
||||
if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues:
|
||||
tempHistory = printer.getTemperatureHistory()
|
||||
tempHistory = printer.get_temperature_history()
|
||||
|
||||
limit = 300
|
||||
if "limit" in request.values.keys() and unicode(request.values["limit"]).isnumeric():
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import copy
|
||||
|
||||
from flask import jsonify, make_response, request, url_for
|
||||
from flask.exceptions import JSONBadRequest
|
||||
|
||||
from octoprint.server.api import api, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.util import dict_merge
|
||||
|
||||
from octoprint.server import printerProfileManager
|
||||
from octoprint.printer.profile import InvalidProfileError, CouldNotOverwriteError, SaveError
|
||||
|
||||
|
||||
@api.route("/printerprofiles", methods=["GET"])
|
||||
def printerProfilesList():
|
||||
all_profiles = printerProfileManager.get_all()
|
||||
return jsonify(dict(profiles=_convert_profiles(all_profiles)))
|
||||
|
||||
@api.route("/printerprofiles", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerProfilesAdd():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "profile" in json_data:
|
||||
return make_response("No profile included in request", 400)
|
||||
|
||||
base_profile = printerProfileManager.get_default()
|
||||
if "basedOn" in json_data and isinstance(json_data["basedOn"], basestring):
|
||||
other_profile = printerProfileManager.get(json_data["basedOn"])
|
||||
if other_profile is not None:
|
||||
base_profile = other_profile
|
||||
|
||||
if "id" in base_profile:
|
||||
del base_profile["id"]
|
||||
if "name" in base_profile:
|
||||
del base_profile["name"]
|
||||
if "default" in base_profile:
|
||||
del base_profile["default"]
|
||||
|
||||
new_profile = json_data["profile"]
|
||||
make_default = False
|
||||
if "default" in new_profile:
|
||||
make_default = True
|
||||
del new_profile["default"]
|
||||
|
||||
profile = dict_merge(base_profile, new_profile)
|
||||
try:
|
||||
saved_profile = printerProfileManager.save(profile, allow_overwrite=False, make_default=make_default)
|
||||
except InvalidProfileError:
|
||||
return make_response("Profile is invalid", 400)
|
||||
except CouldNotOverwriteError:
|
||||
return make_response("Profile already exists and overwriting was not allowed", 400)
|
||||
except Exception as e:
|
||||
return make_response("Could not save profile: %s" % e.message, 500)
|
||||
else:
|
||||
return jsonify(dict(profile=_convert_profile(saved_profile)))
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["GET"])
|
||||
def printerProfilesGet(identifier):
|
||||
profile = printerProfileManager.get(identifier)
|
||||
if profile is None:
|
||||
return make_response("Unknown profile: %s" % identifier, 404)
|
||||
else:
|
||||
return jsonify(_convert_profile(profile))
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def printerProfilesDelete(identifier):
|
||||
printerProfileManager.remove(identifier)
|
||||
return NO_CONTENT
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["PATCH"])
|
||||
@restricted_access
|
||||
def printerProfilesUpdate(identifier):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "profile" in json_data:
|
||||
return make_response("No profile included in request", 400)
|
||||
|
||||
profile = printerProfileManager.get(identifier)
|
||||
if profile is None:
|
||||
profile = printerProfileManager.get_default()
|
||||
|
||||
new_profile = json_data["profile"]
|
||||
new_profile = dict_merge(profile, new_profile)
|
||||
|
||||
make_default = False
|
||||
if "default" in new_profile:
|
||||
make_default = True
|
||||
del new_profile["default"]
|
||||
|
||||
new_profile["id"] = identifier
|
||||
|
||||
try:
|
||||
saved_profile = printerProfileManager.save(new_profile, allow_overwrite=True, make_default=make_default)
|
||||
except InvalidProfileError:
|
||||
return make_response("Profile is invalid", 400)
|
||||
except CouldNotOverwriteError:
|
||||
return make_response("Profile already exists and overwriting was not allowed", 400)
|
||||
except Exception as e:
|
||||
return make_response("Could not save profile: %s" % e.message, 500)
|
||||
else:
|
||||
return jsonify(dict(profile=_convert_profile(saved_profile)))
|
||||
|
||||
def _convert_profiles(profiles):
|
||||
result = dict()
|
||||
for identifier, profile in profiles.items():
|
||||
result[identifier] = _convert_profile(profile)
|
||||
return result
|
||||
|
||||
def _convert_profile(profile):
|
||||
default = printerProfileManager.get_default()["id"]
|
||||
current = printerProfileManager.get_current_or_default()["id"]
|
||||
|
||||
converted = copy.deepcopy(profile)
|
||||
converted["resource"] = url_for(".printerProfilesGet", identifier=profile["id"], _external=True)
|
||||
converted["default"] = (profile["id"] == default)
|
||||
converted["current"] = (profile["id"] == current)
|
||||
return converted
|
||||
@@ -7,17 +7,19 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import logging
|
||||
|
||||
from flask import request, jsonify
|
||||
from flask import request, jsonify, make_response
|
||||
from flask.exceptions import JSONBadRequest
|
||||
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.settings import settings
|
||||
from octoprint.printer import getConnectionOptions
|
||||
from octoprint.printer import get_connection_options
|
||||
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
import octoprint.util
|
||||
|
||||
#~~ settings
|
||||
|
||||
@@ -26,30 +28,20 @@ import octoprint.plugin
|
||||
def getSettings():
|
||||
s = settings()
|
||||
|
||||
[movementSpeedX, movementSpeedY, movementSpeedZ, movementSpeedE] \
|
||||
= s.get(["printerParameters", "movementSpeed", ["x", "y", "z", "e"]])
|
||||
|
||||
connectionOptions = getConnectionOptions()
|
||||
connectionOptions = get_connection_options()
|
||||
|
||||
data = {
|
||||
"api": {
|
||||
"enabled": s.getBoolean(["api", "enabled"]),
|
||||
"key": s.get(["api", "key"]),
|
||||
"key": s.get(["api", "key"]) if admin_permission.can() else "n/a",
|
||||
"allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
|
||||
},
|
||||
"appearance": {
|
||||
"name": s.get(["appearance", "name"]),
|
||||
"color": s.get(["appearance", "color"])
|
||||
"color": s.get(["appearance", "color"]),
|
||||
"colorTransparent": s.getBoolean(["appearance", "colorTransparent"])
|
||||
},
|
||||
"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"]),
|
||||
"defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"])
|
||||
},
|
||||
"webcam": {
|
||||
@@ -57,6 +49,7 @@ def getSettings():
|
||||
"snapshotUrl": s.get(["webcam", "snapshot"]),
|
||||
"ffmpegPath": s.get(["webcam", "ffmpeg"]),
|
||||
"bitrate": s.get(["webcam", "bitrate"]),
|
||||
"ffmpegThreads": s.get(["webcam", "ffmpegThreads"]),
|
||||
"watermark": s.getBoolean(["webcam", "watermark"]),
|
||||
"flipH": s.getBoolean(["webcam", "flipH"]),
|
||||
"flipV": s.getBoolean(["webcam", "flipV"])
|
||||
@@ -69,7 +62,8 @@ def getSettings():
|
||||
"sdSupport": s.getBoolean(["feature", "sdSupport"]),
|
||||
"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
|
||||
"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
|
||||
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"])
|
||||
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
|
||||
"keyboardControl": s.getBoolean(["feature", "keyboardControl"])
|
||||
},
|
||||
"serial": {
|
||||
"port": connectionOptions["portPreference"],
|
||||
@@ -99,13 +93,25 @@ def getSettings():
|
||||
"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"])
|
||||
"scripts": {
|
||||
"gcode": {
|
||||
"afterPrinterConnected": None,
|
||||
"beforePrintStarted": None,
|
||||
"afterPrintCancelled": None,
|
||||
"afterPrintDone": None,
|
||||
"beforePrintPaused": None,
|
||||
"afterPrintResumed": None,
|
||||
"snippets": dict()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
gcode_scripts = s.listScripts("gcode")
|
||||
if gcode_scripts:
|
||||
data["scripts"] = dict(gcode=dict())
|
||||
for name in gcode_scripts:
|
||||
data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True)
|
||||
|
||||
def process_plugin_result(name, plugin, result):
|
||||
if result:
|
||||
if not "plugins" in data:
|
||||
@@ -125,108 +131,102 @@ def getSettings():
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def setSettings():
|
||||
if "application/json" in request.headers["Content-Type"]:
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
s = settings()
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
s = settings()
|
||||
|
||||
if "api" in data.keys():
|
||||
if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"])
|
||||
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
|
||||
if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
|
||||
if "api" in data.keys():
|
||||
if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"])
|
||||
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
|
||||
if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
|
||||
|
||||
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 "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 "colorTransparent" in data["appearance"].keys(): s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"])
|
||||
|
||||
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 "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
|
||||
if "printer" in data.keys():
|
||||
if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
|
||||
|
||||
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 "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 "ffmpegThreads" in data["webcam"].keys(): s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"])
|
||||
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 "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 "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
|
||||
|
||||
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"])
|
||||
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")
|
||||
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 "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"])
|
||||
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 "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"])
|
||||
|
||||
if "temperature" in data.keys():
|
||||
if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"])
|
||||
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 "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"])
|
||||
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)
|
||||
if "scripts" in data:
|
||||
if "gcode" in data["scripts"] and isinstance(data["scripts"]["gcode"], dict):
|
||||
for name, script in data["scripts"]["gcode"].items():
|
||||
if name == "snippets":
|
||||
continue
|
||||
s.saveScript("gcode", name, script.replace("\r\n", "\n").replace("\r", "\n"))
|
||||
|
||||
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)
|
||||
|
||||
if "plugins" in data:
|
||||
for name, plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin).items():
|
||||
if name in data["plugins"]:
|
||||
plugin.on_settings_save(data["plugins"][name])
|
||||
if "plugins" in data:
|
||||
for name, plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin).items():
|
||||
if name in data["plugins"]:
|
||||
plugin.on_settings_save(data["plugins"][name])
|
||||
|
||||
|
||||
s.save()
|
||||
if s.save():
|
||||
eventManager().fire(Events.SETTINGS_UPDATED)
|
||||
|
||||
return getSettings()
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, make_response, url_for
|
||||
from flask.exceptions import JSONBadRequest
|
||||
|
||||
from octoprint.server import slicingManager
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.api import api, NO_CONTENT
|
||||
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
|
||||
from octoprint.slicing import SlicerNotConfigured
|
||||
|
||||
|
||||
@api.route("/slicing", methods=["GET"])
|
||||
def slicingListAll():
|
||||
default_slicer = s().get(["slicing", "defaultSlicer"])
|
||||
|
||||
if "configured" in request.values and request.values["configured"] in valid_boolean_trues:
|
||||
slicers = slicingManager.configured_slicers
|
||||
else:
|
||||
slicers = slicingManager.registered_slicers
|
||||
|
||||
result = dict()
|
||||
for slicer in slicers:
|
||||
slicer_impl = slicingManager.get_slicer(slicer, require_configured=False)
|
||||
result[slicer] = dict(
|
||||
key=slicer,
|
||||
displayName=slicer_impl.get_slicer_properties()["name"],
|
||||
default=default_slicer == slicer,
|
||||
configured = slicer_impl.is_slicer_configured(),
|
||||
profiles=_getSlicingProfilesData(slicer)
|
||||
)
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles", methods=["GET"])
|
||||
def slicingListSlicerProfiles(slicer):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
configured = False
|
||||
if "configured" in request.values and request.values["configured"] in valid_boolean_trues:
|
||||
if not slicer in slicingManager.configured_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
configured = True
|
||||
|
||||
return jsonify(_getSlicingProfilesData(slicer, require_configured=configured))
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["GET"])
|
||||
def slicingGetSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
profile = slicingManager.load_profile(slicer, name)
|
||||
if not profile:
|
||||
return make_response("Profile not found", 404)
|
||||
|
||||
result = _getSlicingProfileData(slicer, name, profile)
|
||||
result["data"] = profile.data
|
||||
return jsonify(result)
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PUT"])
|
||||
@restricted_access
|
||||
def slicingAddSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
data = dict()
|
||||
display_name = None
|
||||
description = None
|
||||
if "data" in json_data:
|
||||
data = json_data["data"]
|
||||
if "displayName" in json_data:
|
||||
display_name = json_data["displayName"]
|
||||
if "description" in json_data:
|
||||
description = json_data["description"]
|
||||
|
||||
profile = slicingManager.save_profile(slicer, name, data, display_name=display_name, description=description)
|
||||
|
||||
result = _getSlicingProfileData(slicer, name, profile)
|
||||
r = make_response(jsonify(result), 201)
|
||||
r.headers["Location"] = result["resource"]
|
||||
return r
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PATCH"])
|
||||
@restricted_access
|
||||
def slicingPatchSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
profile = slicingManager.load_profile(slicer, name)
|
||||
if not profile:
|
||||
return make_response("Profile not found", 404)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
data = dict()
|
||||
display_name = None
|
||||
description = None
|
||||
if "data" in json_data:
|
||||
data = json_data["data"]
|
||||
if "displayName" in json_data:
|
||||
display_name = json_data["displayName"]
|
||||
if "description" in json_data:
|
||||
description = json_data["description"]
|
||||
|
||||
from octoprint.server.api import valid_boolean_trues
|
||||
if "default" in json_data and json_data["default"] in valid_boolean_trues:
|
||||
default_profiles = s().get(["slicing", "defaultProfiles"])
|
||||
if not default_profiles:
|
||||
default_profiles = dict()
|
||||
default_profiles[slicer] = name
|
||||
s().set(["slicing", "defaultProfiles"], default_profiles)
|
||||
s().save(force=True)
|
||||
|
||||
slicingManager.save_profile(slicer, name, profile, overrides=data, display_name=display_name, description=description)
|
||||
return NO_CONTENT
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def slicingDelSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
slicingManager.delete_profile(slicer, name)
|
||||
return NO_CONTENT
|
||||
|
||||
def _getSlicingProfilesData(slicer, require_configured=False):
|
||||
try:
|
||||
profiles = slicingManager.all_profiles(slicer, require_configured=require_configured)
|
||||
except SlicerNotConfigured:
|
||||
return dict()
|
||||
|
||||
result = dict()
|
||||
for name, profile in profiles.items():
|
||||
result[name] = _getSlicingProfileData(slicer, name, profile)
|
||||
return result
|
||||
|
||||
def _getSlicingProfileData(slicer, name, profile):
|
||||
defaultProfiles = s().get(["slicing", "defaultProfiles"])
|
||||
result = dict(
|
||||
key=name,
|
||||
default=defaultProfiles and slicer in defaultProfiles and defaultProfiles[slicer] == name,
|
||||
resource=url_for(".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True)
|
||||
)
|
||||
if profile.display_name is not None:
|
||||
result["displayName"] = profile.display_name
|
||||
if profile.description is not None:
|
||||
result["description"] = profile.description
|
||||
return result
|
||||
@@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import os
|
||||
|
||||
from flask import request, jsonify, url_for
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
import octoprint.timelapse
|
||||
@@ -30,9 +30,11 @@ def getTimelapseData():
|
||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||
config["type"] = "zchange"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||
config["type"] = "timed"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
config.update({
|
||||
"interval": timelapse.interval()
|
||||
})
|
||||
@@ -55,10 +57,11 @@ def downloadTimelapse(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)
|
||||
if util.is_allowed_file(filename, {"mpg"}):
|
||||
timelapse_folder = settings().getBaseFolder("timelapse")
|
||||
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
|
||||
if full_path.startswith(timelapse_folder) and os.path.exists(full_path):
|
||||
os.remove(full_path)
|
||||
return getTimelapseData()
|
||||
|
||||
|
||||
@@ -69,26 +72,46 @@ def setTimelapseConfig():
|
||||
config = {
|
||||
"type": request.values["type"],
|
||||
"postRoll": 0,
|
||||
"fps": 25,
|
||||
"options": {}
|
||||
}
|
||||
|
||||
|
||||
if "postRoll" in request.values:
|
||||
try:
|
||||
config["postRoll"] = int(request.values["postRoll"])
|
||||
postRoll = int(request.values["postRoll"])
|
||||
except ValueError:
|
||||
pass
|
||||
return make_response("Invalid value for postRoll: %r" % request.values["postRoll"], 400)
|
||||
else:
|
||||
if postRoll >= 0:
|
||||
config["postRoll"] = postRoll
|
||||
else:
|
||||
return make_response("Invalid value for postRoll: %d" % postRoll, 400)
|
||||
|
||||
if "fps" in request.values:
|
||||
try:
|
||||
fps = int(request.values["fps"])
|
||||
except ValueError:
|
||||
return make_response("Invalid value for fps: %r" % request.values["fps"], 400)
|
||||
else:
|
||||
if fps > 0:
|
||||
config["fps"] = fps
|
||||
else:
|
||||
return make_response("Invalid value for fps: %d" % fps, 400)
|
||||
|
||||
if "interval" in request.values:
|
||||
interval = 10
|
||||
config["options"] = {
|
||||
"interval": 10
|
||||
}
|
||||
|
||||
try:
|
||||
interval = int(request.values["interval"])
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
config["options"] = {
|
||||
"interval": interval
|
||||
}
|
||||
return make_response("Invalid value for interval: %r" % request.values["interval"])
|
||||
else:
|
||||
if interval > 0:
|
||||
config["options"]["interval"] = interval
|
||||
else:
|
||||
return make_response("Invalid value for interval: %d" % interval)
|
||||
|
||||
if admin_permission.can() and "save" in request.values and request.values["save"] in valid_boolean_trues:
|
||||
octoprint.timelapse.configureTimelapse(config, True)
|
||||
|
||||
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, abort, make_response
|
||||
from flask.exceptions import JSONBadRequest
|
||||
from flask.ext.login import current_user
|
||||
|
||||
import octoprint.users as users
|
||||
@@ -35,21 +36,26 @@ def addUser():
|
||||
if userManager is None:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if "application/json" in request.headers["Content-Type"]:
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
name = data["name"]
|
||||
password = data["password"]
|
||||
active = data["active"]
|
||||
name = data["name"]
|
||||
password = data["password"]
|
||||
active = data["active"]
|
||||
|
||||
roles = ["user"]
|
||||
if "admin" in data.keys() and data["admin"]:
|
||||
roles.append("admin")
|
||||
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)
|
||||
try:
|
||||
userManager.addUser(name, password, active, roles)
|
||||
except users.UserAlreadyExists:
|
||||
abort(409)
|
||||
return getUsers()
|
||||
|
||||
|
||||
@@ -78,18 +84,23 @@ def updateUser(username):
|
||||
|
||||
user = userManager.findUser(username)
|
||||
if user is not None:
|
||||
if "application/json" in request.headers["Content-Type"]:
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
# change roles
|
||||
roles = ["user"]
|
||||
if "admin" in data.keys() and data["admin"]:
|
||||
roles.append("admin")
|
||||
userManager.changeUserRoles(username, roles)
|
||||
# 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"])
|
||||
# change activation
|
||||
if "active" in data.keys():
|
||||
userManager.changeUserActivation(username, data["active"])
|
||||
return getUsers()
|
||||
else:
|
||||
abort(404)
|
||||
@@ -116,13 +127,22 @@ def changePasswordForUser(username):
|
||||
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"]:
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
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, []))
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "password" in data.keys() or not data["password"]:
|
||||
return make_response("password is missing from request", 400)
|
||||
|
||||
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, []))
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import rsa
|
||||
from flask import Blueprint, request, make_response, jsonify
|
||||
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.settings import settings as s
|
||||
|
||||
apps = Blueprint("apps", __name__)
|
||||
|
||||
@apps.route("/auth", methods=["GET"])
|
||||
def getSessionKey():
|
||||
unverified_key, valid_until = octoprint.server.appSessionManager.create()
|
||||
return jsonify(unverifiedKey=unverified_key, validUntil=valid_until)
|
||||
|
||||
@apps.route("/auth", methods=["POST"])
|
||||
def verifySessionKey():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
for key in ("appid", "key", "_sig"):
|
||||
if not key in data:
|
||||
return make_response("Missing argument: {key}".format(key=key), 400)
|
||||
|
||||
appid = str(data["appid"])
|
||||
if not "appversion" in data:
|
||||
appversion = "any"
|
||||
else:
|
||||
appversion = str(data["appversion"])
|
||||
key = str(data["key"])
|
||||
|
||||
# calculate message that was signed
|
||||
message = "{appid}:{appversion}:{key}".format(**locals())
|
||||
|
||||
# decode signature
|
||||
import base64
|
||||
signature = data["_sig"]
|
||||
signature = base64.decodestring("\n".join([signature[x:x+64] for x in range(0, len(signature), 64)]))
|
||||
|
||||
# fetch and validate app information
|
||||
lookup_key = appid + ":" + appversion
|
||||
apps = _get_registered_apps()
|
||||
if not lookup_key in apps or not apps[lookup_key]["enabled"] or not "pubkey" in apps[lookup_key]:
|
||||
octoprint.server.appSessionManager.remove(key)
|
||||
return make_response("Invalid app: {lookup_key}".format(lookup_key=lookup_key), 401)
|
||||
|
||||
pubkey_string = apps[lookup_key]["pubkey"]
|
||||
pubkey_string = "\n".join([pubkey_string[x:x+64] for x in range(0, len(pubkey_string), 64)])
|
||||
try:
|
||||
pubkey = rsa.PublicKey.load_pkcs1("-----BEGIN RSA PUBLIC KEY-----\n" + pubkey_string + "\n-----END RSA PUBLIC KEY-----\n")
|
||||
except:
|
||||
octoprint.server.appSessionManager.remove(key)
|
||||
return make_response("Invalid pubkey stored in server", 500)
|
||||
|
||||
# verify signature
|
||||
try:
|
||||
rsa.verify(message, signature, pubkey)
|
||||
except rsa.VerificationError:
|
||||
octoprint.server.appSessionManager.remove(key)
|
||||
return make_response("Invalid signature", 401)
|
||||
|
||||
# generate new session key and return it
|
||||
result = octoprint.server.appSessionManager.verify(key)
|
||||
if not result:
|
||||
return make_response("Invalid key or already verified", 401)
|
||||
|
||||
verified_key, valid_until = result
|
||||
return jsonify(key=verified_key, validUntil=valid_until)
|
||||
|
||||
__registered_apps = None
|
||||
def _get_registered_apps():
|
||||
global __registered_apps
|
||||
|
||||
if __registered_apps is not None:
|
||||
return __registered_apps
|
||||
|
||||
apps = s().get(["api", "apps"], merged=True)
|
||||
for app, app_data in apps.items():
|
||||
if not "enabled" in app_data:
|
||||
apps[app]["enabled"] = True
|
||||
|
||||
app_plugins = octoprint.server.pluginManager.get_implementations(octoprint.plugin.AppPlugin)
|
||||
for name, plugin in app_plugins.items():
|
||||
additional_apps = plugin.get_additional_apps()
|
||||
any_version_enabled = dict()
|
||||
|
||||
for app_data in additional_apps:
|
||||
id, version, pubkey = app_data
|
||||
key = id + ":" + version
|
||||
if key in apps:
|
||||
continue
|
||||
|
||||
if not id in any_version_enabled:
|
||||
any_version_enabled[id] = False
|
||||
|
||||
if version == "any":
|
||||
any_version_enabled[id] = True
|
||||
|
||||
apps[key] = dict(
|
||||
pubkey=pubkey,
|
||||
enabled=True
|
||||
)
|
||||
|
||||
for id, enabled in any_version_enabled.items():
|
||||
if enabled:
|
||||
continue
|
||||
apps[id + ":any"] = dict(
|
||||
pubkey=None,
|
||||
enabled=False
|
||||
)
|
||||
|
||||
__registered_apps = apps
|
||||
return apps
|
||||
@@ -10,22 +10,97 @@ import octoprint.timelapse
|
||||
import octoprint.server
|
||||
from octoprint.users import ApiUser
|
||||
|
||||
import flask as _flask
|
||||
|
||||
from . import flask
|
||||
from . import sockjs
|
||||
from . import tornado
|
||||
from . import watchdog
|
||||
|
||||
|
||||
def apiKeyRequestHandler():
|
||||
"""
|
||||
All requests in this blueprint need to be made supplying an API key. This may be the UI_API_KEY, in which case
|
||||
the underlying request processing will directly take place, or it may be the global or a user specific case. In any
|
||||
case it has to be present and must be valid, so anything other than the above three types will result in denying
|
||||
the request.
|
||||
"""
|
||||
|
||||
import octoprint.server
|
||||
|
||||
if _flask.request.method == 'OPTIONS' and settings().getBoolean(["api", "allowCrossOrigin"]):
|
||||
return optionsAllowOrigin(_flask.request)
|
||||
|
||||
apikey = get_api_key(_flask.request)
|
||||
if apikey is None:
|
||||
# no api key => 401
|
||||
return _flask.make_response("No API key provided", 401)
|
||||
|
||||
if apikey == octoprint.server.UI_API_KEY:
|
||||
# ui api key => continue regular request processing
|
||||
return
|
||||
|
||||
if not settings().get(["api", "enabled"]):
|
||||
# api disabled => 401
|
||||
return _flask.make_response("API disabled", 401)
|
||||
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# global api key => continue regular request processing
|
||||
return
|
||||
|
||||
if octoprint.server.appSessionManager.validate(apikey):
|
||||
# app session key => continue regular request processing
|
||||
return
|
||||
|
||||
user = get_user_for_apikey(apikey)
|
||||
if user is not None:
|
||||
# user specific api key => continue regular request processing
|
||||
return
|
||||
|
||||
# invalid api key => 401
|
||||
return _flask.make_response("Invalid API key", 401)
|
||||
|
||||
|
||||
def corsResponseHandler(resp):
|
||||
|
||||
# Allow crossdomain
|
||||
allowCrossOrigin = settings().getBoolean(["api", "allowCrossOrigin"])
|
||||
if _flask.request.method != 'OPTIONS' and 'Origin' in _flask.request.headers and allowCrossOrigin:
|
||||
resp.headers['Access-Control-Allow-Origin'] = _flask.request.headers['Origin']
|
||||
|
||||
return resp
|
||||
|
||||
|
||||
def optionsAllowOrigin(request):
|
||||
""" Always reply 200 on OPTIONS request """
|
||||
|
||||
resp = _flask.current_app.make_default_options_response()
|
||||
|
||||
# Allow the origin which made the XHR
|
||||
resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
|
||||
# Allow the actual method
|
||||
resp.headers['Access-Control-Allow-Methods'] = request.headers['Access-Control-Request-Method']
|
||||
# Allow for 10 seconds
|
||||
resp.headers['Access-Control-Max-Age'] = "10"
|
||||
|
||||
# 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key)
|
||||
customRequestHeaders = request.headers.get('Access-Control-Request-Headers', None)
|
||||
if customRequestHeaders is not None:
|
||||
# If present => allow them all
|
||||
resp.headers['Access-Control-Allow-Headers'] = customRequestHeaders
|
||||
|
||||
return resp
|
||||
|
||||
|
||||
def get_user_for_apikey(apikey):
|
||||
if settings().get(["api", "enabled"]) and apikey is not None:
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# master key was used
|
||||
if apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey):
|
||||
# master key or an app session key was used
|
||||
return ApiUser()
|
||||
else:
|
||||
elif octoprint.server.userManager is not None:
|
||||
# user key might have been used
|
||||
return octoprint.server.userManager.findUser(apikey=apikey)
|
||||
else:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def get_api_key(request):
|
||||
@@ -72,20 +147,25 @@ class ReverseProxied(object):
|
||||
:param app: the WSGI application
|
||||
:param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix
|
||||
:param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme
|
||||
:param header_host: the HTTP header in the wsgi environment from which to determine the host for which to generate external URLs
|
||||
:param base_url: the prefix to use as fallback if headers are not set
|
||||
:param scheme: the scheme to use as fallback if headers are not set
|
||||
:param host: the host to use as fallback if headers are not set
|
||||
"""
|
||||
|
||||
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", base_url="", scheme=""):
|
||||
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", header_host="x-forwarded-host", base_url="", scheme="", host=""):
|
||||
self.app = app
|
||||
|
||||
# headers for prefix & scheme, converted to conform to WSGI format
|
||||
# headers for prefix & scheme & host, converted to conform to WSGI format
|
||||
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
|
||||
self._header_prefix = to_wsgi_format(header_prefix)
|
||||
self._header_scheme = to_wsgi_format(header_scheme)
|
||||
self._header_host = to_wsgi_format(header_host)
|
||||
|
||||
# fallback prefix & scheme from config
|
||||
# fallback prefix & scheme & host from config
|
||||
self._fallback_prefix = base_url
|
||||
self._fallback_scheme = scheme
|
||||
self._fallback_host = host
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
# determine prefix
|
||||
@@ -109,6 +189,15 @@ class ReverseProxied(object):
|
||||
if scheme:
|
||||
environ["wsgi.url_scheme"] = scheme
|
||||
|
||||
# determine host
|
||||
host = environ.get(self._header_host, "")
|
||||
if not host:
|
||||
host = self._fallback_host
|
||||
|
||||
# rewrite host header based on host
|
||||
if host:
|
||||
environ["HTTP_HOST"] = host
|
||||
|
||||
# call wrapped app with rewritten environment
|
||||
return self.app(environ, start_response)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
from flask import make_response
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -10,11 +11,57 @@ import flask
|
||||
import flask.ext.login
|
||||
import flask.ext.principal
|
||||
import functools
|
||||
import time
|
||||
import uuid
|
||||
import threading
|
||||
import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
import octoprint.server
|
||||
import octoprint.users
|
||||
|
||||
from werkzeug.contrib.cache import SimpleCache
|
||||
|
||||
|
||||
#~~ cache decorator for cacheable views
|
||||
|
||||
_cache = SimpleCache()
|
||||
|
||||
def cached(timeout=5 * 60, key="view/%s", unless=None, refreshif=None):
|
||||
def decorator(f):
|
||||
@functools.wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# bypass the cache if "unless" condition is true
|
||||
if callable(unless) and unless():
|
||||
logger.debug("Cache bypassed, calling wrapped function")
|
||||
return f(*args, **kwargs)
|
||||
|
||||
cache_key = key % flask.request.path
|
||||
|
||||
# only take the value from the cache if we are not required to refresh it from the wrapped function
|
||||
if not callable(refreshif) or not refreshif():
|
||||
rv = _cache.get(cache_key)
|
||||
if rv is not None:
|
||||
logger.debug("Serving entry from cache")
|
||||
return rv
|
||||
|
||||
# get value from wrapped function
|
||||
logger.debug("No cache entry or refreshing cache, calling wrapped function")
|
||||
rv = f(*args, **kwargs)
|
||||
|
||||
# store it in the cache
|
||||
_cache.set(cache_key, rv, timeout=timeout)
|
||||
|
||||
return rv
|
||||
|
||||
return decorated_function
|
||||
|
||||
return decorator
|
||||
|
||||
def cache_check_headers():
|
||||
return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma
|
||||
|
||||
#~~ access validators for use with tornado
|
||||
|
||||
@@ -119,12 +166,7 @@ def restricted_access(func, api_enabled=True):
|
||||
# if API is globally enabled, enabled for this request and an api key is provided that is not the current UI API key, try to use that
|
||||
apikey = octoprint.server.util.get_api_key(flask.request)
|
||||
if settings().get(["api", "enabled"]) and api_enabled and apikey is not None and apikey != octoprint.server.UI_API_KEY:
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# master key was used
|
||||
user = octoprint.users.ApiUser()
|
||||
else:
|
||||
# user key might have been used
|
||||
user = octoprint.server.userManager.findUser(apikey=apikey)
|
||||
user = octoprint.server.util.get_user_for_apikey(apikey)
|
||||
|
||||
if user is None:
|
||||
return flask.make_response("Invalid API key", 401)
|
||||
@@ -137,18 +179,92 @@ def restricted_access(func, api_enabled=True):
|
||||
return decorated_view
|
||||
|
||||
|
||||
def api_access(func):
|
||||
@functools.wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
if not settings().get(["api", "enabled"]):
|
||||
flask.make_response("API disabled", 401)
|
||||
apikey = octoprint.server.util.get_api_key(flask.request)
|
||||
if apikey is None:
|
||||
flask.make_response("No API key provided", 401)
|
||||
if apikey != settings().get(["api", "key"]):
|
||||
flask.make_response("Invalid API key", 403)
|
||||
return func(*args, **kwargs)
|
||||
return decorated_view
|
||||
class AppSessionManager(object):
|
||||
|
||||
VALIDITY_UNVERIFIED = 1 * 60 # 1 minute
|
||||
VALIDITY_VERIFIED = 2 * 60 * 60 # 2 hours
|
||||
|
||||
def __init__(self):
|
||||
self._sessions = dict()
|
||||
self._oldest = None
|
||||
self._mutex = threading.RLock()
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
def create(self):
|
||||
self._clean_sessions()
|
||||
|
||||
key = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
|
||||
created = time.time()
|
||||
valid_until = created + self.__class__.VALIDITY_UNVERIFIED
|
||||
|
||||
with self._mutex:
|
||||
self._sessions[key] = (created, False, valid_until)
|
||||
return key, valid_until
|
||||
|
||||
def remove(self, key):
|
||||
with self._mutex:
|
||||
if not key in self._sessions:
|
||||
return
|
||||
del self._sessions[key]
|
||||
|
||||
def verify(self, key):
|
||||
self._clean_sessions()
|
||||
|
||||
if not key in self._sessions:
|
||||
return False
|
||||
|
||||
with self._mutex:
|
||||
created, verified, _ = self._sessions[key]
|
||||
if verified:
|
||||
return False
|
||||
|
||||
valid_until = created + self.__class__.VALIDITY_VERIFIED
|
||||
self._sessions[key] = created, True, created + self.__class__.VALIDITY_VERIFIED
|
||||
|
||||
return key, valid_until
|
||||
|
||||
def validate(self, key):
|
||||
self._clean_sessions()
|
||||
return key in self._sessions and self._sessions[key][1]
|
||||
|
||||
def _clean_sessions(self):
|
||||
if self._oldest is not None and self._oldest > time.time():
|
||||
return
|
||||
|
||||
with self._mutex:
|
||||
self._oldest = None
|
||||
for key, value in self._sessions.items():
|
||||
created, verified, valid_until = value
|
||||
if not verified:
|
||||
valid_until = created + self.__class__.VALIDITY_UNVERIFIED
|
||||
|
||||
if valid_until < time.time():
|
||||
del self._sessions[key]
|
||||
elif self._oldest is None or valid_until < self._oldest:
|
||||
self._oldest = valid_until
|
||||
|
||||
self._logger.debug("App sessions after cleanup: %r" % self._sessions)
|
||||
|
||||
|
||||
def get_remote_address(request):
|
||||
forwardedFor = request.headers.get("X-Forwarded-For", None)
|
||||
if forwardedFor is not None:
|
||||
return forwardedFor.split(",")[0]
|
||||
return request.remote_addr
|
||||
|
||||
|
||||
def get_json_command_from_request(request, valid_commands):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
if not "command" in data.keys() or not data["command"] in valid_commands.keys():
|
||||
return None, None, make_response("Expected valid command", 400)
|
||||
|
||||
command = data["command"]
|
||||
for parameter in valid_commands[command]:
|
||||
if not parameter in data:
|
||||
return None, None, make_response("Mandatory parameter %s missing for command %s" % (parameter, command), 400)
|
||||
|
||||
return command, data, None
|
||||
@@ -13,9 +13,11 @@ import octoprint.timelapse
|
||||
import octoprint.server
|
||||
from octoprint.events import Events
|
||||
|
||||
import octoprint.printer
|
||||
|
||||
class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
def __init__(self, printer, gcodeManager, userManager, eventManager, session):
|
||||
|
||||
class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback):
|
||||
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session):
|
||||
sockjs.tornado.SockJSConnection.__init__(self, session)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
@@ -28,9 +30,13 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
self._messageBacklogMutex = threading.Lock()
|
||||
|
||||
self._printer = printer
|
||||
self._gcodeManager = gcodeManager
|
||||
self._fileManager = fileManager
|
||||
self._analysisQueue = analysisQueue
|
||||
self._userManager = userManager
|
||||
self._eventManager = eventManager
|
||||
self._pluginManager = pluginManager
|
||||
|
||||
self._remoteAddress = None
|
||||
|
||||
def _getRemoteAddress(self, info):
|
||||
forwardedFor = info.headers.get("X-Forwarded-For")
|
||||
@@ -39,36 +45,38 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
return info.ip
|
||||
|
||||
def on_open(self, info):
|
||||
remoteAddress = self._getRemoteAddress(info)
|
||||
self._logger.info("New connection from client: %s" % remoteAddress)
|
||||
self._remoteAddress = self._getRemoteAddress(info)
|
||||
self._logger.info("New connection from client: %s" % self._remoteAddress)
|
||||
|
||||
# connected => update the API key, might be necessary if the client was left open while the server restarted
|
||||
self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION})
|
||||
|
||||
self._printer.registerCallback(self)
|
||||
self._gcodeManager.registerCallback(self)
|
||||
self._printer.register_callback(self)
|
||||
self._fileManager.register_slicingprogress_callback(self)
|
||||
octoprint.timelapse.registerCallback(self)
|
||||
self._pluginManager.register_client(self)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
|
||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
|
||||
for event in octoprint.events.all_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)
|
||||
self._logger.info("Client connection closed: %s" % self._remoteAddress)
|
||||
self._printer.unregister_callback(self)
|
||||
self._fileManager.unregister_slicingprogress_callback(self)
|
||||
octoprint.timelapse.unregisterCallback(self)
|
||||
self._pluginManager.unregister_client(self)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_CLOSED)
|
||||
self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.unsubscribe(event, self._onEvent)
|
||||
|
||||
def on_message(self, message):
|
||||
pass
|
||||
|
||||
def sendCurrentData(self, data):
|
||||
def on_printer_send_current_data(self, data):
|
||||
# add current temperature, log and message backlogs to sent data
|
||||
with self._temperatureBacklogMutex:
|
||||
temperatures = self._temperatureBacklog
|
||||
@@ -82,34 +90,47 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
messages = self._messageBacklog
|
||||
self._messageBacklog = []
|
||||
|
||||
busy_files = [dict(origin=v[0], name=v[1]) for v in self._fileManager.get_busy_files()]
|
||||
if "job" in data and data["job"] is not None \
|
||||
and "file" in data["job"] and "name" in data["job"]["file"] and "origin" in data["job"]["file"] \
|
||||
and data["job"]["file"]["name"] is not None and data["job"]["file"]["origin"] is not None \
|
||||
and (self._printer.is_printing() or self._printer.is_paused()):
|
||||
busy_files.append(dict(origin=data["job"]["file"]["origin"], name=data["job"]["file"]["name"]))
|
||||
|
||||
data.update({
|
||||
"temps": temperatures,
|
||||
"logs": logs,
|
||||
"messages": messages
|
||||
"temps": temperatures,
|
||||
"logs": logs,
|
||||
"messages": messages,
|
||||
"busyFiles": busy_files,
|
||||
})
|
||||
self._emit("current", data)
|
||||
|
||||
def sendHistoryData(self, data):
|
||||
def on_printer_send_initial_data(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):
|
||||
def sendSlicingProgress(self, slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
self._emit("slicingProgress",
|
||||
dict(slicer=slicer, source_location=source_location, source_path=source_path, dest_location=dest_location, dest_path=dest_path, progress=progress)
|
||||
)
|
||||
|
||||
def sendPluginMessage(self, plugin, data):
|
||||
self._emit("plugin", dict(plugin=plugin, data=data))
|
||||
|
||||
def on_printer_add_log(self, data):
|
||||
with self._logBacklogMutex:
|
||||
self._logBacklog.append(data)
|
||||
|
||||
def addMessage(self, data):
|
||||
def on_printer_add_message(self, data):
|
||||
with self._messageBacklogMutex:
|
||||
self._messageBacklog.append(data)
|
||||
|
||||
def addTemperature(self, data):
|
||||
def on_printer_add_temperature(self, data):
|
||||
with self._temperatureBacklogMutex:
|
||||
self._temperatureBacklog.append(data)
|
||||
|
||||
@@ -117,4 +138,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
self.sendEvent(event, payload)
|
||||
|
||||
def _emit(self, type, payload):
|
||||
self.send({type: payload})
|
||||
try:
|
||||
self.send({type: payload})
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, e.message))
|
||||