Compare commits

...
Author SHA1 Message Date
Gina Häußge cb2097793c WIP: Working on getting gcode viewer to reload/rezoom upon changing the current printer profile 2014-12-08 10:12:53 +01:00
Gina Häußge f7f70108bc Make sure the printer profile fields are all of the correct type during validation 2014-12-05 12:20:35 +01:00
Gina Häußge bd08eadac9 Fixed a bug causing the _default profile to be saved to a file instead of config.yaml 2014-12-05 12:01:02 +01:00
Gina Häußge a2314a9ab3 Fixed URL endpoint for printer profile API, it's supposed to be "api/printerprofiles", not "api/printerProfiles" 2014-12-05 11:52:27 +01:00
Gina Häußge e1b071c0d8 Removed old printer parameter and appearance settings and added auto migration of config 2014-12-05 11:46:55 +01:00
Gina Häußge aba8a57fa5 Added possibility to say to select or directly a file right after slicing it finished, both to the API and the UI 2014-12-04 18:06:35 +01:00
Gina Häußge 5784ab82ef WIP: Adding option to start printing directly after slicing 2014-12-04 15:31:00 +01:00
Gina Häußge 636e79672a The API now allows to specify where on the print bed to put the sliced model's center 2014-12-04 12:52:33 +01:00
Gina Häußge b935e96448 Fixed a bug causing slicing not to work if no printer profile was provided 2014-12-03 08:52:20 +01:00
Gina Häußge 56ad5b97b6 This on the other hand really fixes it and doesn't break anything in the progress 2014-12-02 17:48:12 +01:00
Gina Häußge dcead7361f Nope, reverting that fix, that broke something else 2014-12-02 17:28:53 +01:00
Gina Häußge ef314340fa Fixed a bug that caused medium to large sized STLs not to properly report progress when being sliced via the Cura plugin 2014-12-02 17:10:52 +01:00
Gina Häußge a149cdc4f5 Added the nozzle diameter to the printer profile (needed for slicing, cura plugin uses it too) 2014-12-02 12:41:25 +01:00
Gina Häußge fc777e69e2 API Documentation updated for printer profiles (still a WIP though) 2014-12-02 11:57:03 +01:00
Gina Häußge 2ea1b9df6c Fully switched to printer profiles 2014-12-02 11:30:00 +01:00
Gina Häußge 05e54fa0c6 Internal representation for extruder offsets changed, adjusted gcode viewer view model to be able to cope 2014-12-01 16:36:08 +01:00
Gina Häußge 0203e6da31 More work on the printer profiles, connection dialog and Settings dialog are now working. GCODE viewer makes trouble 2014-12-01 16:26:55 +01:00
Gina Häußge 93a852e6ea WIP: Printer profiles & management now functional, but integration with connection dialog still broken
The API documentation is also still missing.
2014-11-29 20:55:30 +01:00
Gina Häußge 985b0970f1 More work on the printer profiles 2014-11-29 12:32:55 +01:00
Gina Häußge a56ddb9ebe WIP commit, probably a tad bit broken ;) 2014-11-28 11:29:38 +01:00
Gina Häußge 1957d2bb58 WIP First work towards printer profiles 2014-11-28 09:32:44 +01:00
Gina Häußge e55f11c5b9 Fixed wrong default types for plugin hooks etc 2014-11-26 16:53:35 +01:00
Gina Häußge 07133b79e5 Track modification time of configuration file and reload it if it was externally modified before changing settings 2014-11-25 17:04:27 +01:00
Gina Häußge 183a8feed4 Plugins can now push messages via the websocket as well 2014-11-25 09:08:33 +01:00
Gina Häußge e3253fce16 Changed name of cura plugin to CuraEngine 2014-11-24 17:52:39 +01:00
Gina Häußge acd6f729f0 Wait at least 5s before reloading the UI 2014-11-20 12:16:59 +01:00
Gina Häußge ec85cccc75 Initialize logging before plugin manager, otherwise the logging output of the latter will not be visible 2014-11-19 11:33:20 +01:00
Gina Häußge f3f640c24f On reconnect to server, check if the version changed and if so hard-reload the UI 2014-11-19 09:16:37 +01:00
Gina Häußge 9c2b42caa2 Added an additional constant for the plugin base url for blueprint plugins 2014-11-19 09:03:50 +01:00
Gina Häußge a677ffc90e Only bind additional view models from plugins if they specify a target to bind to 2014-11-19 09:03:11 +01:00
Gina Häußge 254145da22 Also protect resources from blueprint plugins with the api key (unless the plugin specifies otherwise) 2014-11-19 09:02:33 +01:00
Gina Häußge fec51ebc8e Fixed a merge error that caused duplicated code and missing auto migration of reverse proxy settings 2014-11-17 13:50:47 +01:00
Gina Häußge 9d66aea843 Documentation and changelog entries updated 2014-11-17 13:49:46 +01:00
Gina Häußge 50895a662a Updating the settings now fires a new event "SettingsUpdated" 2014-11-17 11:06:54 +01:00
Gina Häußge 048ad78778 Do not deliver API key on settings API unless user has admin rights. 2014-11-14 18:24:57 +01:00
Gina Häußge e9beffc799 Properly recognize app session keys everywhere. Also fixed a bug where the ApiUser was not properly provisioned with his roles. 2014-11-14 17:58:42 +01:00
Gina Häußge fe9dd5ef28 Send 401 Unauthorized instead of 403 Forbidden upon failed app session verification 2014-11-14 15:02:52 +01:00
Gina Häußge 468e4b6d55 Support for a new type of API key
In order to solve the initial handshake problem with apps, OctoPrint now supports so called app session keys which are basically API keys with a limited validity. Obtaining those keys is based on a handshake procedure backed by RSA signatures. OctoPrint needs to be aware of apps and their associated public keys (with the AppPlugin there exists a mechanism to add additional recognized apps by installing a plugin). 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.
2014-11-14 14:30:25 +01:00
Gina Häußge b48ac505fd Allow to fetch whole tree from the settings merged with the defaults 2014-11-14 10:42:02 +01:00
Gina Häußge 947de33b5a Merge branch 'Booli-updateSettingsModal' into devel 2014-11-12 11:28:39 +01:00
Gina Häußge 4b9cd490ab Merge branch 'updateSettingsModal' of https://github.com/Booli/OctoPrint into Booli-updateSettingsModal 2014-11-12 11:26:23 +01:00
Gina Häußge 784688a9da Merge branch 'mrbeam-devel' into devel 2014-11-12 11:24:01 +01:00
Gina Häußge 71bb760ce5 Small optimization 2014-11-12 11:22:55 +01:00
Philipp Engel 98a46e8caa including plugins' main template (='name of the plugin'.jinja2, e.g. cura.jinja2) to index.jinja2 2014-11-11 14:22:30 -08:00
Gina Häußge dcdbd3652a Merge branch 'master' into devel 2014-11-10 09:21:23 +01:00
Gina Häußge c35b7a66b0 Encoding has to be specified before any other line of code 2014-11-10 09:21:05 +01:00
Gina Häußge 5ec02e2f18 And some more changelog entries (some day I might actually catch up...) 2014-11-08 15:29:49 +01:00
Gina Häußge 9709b97adf GCODE viewer now doesn't stumble over completely extrusionless GCODE files 2014-11-08 15:27:03 +01:00
Gina Häußge 3be039b1a9 Added a couple of changelog entries for previous commits 2014-11-08 15:23:57 +01:00
Gina Häußge 21bd664edf Merge branch 'devel' of github.com:foosel/OctoPrint into devel 2014-11-08 15:16:29 +01:00
Gina Häußge a31c422537 Merge branch 'imrahil-feature_qr_code' into devel 2014-11-08 15:16:15 +01:00
Gina Häußge e5299d96ad Added changelog entry for qr code 2014-11-08 15:15:49 +01:00
Gina Häußge 5675f32a19 QR Code generation uses jquery.qrcode and a custom knockout binding
This way it will also be possible to easily add another qrcode to the user api key later. Refused to work for now (value binding doesn't update), so commented out right now, but works in theory.
2014-11-08 15:14:38 +01:00
Gina Häußge c207578f14 Merge pull request #639 from mangtronix/iphone-autocaps
Disable automatic capitalization for username entry field (Safari)
2014-11-07 08:26:10 +01:00
Michael Ang 16801ad3e1 Disable autocapitalization for username
Makes it easier to login on iPhone (Mobile Safari)
2014-11-07 00:24:05 +01:00
Jarek Szczepanski 25cfed949d Added QR code with API key on Settings dialog 2014-11-05 12:24:51 +01:00
Gina Häußge eacfcab187 Merge branch 'master' into devel
Conflicts:
	CHANGELOG.md
2014-11-04 10:43:11 +01:00
Gina Häußge 9e014eba1f Added removal of pyc files (and their parent folders if they are empty after that) to the python setup.py clean command 2014-11-04 10:40:15 +01:00
Gina Häußge 9692b709aa Merge branch 'Wallacoloo-master' 2014-11-04 10:08:07 +01:00
Gina Häußge 5acb04c180 Fixed a couple of more missing branch fields and added Changelog entry 2014-11-04 10:07:46 +01:00
Gina Häußge ff96e2e4d6 Also interpret lines starting with "!!" as errors from the firmware
(see http://reprap.org/wiki/G-code#Replies_from_the_RepRap_machine_to_the_host_computer)
2014-11-03 21:40:21 +01:00
Pim Rutgers 2e96fa9e1e Request Settings data on opening modal
to counter different browser windows having different settings
2014-11-03 19:14:50 +01:00
Colin Wallace 87234bda05 Fix missing branch field in DEFAULT dict
Should fix an error raised on line 951 (SHORT_VERSION_PY % DEFAULT) during Octoprint setup when there's no version info. More info here: https://groups.google.com/forum/#!topic/deltabot/8udyUsJ1c9M
2014-11-03 05:50:09 +00:00
Gina Häußge ca6364e5d4 Correctly interpret Smoothieware temperature data for multiple extruders
Fixes #633
2014-10-31 14:08:52 +01:00
Gina Häußge 62667de4a8 Fix: Don't try to create a SessionUser for anonymous users 2014-10-30 12:22:58 +01:00
Gina Häußge f8955c0d1b Fix of file type detection 2014-10-29 12:17:26 +01:00
Gina Häußge 0aac7813e4 More work on slicing integration:
- be able to handle slicers which can't report progress
- distinguish between registered and configured slicers (e.g. to allow uploading of profiles via the settings before having saved the path to the executable)
2014-10-29 12:16:49 +01:00
Gina Häußge 44cc9e7db8 Cura Plugin: Filament diameter and hotend temperature where not correctly extracted from profile and supplied to CuraEngine, resulting in low print quality
(using the default of 2.85mm filament diameter doesn't work well for 1.75mm machines...)
2014-10-29 11:57:43 +01:00
Gina Häußge 644329c0b8 Preparing release of 1.1.1 2014-10-27 09:48:54 +01:00
Gina Häußge ff97fba0f0 Merge branch 'master' into devel
Conflicts:
	src/octoprint/server/api/__init__.py
2014-10-27 09:39:14 +01:00
Gina Häußge ce67e28f96 Generate the salt used for hashing user passwords individually for each server instance 2014-10-27 09:37:39 +01:00
Gina Häußge e149689249 Enable logging of tornado errors by default, to make sure octoprint.log will contain meaningful entries if something goes wrong in our tornado customization 2014-10-24 20:11:58 +02:00
Gina Häußge b79d5e670a Tornado's StaticFileHandler now supports content streaming, use that instead of our own implementation
Also allow for definition of access validation and serving as attachment though.

Hopefully also fixes #606, since that was possibly called by our own implementation of content streaming, which now has been removed completely.
2014-10-24 19:59:59 +02:00
Gina Häußge c23cb378cd Allow login of the same user from multiple browsers without side effects
So far when logging in from two different browsers, then logging out in one of them the user was logged out across all browsers. This should now be changed in so far as that each individual browser session is tracked and only that session is ended by a logout that belongs to the browser where the logout button was clicked.

Should fix #556
2014-10-24 13:05:07 +02:00
Gina Häußge a185685f0c Merge branch 'master' into devel
Conflicts:
	src/octoprint/server/__init__.py
	src/octoprint/settings.py
2014-10-23 16:21:39 +02:00
Gina Häußge b4699825d6 Generate the key used for session hashing individually for each server instance
(cherry picked from commit 118a4f7)
2014-10-23 15:38:43 +02:00
Gina Häußge 118a4f7097 Generate the key used for session hashing individually for each server instance 2014-10-23 15:33:32 +02:00
Gina Häußge 7acb0657a7 Made "Streaming done" notification green 2014-10-23 14:45:12 +02:00
Gina Häußge 021ce44673 Don't die if you're not able to log a print (e.g. for prints from SD) 2014-10-23 14:45:11 +02:00
Gina Häußge 9a7733c9a3 Make "Slicing done" notification green
Implements #558
2014-10-22 09:45:42 +02:00
Gina Häußge 7150f5b536 Properly reselect default slicer and profile in slicing dialog after sending a slicing request 2014-10-22 09:12:50 +02:00
Gina Häußge 753b9e8d7a Automatically refresh slicing profiles in slicing dialog when profiles are added or removed via the Cura plugin settings 2014-10-22 09:09:37 +02:00
Gina Häußge 6e62ecc8c1 Keep track of files that are currently being used (file being printed, source and destination for slicing) so that they can't be deleted
Also added logging to exception branches where the exception was formerly just swallowed.
2014-10-21 19:18:59 +02:00
Gina Häußge 0ab5369635 Added changelog entry for bugfix 2014-10-21 18:47:56 +02:00
Gina Häußge a274b769bd Merge pull request #625 from imrahil/gcode_analyzer_fix
Fixed gcode analyzing after file upload
2014-10-21 18:44:40 +02:00
Jarek Szczepanski 6e4d35777b Fixed gcode analyzing after file upload 2014-10-21 18:35:08 +02:00
Gina Häußge 776e6aa498 Fixed a typo breaking slicing altogether 2014-10-21 15:03:36 +02:00
Gina Häußge b7a21dd322 More error resilience in regards to defined printer parameters when converting the slicing profile for Cura 2014-10-21 14:56:59 +02:00
Gina Häußge 71d73c6562 Do not try to slice on local slicers when printing
Since slicing takes a lot of resources, that might lead to quality loss for the print job.
2014-10-21 14:14:00 +02:00
Gina Häußge 6732710d6f Added logging of CuraEngine output to Cura plugin
Should hopefully help debugging issues where the slicer appears to not be doing anything.
2014-10-21 12:08:16 +02:00
Gina Häußge 90618723d4 Parse slicing progress from Cura and provide it on sock.js socket
UI for now displays it in the "Slicing" progress bar text.
2014-10-20 18:58:04 +02:00
Gina Häußge 084ca956fb Cache metadata in an LRU cache instead of fetching it from disk everytime 2014-10-20 16:49:53 +02:00
Gina Häußge 44109f9d8f Automatically cancel running slicing jobs targeting the same output file if a new slicing request is received
This way there won't be two concurrent jobs trying to slice to the same file, which would practically render the cpu cycles from any slicing jobs than the final one wasted. Also adds a new event "SlicingCancelled" that will be sent in these cases.
2014-10-20 13:40:04 +02:00
Gina Häußge 606efd3da1 Pause button now changes icon when paused to indicate "Resume" state better, also added tooltips
Updated german translation accordingly, other translations will have to follow once the community translates the new strings.
2014-10-20 09:51:33 +02:00
Gina Häußge 2d76aa029a Updated contribution guidelines
We sadly still need to be more clear that tickets need to adhere to certain standards to be manageable...
2014-10-17 13:04:35 +02:00
Gina Häußge 1acbbbaf6c Merge branch 'master' into devel 2014-10-16 23:51:00 +02:00
Gina Häußge 8864884c67 Forgot changelog entry again 2014-10-16 23:50:38 +02:00
Gina Häußge a332b71463 Properly initialize settings dir
Since config.yaml gets now saved on server startup before settings basedir gets initialized by other means (e.g. first access of base folder for uploads), it was not created yet when the config.yaml was tried to be saved upon first start up, causing an error at server startup.

Closes #604
2014-10-16 23:49:26 +02:00
Gina Häußge 10d76ae7a4 Fix for deleting the file that is currently selected
Due to a missing switch to a refactored version of an internal data structure, that file stayed being selected but wasn't actually there anymore, leading to an error upon hitting Print.
2014-10-06 19:01:30 +02:00
Gina Häußge cd973adedf Improved slicing and file management
- File management is prepared to support folders (UI still lacking support)
- STL files are now first class citizens
  - can be managed via the file list (and filtered from it)
  - can be sliced on demand
- Slicing now happens via plugins
- Added Cura plugin
  - uses CuraEngine directly instead of full Cura installation
  - Cura profile importer for importing profiles from regular Cura installs via settings dialog
  - TODO: UI for editing profiles
- API for slicing and slicing profile management
2014-10-06 17:34:07 +02:00
Gina Häußge af94b770f9 Merge branch 'master' into devel 2014-10-01 15:57:04 +02:00
Gina Häußge 62a51bb061 Added changelog entry 2014-10-01 15:55:57 +02:00
Gina Häußge 01ab61b8b1 Enable event subscriptions by default 2014-10-01 15:54:42 +02:00
Gina Häußge c55d8c0bdf Merge remote-tracking branch 'origin/devel' into devel 2014-10-01 14:36:27 +02:00
Gina Häußge 7336ed6eff Merge branch 'master' into devel
Conflicts:
	src/octoprint/settings.py
2014-10-01 14:36:02 +02:00
Gina Häußge 60ca95e9b2 Started documenting plugin types and their API 2014-09-30 23:20:47 +02:00
Gina Häußge 89b43a42c4 Merge pull request #595 from koenkooi/scarequotes
Don't use scare quotes when displaying the username.
2014-09-30 15:51:33 +02:00
Koen Kooi 197be925b8 Don't use scare quotes when displaying the username.
See http://en.wikipedia.org/wiki/Scare_quotes for details.

Signed-off-by: Koen Kooi <koen@dominion.thruhere.net>
2014-09-30 15:28:38 +02:00
Gina Häußge d49cd209e1 Enable API by default and automatically generate API key on first server startup 2014-09-29 22:20:18 +02:00
Gina Häußge d60ab8cd9e Update CHANGELOG.md 2014-09-24 22:55:23 +02:00
Gina Häußge 7840ff0d7c Updated changelog 2014-09-23 19:11:35 +02:00
Gina Häußge a7144e57e1 Merge branch 'Booli-confirmCustomCommand' into devel 2014-09-23 18:58:46 +02:00
Pim Rutgers 50eac58493 Confirm custom command REQUEST #532
Syntax (and code) similar to System Command confirm. First commit,
please be gentle.
2014-09-23 18:29:37 +02:00
Pim Rutgers 4ef58b56e6 Ignore code kit 2014-09-23 18:16:54 +02:00
Gina Häußge c1f0c76d17 Properly handle non-ASCII instance names 2014-09-21 18:14:01 +02:00
Gina Häußge 079116fdf8 Fix: SlicingDone has a different event payload than UpdatedFiles, so we need a different handler for the updates to work 2014-09-19 23:58:41 +02:00
Gina Häußge 45e6385963 Fix: gcodeFilesViewModel doesn't exist as invididual variable anymore, iterate over registered view models instead 2014-09-19 23:11:20 +02:00
Gina Häußge 3ca0458d65 Fix: Use event strings, not names for all_events
Temporarily broke event registration by frontend, this should fix it again.
2014-09-19 16:11:44 +02:00
Gina Häußge d5edec2cd0 Merge branch 'master' into devel
Conflicts:
	src/octoprint/server/__init__.py
2014-09-18 09:38:20 +02:00
Gina Häußge ce9c9bea6a Also allow downloading .g files via Tornado
Regex so far only matched .gcode and .gco, files ending just in .g are expected for upload as well though, so this needed to be adjusted
2014-09-18 09:36:33 +02:00
Gina Häußge 604c2a0bdd Some small bugfixes in the plugin handling code and a changelog entry 2014-09-14 14:41:18 +02:00
Gina Häußge 1c19bb4dfc Merge branch 'master' into devel
Conflicts:
	CHANGELOG.md
2014-09-13 22:01:12 +02:00
Gina Häußge 858d87a732 Forgot entry in changelog 2014-09-13 21:58:41 +02:00
Gina Häußge ea28900913 Properly unset job data when instructed so by callers
Closes #580
2014-09-13 21:49:26 +02:00
Gina Häußge 192e606fea Don't hiccup on templates provided by plugins we can't resolve 2014-09-12 20:15:28 +02:00
Gina Häußge 8e4152e567 Merge pull request #577 from dattas/feature/comms_code_hooks
Merged PR #577 - Allow plugins that hook into comms

Establishes basics for alternative version to implement #324
2014-09-12 19:38:21 +02:00
Dattas Moonchaser 9e9da5355c Initial comm protocol gcode hooks 2014-09-12 10:23:08 -06:00
Gina Häußge 26e9a17c6b Started working on the documentation of the plugin system 2014-09-12 14:26:29 +02:00
Gina Häußge fa43600cd9 Always use absolute paths as root for static response handler in tornado 2014-09-12 12:40:11 +02:00
Gina Häußge 3aca55205e Fixed a bug that crept in during adding i18n support and made gcode viewer slides stop working 2014-09-12 12:39:33 +02:00
Gina Häußge 3a0aac3c36 Fixed issue that broke the offline dialog
Javascript is not python...
2014-09-12 12:21:25 +02:00
Gina Häußge fe34bdc656 Fixed a bug that broke the first-run-dialog 2014-09-12 12:18:15 +02:00
Gina Häußge e69c1e8e93 Added some comments to discovery plugin 2014-09-12 11:22:06 +02:00
Gina Häußge 1c0721f179 Introduced __plugin_init__ method called after all plugins have been discovered
Plugins may be able to use this method for final setups before the implementations and hooks are evaluated, e.g. for adjusting their offered functionality based on what other plugins are available.
2014-09-12 11:21:39 +02:00
Gina Häußge 6f37968670 Moved netconnectd plugin to it's own separate project
Now resides at https://github.com/OctoPrint/OctoPrint-Netconnectd
2014-09-11 18:53:45 +02:00
Gina Häußge d1c34a9c88 Try to reconnect to backend when switching from ap to wifi
netconnectd now regularly pings hostname it got from backend (defaults to <systemname>.local) while switching to wifi from ap mode and reloads page to that if host comes up.

This requires the browser the client is currently running in to be able to resolve local domains as broadcasted via avahi. Windows systems will need to install the Bonjour for Windows client for this to work.
2014-09-11 15:40:04 +02:00
Gina Häußge 65263a8b74 Made what is registered for discovery more configurable
- Additional zeroconf services may now be added via config
- Exposed zeroconf_register method as helper for plugins
- Vendor specifics may be added to service registrations via config
2014-09-11 12:19:10 +02:00
Gina Häußge 5cd6ab9335 More error resilience during plugin loading 2014-09-11 12:17:45 +02:00
Gina Häußge 56b1705df4 Added plugin helpers, added ssdp/zeroconf browsing in discovery plugin as first helpers 2014-09-10 22:28:03 +02:00
Gina Häußge 08e4c05129 Plugins can now also be retrieved via entry_points, also added EventPlugin and afterStartup handler in StartupPlugin 2014-09-10 15:46:14 +02:00
Gina Häußge b5b0ea5980 Armed netconnectd check for Linux 2014-09-10 15:42:38 +02:00
Gina Häußge 803e17f3a3 More work on netconnectd plugin frontend
* now also correctly displays current state
* detects current wifi network
* spinner while configuring wifi
* quality display only if quality available
2014-09-10 10:26:28 +02:00
Gina Häußge 75017d7ac6 Integrated netconnectd plugin with netconnectd service 2014-09-08 18:05:25 +02:00
Gina Häußge 80486d644d Better logging for NOTIFY messages 2014-09-07 17:32:02 +02:00
Gina Häußge 1bdc167f7a Also install plugins from setup.py and don't log notify as info level 2014-09-07 17:28:50 +02:00
Gina Häußge 3f2fdb0b14 Added shutdown trigger and UUID persistence 2014-09-07 17:25:20 +02:00
Gina Häußge ac186f89f1 discovery now has automatic location url building based on querying client 2014-09-07 01:57:59 +02:00
Gina Häußge fdccfd166f Also forgot to add knockout mapping plugin to git 2014-09-07 01:39:13 +02:00
Gina Häußge 272a71f3d5 Fixed a typo in an URL 2014-09-07 01:33:55 +02:00
Gina Häußge 3621879d38 Forgot to commit template files 2014-09-07 01:29:48 +02:00
Gina Häußge 4661990cfe Fixed error in usage of netifaces 2014-09-07 01:16:39 +02:00
Gina Häußge 7db63b10e8 Use netifaces for ipaddress iteration 2014-09-07 01:11:11 +02:00
Gina Häußge 428ea89f62 discovery plugin: let's try upnp 2014-09-07 00:53:54 +02:00
Gina Häußge 60e0ed911e discovery plugin: removed _workstation._tcp registration, added more parameters to http and octoprint txt records 2014-09-05 18:47:46 +02:00
Gina Häußge e1366ef90f First experiments with a plugin system, service discovery and connectivity ensurance 2014-09-05 17:11:11 +02:00
Gina Häußge 85c170712a Some more entries into the Changelog, trying to get up to date... 2014-09-04 08:30:36 +02:00
Gina Häußge 33bf487a1c i18n: Added dutch and norwegian translations 2014-09-03 18:59:50 +02:00
Gina Häußge 227810db75 Merge branch 'master' into devel
Conflicts:
	src/octoprint/events.py
	src/octoprint/server/__init__.py
	src/octoprint/settings.py
	src/octoprint/templates/index.jinja2
2014-09-03 18:55:59 +02:00
Gina Häußge 6171c76199 Renamed RELEASE-NOTES.md to CHANGELOG.md, added note regarding new version format 2014-09-03 11:30:00 +02:00
Gina Häußge 45c1958d83 Versioneer now also returns and persists the branch from which OctoPrint was installed
Changed version output accordingly to now display "{version} ({branch} branch)" if branch information is available (which should be the case if installation was performed from git).
(cherry picked from commit a48b5de)
2014-09-03 10:56:39 +02:00
Gina Häußge e51d9439c5 Modified versioneer to allow specification of manual versions based on branches
You can now define a lookup file explicitely mapping virtual version tags to branches via regular expressions and a reference commit from which the commit distance will be calculated.

Format of the file is

  <branch-regex> <tag> <reference commit>

The file is processed from top to bottom, the first matching line wins. If <tag> or <reference commit> are left out, the lookup table does not apply to the matched branches and the regular versioneer resolution (via git describe) takes place.

Current configuration makes "master", "staging" and any branch starting with "fix/" make use the default behaviour, all other branches (so basically all development branches) are defined as "1.2.0-dev"
(cherry picked from commit 212f40c)
2014-09-03 10:53:54 +02:00
Gina Häußge a48b5deb29 Versioneer now also returns and persists the branch from which OctoPrint was installed
Changed version output accordingly to now display "{version} ({branch} branch)" if branch information is available (which should be the case if installation was performed from git).
2014-09-02 12:06:02 +02:00
Gina Häußge 212f40cd1a Modified versioneer to allow specification of manual versions based on branches
You can now define a lookup file explicitely mapping virtual version tags to branches via regular expressions and a reference commit from which the commit distance will be calculated.

Format of the file is

  <branch-regex> <tag> <reference commit>

The file is processed from top to bottom, the first matching line wins. If <tag> or <reference commit> are left out, the lookup table does not apply to the matched branches and the regular versioneer resolution (via git describe) takes place.

Current configuration makes "master", "staging" and any branch starting with "fix/" make use the default behaviour, all other branches (so basically all development branches) are defined as "1.2.0-dev"
2014-09-02 11:35:42 +02:00
Gina Häußge 18952c57ff Added automatic migration of old event subscription format to the new one
(cherry picked from commit e7088ef)
2014-08-31 22:54:16 +02:00
Gina Häußge 4296b49570 Some first entries into the release notes list for the next release (WIP) 2014-08-31 22:52:18 +02:00
111 changed files with 156719 additions and 2560 deletions

No files matched your search

+2 -1
View File
@@ -4,7 +4,6 @@
*.pyc
*.zip
*.exe
*.gcode
*.swp
darwin-Cura-*
win32-Cura-*
@@ -21,3 +20,5 @@ dist
pypy
OctoPrint.egg-info
*.orig
*.codekit
+18
View File
@@ -0,0 +1,18 @@
# Configuration file for the versioneer lookup, manually mapping tags based on branches
#
# Format is
#
# <branch-regex> <tag> <reference commit>
#
# The file is processed from top to bottom, the first matching line wins. If <tag> or <reference commit> are left out,
# the lookup table does not apply to the matched branches
# master and staging shall not use the lookup table
master
staging
# fix/ branches are fixes for master, so we don't handle those either
fix/.*
# every other branch is a development branch and thus gets resolved to 1.2.0-dev for now
.* 1.2.0-dev 50cf776e70b9
+97 -5
View File
@@ -1,6 +1,96 @@
# OctoPrint Release Notes
# OctoPrint Changelog
## 1.1.0
## 1.2.0 (Unreleased)
### New Features
* Added internationalization of UI. Translations of OctoPrint are being crowd sourced via [Transifex](https://www.transifex.com/projects/p/octoprint/).
The following translations are already available with more in the works:
- Dutch (nl)
- German (de)
- French (fr)
- Hebrew (he)
- Norwegian (no)
- Romanian (ro)
* New file list: Pagination is gone, no more (mobile incompatible) pop overs, instead scrollable and with instant
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
### Improvements
* Logging is now configurable via config file
* Added last print time to additional GCODE file information
* Better error handling for capture issues during timelapse creation & more robust handling of missing images during
timelapse creation
* 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
* 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).
* 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)).
* 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)
* 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 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"
### 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
* 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
* 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
## 1.1.2 (Unreleased)
### Bug Fixes
* [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated
by versioneer
## 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
## 1.1.0 (2014-09-03)
### New Features
@@ -28,7 +118,9 @@
* Support for circular beds in the GCODE viewer ([#407](https://github.com/foosel/OctoPrint/pull/407))
* The dimensions of the print bed can now be configured via the Settings ([#396](https://github.com/foosel/OctoPrint/pull/396))
* Target temperature reporting format of Repetier Firmware is now supported as well ([360](https://github.com/foosel/OctoPrint/issues/360))
* Version tracking now based on git tagging and [versioneer](https://github.com/warner/python-versioneer/).
* Version tracking now based on git tagging and [versioneer](https://github.com/warner/python-versioneer/). Version number,
git commit and branch get reported in the format `<version tag>-<commits since then>-g<commit hash> (<branch> branch)`,
e.g. `1.2.0-dev-172-ga48b5de (devel branch)`.
* Made "Center viewport on model" and "Zoom in on model" in the GCODE viewer automatically deselect and de-apply if
viewport gets manipulated by the user ([#398](https://github.com/foosel/OctoPrint/issues/398))
* GCODE viewer now interprets inverted axes for printer control and mirrors print bed accordingly ([#431](https://github.com/foosel/OctoPrint/issues/431))
@@ -68,6 +160,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.
+9 -4
View File
@@ -1,11 +1,16 @@
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!
- 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 treated as if only describing the first purpose, the others will be ignored!
- 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.
- 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), **add [Support] to your issue's title!**. Note that for problems like these, the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) will probably get you help faster!
- If you have a general **question**, **add [Question] to your issue's title!**. Note that for problems like these, the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) will probably get you help faster!
- If you have another reason for creating a ticket that doesn't fit any of the above categories, think hard if it might not be something better suited for the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741). If you are sure it needs to be reported here, **add [Misc] to your issue's title!**
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
-------------
+15 -12
View File
@@ -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.
+170
View File
@@ -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-----
+9 -1
View File
@@ -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
+88 -11
View File
@@ -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:
+2 -2
View File
@@ -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.
+3
View File
@@ -9,10 +9,13 @@ API Documentation
general.rst
version.rst
apps.rst
fileops.rst
connection.rst
printer.rst
printerprofiles.rst
job.rst
logs.rst
slicing.rst
push.rst
datamodel.rst
+1 -1
View File
@@ -783,7 +783,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:
+190
View File
@@ -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-slicing-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-slicing-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] ]``
+41
View File
@@ -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
+336
View File
@@ -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.
+7 -6
View File
@@ -12,17 +12,18 @@
# 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/'))
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.
@@ -30,7 +31,7 @@ year_current = date.today().year
# 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 = ['sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain']
todo_include_todos = True
# Add any paths that contain templates here, relative to this directory.
+24 -1
View File
@@ -132,7 +132,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 +328,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 +339,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 +356,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.
+1
View File
@@ -18,4 +18,5 @@ Contents
api/index.rst
events/index.rst
plugins/index.rst
+19
View File
@@ -0,0 +1,19 @@
.. _sec-plugins-developing:
******************
Developing Plugins
******************
.. todo::
A section on how to develop plugins yourself, including a tutorial creating an exemplary plugin as well as
a documentation of the plugin API, will be added in the near future.
.. _sec-plugins-developing-types:
Available plugin types
======================
.. automodule:: octoprint.plugin.types
:members:
:undoc-members:
+60
View File
@@ -0,0 +1,60 @@
.. _sec-plugins:
#####################
Plugins Documentation
#####################
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, 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:
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>`_.
Developing Plugins
==================
Please see the following sub topics for information on how to develop your own OctoPrint plugins.
.. toctree::
:maxdepth: 2
developing.rst
+3
View File
@@ -10,3 +10,6 @@ pyserial
netaddr
watchdog
sarge
netifaces
pylru
rsa
+45 -1
View File
@@ -7,6 +7,7 @@ versioneer.versionfile_source = 'src/octoprint/_version.py'
versioneer.versionfile_build = 'octoprint/_version.py'
versioneer.tag_prefix = ''
versioneer.parentdir_prefix = ''
versioneer.lookupfile = '.versioneer-lookup'
from setuptools import setup, find_packages, Command
import os
@@ -32,6 +33,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 = []
@@ -44,14 +65,37 @@ 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
)
class NewTranslation(Command):
description = "create a new translation"
@@ -219,7 +263,7 @@ def params():
packages = find_packages(where="src")
package_dir = {"octoprint": "src/octoprint"}
package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates'])}
package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates', 'plugins'])}
include_package_data = True
zip_safe = False
+101 -11
View File
@@ -54,6 +54,18 @@ import sys
import re
import os.path
def get_gits(root, verbose=False):
if not os.path.exists(os.path.join(root, ".git")):
if verbose:
print("no .git in %s" % root)
return None
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
return GITS
def get_expanded_variables(versionfile_abs):
# the code embedded in _version.py can just fetch the value of these
# variables. When used from setup.py, we don't want to import
@@ -114,20 +126,60 @@ def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
return { "version": variables["full"].strip(),
"full": variables["full"].strip() }
def versions_from_lookup(lookup, root, verbose=False):
GITS = get_gits(root, verbose=verbose)
if GITS is None:
return {}
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
if stdout is None:
return {}
current_branch = stdout.strip()
for matcher, tag, ref_commit in lookup:
if matcher.match(current_branch):
if tag is None or ref_commit is None:
return {}
stdout = run_command(GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root)
if stdout is None:
return {}
num_commits = stdout.strip()
stdout =run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root)
if stdout is None:
return {}
short_hash = stdout.strip()
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root)
if stdout is None:
return {}
dirty = stdout.strip().endswith("-dirty")
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if stdout is None:
return {}
full = stdout.strip()
version = "%s-%s-g%s" % (tag, num_commits, short_hash)
if dirty:
version += "-dirty"
full += "-dirty"
return {"version": version, "full": full, "branch": current_branch}
return {}
def versions_from_vcs(tag_prefix, root, verbose=False):
# this runs 'git' from the root of the source tree. This only gets called
# if the git-archive 'subst' variables were *not* expanded, and
# _version.py hasn't already been rewritten with a short version string,
# meaning we're inside a checked out source tree.
if not os.path.exists(os.path.join(root, ".git")):
if verbose:
print("no .git in %s" % root)
GITS = get_gits(root, verbose=verbose)
if GITS is None:
return {}
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"],
cwd=root)
if stdout is None:
@@ -143,7 +195,14 @@ def versions_from_vcs(tag_prefix, root, verbose=False):
full = stdout.strip()
if tag.endswith("-dirty"):
full += "-dirty"
return {"version": tag, "full": full}
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
if stdout is None:
branch = None
else:
branch = stdout.strip()
return {"version": tag, "full": full, "branch": branch}
def versions_from_parentdir(parentdir_prefix, root, verbose=False):
@@ -155,13 +214,42 @@ 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 = "octoprint-"
parentdir_prefix = ""
versionfile_source = "src/octoprint/_version.py"
lookupfile = ".versioneer-lookup"
def get_versions(default={"version": "unknown", "full": ""}, verbose=False):
def parse_lookup_file(root, lookup_path=None):
if not lookup_path:
lookup_path = lookupfile
if not lookup_path:
return []
path = os.path.join(root, lookup_path)
if not os.path.exists(path):
return []
import re
lookup = []
with open(os.path.join(root, lookup_path), "r") as f:
for line in f:
if '#' in line:
line = line[:line.rindex('#')]
line = line.strip()
try:
split_line = line.split()
if len(split_line) == 3:
pattern, tag, ref_commit = split_line
lookup.append([re.compile(pattern), tag, ref_commit])
elif len(split_line) >= 1:
lookup.append([re.compile(split_line[0]), None, None])
except:
break
return lookup
def get_versions(default={"version": "unknown", "full": "", "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
@@ -182,7 +270,9 @@ def get_versions(default={"version": "unknown", "full": ""}, verbose=False):
except NameError:
return default
return (versions_from_vcs(tag_prefix, root, verbose)
lookup = parse_lookup_file(root, lookup_path=lookup_path)
return (versions_from_lookup(lookup, root, verbose)
or versions_from_vcs(tag_prefix, root, verbose)
or versions_from_parentdir(parentdir_prefix, root, verbose)
or default)
+34 -16
View File
@@ -1,21 +1,28 @@
# coding=utf-8
from __future__ import (print_function, absolute_import)
__author__ = "Lars Norpchen"
__author__ = "Gina Häußge <osd@foosel.net>"
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
__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 datetime
import logging
import subprocess
import Queue
import threading
import collections
from octoprint.settings import settings
import octoprint.plugin
# singleton
_instance = None
def all_events():
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")]
class Events(object):
# application startup
STARTUP = "Startup"
@@ -72,6 +79,15 @@ class Events(object):
SLICING_STARTED = "SlicingStarted"
SLICING_DONE = "SlicingDone"
SLICING_FAILED = "SlicingFailed"
SLICING_CANCELLED = "SlicingCancelled"
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
# Printer Profiles
PRINTER_PROFILE_SELECTED = "PrinterProfileSelected"
PRINTER_PROFILE_DESELECTED = "PrinterProfileDeselected"
PRINTER_PROFILE_MODIFIED = "PrinterProfileModified"
def eventManager():
@@ -87,7 +103,7 @@ class EventManager(object):
"""
def __init__(self):
self._registeredListeners = {}
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._queue = Queue.PriorityQueue()
@@ -99,9 +115,7 @@ class EventManager(object):
while True:
(event, payload) = self._queue.get(True)
eventListeners = self._registeredListeners.get(event, None)
if eventListeners is None:
return
eventListeners = self._registeredListeners[event]
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
for listener in eventListeners:
@@ -111,6 +125,10 @@ class EventManager(object):
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])
def fire(self, event, payload=None):
"""
Fire an event to anyone subscribed to it
@@ -122,18 +140,22 @@ class EventManager(object):
payload being a payload object specific to the event.
"""
if not event in self._registeredListeners.keys():
return
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
"""
if not event in self._registeredListeners.keys():
self._registeredListeners[event] = []
if callback in self._registeredListeners[event]:
# callback is already subscribed to the event
return
@@ -146,10 +168,6 @@ class EventManager(object):
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
"""
if not event in self._registeredListeners:
# no callback registered for callback, just return
return
if not callback in self._registeredListeners[event]:
# callback not subscribed to event, just return
return
@@ -293,7 +311,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)
+355 -1
View File
@@ -1,3 +1,357 @@
# 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
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
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.get_absolute_path(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):
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)
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:
return
else:
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")
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):
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).get_absolute_path(file_path)
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)
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):
try:
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success))
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 get_absolute_path(self, destination, path):
return self._storage(destination).get_absolute_path(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 rel_path(self, destination, path):
return self._storage(destination).rel_path(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 _on_analysis_finished(self, entry, result):
if not entry.location in self._storage_managers:
return
storage_manager = self._storage_managers[entry.location]
storage_manager.set_additional_metadata(entry.path, "analysis", result)
+166
View File
@@ -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()
+828
View File
@@ -0,0 +1,828 @@
# 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 os
import pylru
import octoprint.filemanager
class StorageInterface(object):
@property
def analysis_backlog(self):
# empty generator pattern, yield is intentionally unreachable
return
yield
def file_exists(self, path):
raise NotImplementedError()
def list_files(self, path=None, filter=None, recursive=True):
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True):
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
raise NotImplementedError()
def remove_file(self, path):
raise NotImplementedError()
def get_metadata(self, path):
raise NotImplementedError()
def add_link(self, path, rel, data):
raise NotImplementedError()
def remove_link(self, path, rel, data):
raise NotImplementedError()
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
raise NotImplementedError()
def remove_additional_metadata(self, path, key):
raise NotImplementedError()
def sanitize(self, path):
raise NotImplementedError()
def sanitize_path(self, path):
raise NotImplementedError()
def sanitize_name(self, name):
raise NotImplementedError()
def split_path(self, path):
raise NotImplementedError()
def join_path(self, *path):
raise NotImplementedError()
def rel_path(self, path):
raise NotImplementedError()
def get_absolute_path(self, path):
raise NotImplementedError()
class LocalFileStorage(StorageInterface):
def __init__(self, basefolder, create=False):
self._logger = logging.getLogger(__name__)
self.basefolder = os.path.realpath(os.path.abspath(basefolder))
if not os.path.exists(self.basefolder) and create:
os.makedirs(self.basefolder)
if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):
raise RuntimeError("{basefolder} is not a valid directory".format(**locals()))
import threading
self._metadata_lock = threading.Lock()
self._metadata_cache = pylru.lrucache(10)
@property
def analysis_backlog(self):
for entry in self._analysis_backlog_generator():
yield entry
def _analysis_backlog_generator(self, path=None):
if path is None:
path = self.basefolder
metadata = self._get_metadata(path)
if not metadata:
metadata = dict()
for entry in os.listdir(path):
if entry.startswith(".") or not octoprint.filemanager.valid_file_type(entry):
continue
absolute_path = os.path.join(path, entry)
if os.path.isfile(absolute_path):
if not entry in metadata or not isinstance(metadata[entry], dict) or not "analysis" in metadata[entry]:
printer_profile_rels = self.get_link(absolute_path, "printerprofile")
if printer_profile_rels:
printer_profile_id = printer_profile_rels[0]["id"]
else:
printer_profile_id = None
yield entry, absolute_path, printer_profile_id
elif os.path.isdir(absolute_path):
for sub_entry in self._analysis_backlog_generator(absolute_path):
yield self.join_path(entry, sub_entry[0]), sub_entry[1], sub_entry[2]
def file_exists(self, path):
path, name = self.sanitize(path)
file_path = os.path.join(path, name)
return os.path.exists(file_path) and os.path.isfile(file_path)
def list_files(self, path=None, filter=None, recursive=True):
"""
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
subfolders.
An optional filter function can be supplied which will be called with a file name and file data and which has
to return True if the file is to be included in the result or False if not.
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
{
"some_folder": {
"type": "folder",
"children": {
"some_sub_folder": {
"type": "folder",
"children": { ... }
},
"some_file.gcode": {
"type": "machinecode",
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"type": "machinecode",
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"type": "model",
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
:param recursive: will also step into sub folders for building the complete list if set to True
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
if path:
path = self.sanitize_path(path)
else:
path = self.basefolder
return self._list_folder(path, filter=filter, recursive=recursive)
def add_folder(self, path, ignore_existing=True):
"""
Adds a folder as ``path``. The ``path`` will be sanitized.
:param path: the path of the new folder
:param ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:return: the sanitized name of the new folder to be used for future references to the folder
"""
path, name = self.sanitize(path)
folder_path = os.path.join(path, name)
if os.path.exists(folder_path):
if not ignore_existing:
raise RuntimeError("{sanitized_foldername} does already exist in {virtual_path}".format(**locals()))
else:
os.mkdir(folder_path)
return self.rel_path((path, name))
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``.
:param path: the path of the folder to remove
:param recursive: if set to True, contained folders and files will also be removed, otherwise and error will
be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed
"""
path, name = self.sanitize(path)
folder_path = os.path.join(path, name)
if not os.path.exists(folder_path):
return
contents = os.listdir(folder_path)
if ".metadata.yaml" in contents:
contents.remove(".metadata.yaml")
if contents and not recursive:
raise RuntimeError("{sanitized_foldername} in {virtual_path} is not empty".format(**locals()))
import shutil
shutil.rmtree(folder_path)
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
"""
Adds the file ``file_object`` as ``path``
:param path: the file's new path, will be sanitized
:param file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param printer_profile: the printer profile associated with this file (if any)
:param links: any links to add with the file
:param allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:return: the sanitized name of the file to be used for future references to it
"""
path, name = self.sanitize(path)
if not octoprint.filemanager.valid_file_type(name):
raise RuntimeError("{name} is an unrecognized file type".format(**locals()))
metadata = self._get_metadata(path)
if not metadata:
metadata = dict()
file_path = os.path.join(path, name)
if os.path.exists(file_path) and not os.path.isfile(file_path):
raise RuntimeError("{name} does already exist in {path} and is not a file".format(**locals()))
if os.path.exists(file_path) and not allow_overwrite:
raise RuntimeError("{name} does already exist in {path} and overwriting is prohibited".format(**locals()))
# make sure folders exist
if not os.path.exists(path):
os.makedirs(path)
# save the file
file_object.save(file_path)
# save the file's hash to the metadata of the folder
file_hash = self._create_hash(file_path)
if not name in metadata or not "hash" in metadata[name] or metadata[name]["hash"] != file_hash:
# make sure to create a new metadata entry if we've never seen that file with that content before
file_metadata = dict(
hash=file_hash
)
metadata[name] = file_metadata
self._save_metadata(path, metadata)
# process any links that were also provided for adding to the file
if not links:
links = []
if printer_profile is not None:
links.append(("printerprofile", dict(id=printer_profile["id"], name=printer_profile["name"])))
self._add_links(name, path, links)
return self.rel_path((path, name))
def remove_file(self, path):
"""
Removes the file at ``path``. Will also take care of deleting the corresponding entries
in the metadata and deleting all links pointing to the file.
:param path: path of the file to remove
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
file_path = os.path.join(path, name)
if not os.path.exists(file_path):
return
if not os.path.isfile(file_path):
raise RuntimeError("{name} in {path} is not a file".format(**locals()))
try:
os.remove(file_path)
except Exception as e:
raise RuntimeError("Could not delete {name} in {path}".format(**locals()), e)
if name in metadata:
if "hash" in metadata[name]:
hash = metadata[name]["hash"]
for m in metadata.values():
if not "links" in m:
continue
for link in m["links"]:
if "rel" in link and "hash" in link and (link["rel"] == "model" or link["rel"] == "machinecode") and link["hash"] == hash:
m["links"].remove(link)
del metadata[name]
self._save_metadata(path, metadata)
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
if name in metadata:
return metadata[name]
else:
return None
def get_link(self, path, rel):
path, name = self.sanitize(path)
return self._get_links(name, path, rel)
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
refering to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` refering to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
path, name = self.sanitize(path)
self._add_links(name, path, [(rel, data)])
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
path, name = self.sanitize(path)
self._remove_links(name, path, [(rel, data)])
def add_history(self, path, data):
path, name = self.sanitize(path)
self._add_history(name, path, data)
def update_history(self, path, index, data):
path, name = self.sanitize(path)
self._update_history(name, path, index, data)
def remove_history(self, path, index):
path, name = self.sanitize(path)
self._update_history(name, path, index)
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
metadata_dirty = False
if not name in metadata:
return
if not key in metadata[name] or overwrite:
metadata[name][key] = data
metadata_dirty = True
elif key in metadata[name] and isinstance(metadata[name][key], dict) and isinstance(data, dict) and merge:
current_data = metadata[name][key]
import octoprint.util
new_data = octoprint.util.dict_merge(current_data, data)
metadata[name][key] = new_data
metadata_dirty = True
elif key in metadata[name] and overwrite:
metadata[name][key] = data
metadata_dirty = True
if metadata_dirty:
self._save_metadata(path, metadata)
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
if not name in metadata:
return
if not key in metadata[name]:
return
del metadata[name][key]
self._save_metadata(path, metadata)
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
split = path.split("/")
if len(split) == 1:
return "", split[0]
else:
return self.join_path(*split[:-1]), split[-1]
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
return "/".join(path)
def get_absolute_path(self, path):
"""
Retrieves the absolute path on disk for ``path``
:param path: the virtual path for which to retrieve the absolute path on disk
:return: the absolute path on disk to ``path``
"""
path, name = self.sanitize(path)
return os.path.join(path, name)
##~~ internals
def _add_history(self, name, path, data):
metadata = self._get_metadata(path)
if not name in metadata:
metadata[name] = dict()
if not "hash" in metadata[name]:
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
if not "history" in metadata[name]:
metadata[name]["history"] = []
metadata[name]["history"].append(data)
self._save_metadata(path, metadata)
def _update_history(self, name, path, index, data):
metadata = self._get_metadata(path)
if not name in metadata or not "history" in metadata[name]:
return
try:
metadata[name]["history"][index] = data
self._save_metadata(path, metadata)
except IndexError:
pass
def _delete_history(self, name, path, index):
metadata = self._get_metadata(path)
if not name in metadata or not "history" in metadata[name]:
return
try:
del metadata[name]["history"][index]
self._save_metadata(path, metadata)
except IndexError:
pass
def _get_links(self, name, path, searched_rel):
metadata = self._get_metadata(path)
result = []
if not name in metadata:
return result
if not "links" in metadata[name]:
return result
for data in metadata[name]["links"]:
if not "rel" in data or not data["rel"] == searched_rel:
continue
result.append(data)
return result
def _add_links(self, name, path, links):
file_type = octoprint.filemanager.get_file_type(name)
if file_type:
file_type = file_type[0]
metadata = self._get_metadata(path)
metadata_dirty = False
if not name in metadata:
metadata[name] = dict()
if not "hash" in metadata[name]:
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
if not "links" in metadata[name]:
metadata[name]["links"] = []
for rel, data in links:
if (rel == "model" or rel == "machinecode") and "name" in data:
if file_type == "model" and rel == "model":
# adding a model link to a model doesn't make sense
return
elif file_type == "machinecode" and rel == "machinecode":
# adding a machinecode link to a machinecode doesn't make sense
return
ref_path = os.path.join(path, data["name"])
if not os.path.exists(ref_path):
# file doesn't exist, we won't create the link
continue
# fetch hash of target file
if data["name"] in metadata and "hash" in metadata[data["name"]]:
hash = metadata[data["name"]]["hash"]
else:
hash = self._create_hash(ref_path)
if not data["name"] in metadata:
metadata[data["name"]] = dict(
hash=hash,
links=[]
)
else:
metadata[data["name"]]["hash"] = hash
if "hash" in data and not data["hash"] == hash:
# file doesn't have the correct hash, we won't create the link
continue
if not "links" in metadata[data["name"]]:
metadata[data["name"]]["links"] = []
# add reverse link to link target file
metadata[data["name"]]["links"].append(
dict(rel="machinecode" if rel == "model" else "model", name=name, hash=metadata[name]["hash"])
)
metadata_dirty = True
link_dict = dict(
rel=rel,
name=data["name"],
hash=hash
)
elif rel == "web" and "href" in data:
link_dict = dict(
rel=rel,
href=data["href"]
)
if "retrieved" in data:
link_dict["retrieved"] = data["retrieved"]
else:
continue
if link_dict:
metadata[name]["links"].append(link_dict)
metadata_dirty = True
if metadata_dirty:
self._save_metadata(path, metadata)
def _remove_links(self, name, path, links):
metadata = self._get_metadata(path)
metadata_dirty = False
if not name in metadata or not "hash" in metadata[name]:
hash = self._create_hash(os.path.join(path, name))
else:
hash = metadata[name]["hash"]
for rel, data in links:
if (rel == "model" or rel == "machinecode") and "name" in data:
if data["name"] in metadata and "links" in metadata[data["name"]]:
ref_rel = "model" if rel == "machinecode" else "machinecode"
for link in metadata[data["name"]]["links"]:
if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash:
metadata[data["name"]]["links"].remove(link)
metadata_dirty = True
if "links" in metadata[name]:
for link in metadata[name]["links"]:
if not link["rel"] == rel:
continue
matches = True
for k, v in data.items():
if not k in link or not link[k] == v:
matches = False
break
if not matches:
continue
metadata[name]["links"].remove(link)
metadata_dirty = True
if metadata_dirty:
self._save_metadata(path, metadata)
def _list_folder(self, path, filter=None, recursive=True):
metadata = self._get_metadata(path)
if not metadata:
metadata = dict()
metadata_dirty = False
result = dict()
for entry in os.listdir(path):
if entry.startswith("."):
# no hidden files and folders
continue
entry_path = os.path.join(path, entry)
# file handling
if os.path.isfile(entry_path):
file_type = octoprint.filemanager.get_file_type(entry)
if not file_type:
# only supported extensions
continue
else:
file_type = file_type[0]
if entry in metadata and isinstance(metadata[entry], dict):
entry_data = metadata[entry]
else:
entry_data = dict(
hash=self._create_hash(entry_path),
links=[],
notes=[]
)
metadata[entry] = entry_data
metadata_dirty = True
# TODO extract model hash from source if possible to recreate link
if not filter or filter(entry, entry_data):
# only add files passing the optional filter
extended_entry_data = dict()
extended_entry_data.update(entry_data)
extended_entry_data["name"] = entry
extended_entry_data["type"] = file_type
stat = os.stat(entry_path)
if stat:
extended_entry_data["size"] = stat.st_size
extended_entry_data["date"] = int(stat.st_mtime)
result[entry] = extended_entry_data
# folder recursion
elif os.path.isdir(entry_path) and recursive:
sub_result = self._list_folder(entry_path, filter=filter)
result[entry] = dict(
name=entry,
type="folder",
children=sub_result
)
# TODO recreate links if we have metadata less entries
# save metadata
if metadata_dirty:
self._save_metadata(path, metadata)
return result
def _create_hash(self, path):
import hashlib
blocksize = 65536
hash = hashlib.sha1()
with open(path, "rb") as f:
buffer = f.read(blocksize)
while len(buffer) > 0:
hash.update(buffer)
buffer = f.read(blocksize)
return hash.hexdigest()
def sanitize(self, path):
name = None
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
path = path.split("/")
if isinstance(path, (list, tuple)):
if len(path) == 1:
name = path[0]
path = "/"
else:
name = path[-1]
path = "/" + self.join_path(*path[:-1])
if not path:
path = "/"
name = self.sanitize_name(name)
path = self.sanitize_path(path)
return path, name
def sanitize_name(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 sanitize_path(self, path):
if path[0] == "/" or path[0] == ".":
path = path[1:]
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
path = os.path.realpath(joined_path)
if not path.startswith(self.basefolder):
raise ValueError("path not contained in base folder: {path}".format(**locals()))
return path
def rel_path(self, path):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
if path.startswith("/"):
path = path[1:]
return path
def _get_metadata(self, path):
if path in self._metadata_cache:
return self._metadata_cache[path]
metadata_path = os.path.join(path, ".metadata.yaml")
if os.path.exists(metadata_path):
with self._metadata_lock:
with open(metadata_path) as f:
try:
import yaml
return yaml.safe_load(f)
except:
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
return dict()
def _save_metadata(self, path, metadata):
metadata_path = os.path.join(path, ".metadata.yaml")
with self._metadata_lock:
with open(metadata_path, "w") as f:
try:
import yaml
yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
except:
self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
else:
self._metadata_cache[path] = metadata
-615
View File
@@ -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
+151
View File
@@ -0,0 +1,151 @@
# 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
from octoprint.settings import settings
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
from octoprint.plugin.types import *
# singleton
_instance = None
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None):
global _instance
if _instance is None:
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")))
if plugin_types is None:
plugin_types = [StartupPlugin,
ShutdownPlugin,
TemplatePlugin,
SettingsPlugin,
SimpleApiPlugin,
AssetPlugin,
BlueprintPlugin,
EventHandlerPlugin,
SlicerPlugin,
AppPlugin]
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, 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 call_plugin(types, method, args=None, kwargs=None, callback=None):
if not isinstance(types, (list, tuple)):
types = [types]
if args is None:
args = []
if kwargs is None:
kwargs = dict()
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)
class PluginSettings(object):
def __init__(self, settings, plugin_key, defaults=None):
self.settings = settings
self.plugin_key = plugin_key
if defaults is None:
defaults = dict()
self.defaults = dict(plugins=dict())
self.defaults["plugins"][plugin_key] = defaults
def prefix_path(path):
return ['plugins', self.plugin_key] + path
def prefix_path_in_args(args, index=0):
result = []
if index == 0:
result.append(prefix_path(args[0]))
result.extend(args[1:])
else:
args_before = args[:index - 1]
args_after = args[index + 1:]
result.extend(args_before)
result.append(prefix_path(args[index]))
result.extend(args_after)
return result
def add_defaults_to_kwargs(kwargs):
kwargs.update(dict(defaults=self.defaults))
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 globalGet(self, path):
return self.settings.get(path)
def globalGetInt(self, path):
return self.settings.getInt(path)
def globalGetFloat(self, path):
return self.settings.getFloat(path)
def globalGetBoolean(self, path):
return self.settings.getBoolean(path)
def globalSet(self, path, value):
self.settings.set(path, value)
def globalSetInt(self, path, value):
self.settings.setInt(path, value)
def globalSetFloat(self, path, value):
self.settings.setFloat(path, value)
def globalSetBoolean(self, path, value):
self.settings.setBoolean(path, value)
def globalGetBaseFolder(self, folder_type):
return self.settings.getBaseFolder(folder_type)
def getPluginLogfilePath(self, postfix=None):
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]
return lambda *args, **kwargs: orig_item(*args_mapper(args), **kwargs_mapper(kwargs))
else:
return getattr(self.settings, item)
+286
View File
@@ -0,0 +1,286 @@
# 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 imp
from collections import defaultdict
import logging
class PluginInfo(object):
attr_name = '__plugin_name__'
attr_description = '__plugin_description__'
attr_version = '__plugin_version__'
attr_hooks = '__plugin_hooks__'
attr_implementations = '__plugin_implementations__'
attr_helpers = '__plugin_helpers__'
attr_check = '__plugin_check__'
attr_init = '__plugin_init__'
def __init__(self, key, location, instance, version=None):
self.key = key
self.location = location
self.instance = instance
self._version = version
def __str__(self):
return "{name} ({version})".format(name=self.name, version=self.version if self.version else "unknown")
def get_hook(self, hook):
if not hook in self.hooks:
return None
return self.hooks[hook]
def get_implementations(self, *types):
result = set()
for implementation in self.implementations:
matches_all = True
for type in types:
if not isinstance(implementation, type):
matches_all = False
if matches_all:
result.add(implementation)
return result
@property
def name(self):
return self._get_instance_attribute(self.__class__.attr_name, default=None)
@property
def description(self):
return self._get_instance_attribute(self.__class__.attr_description, default=None)
@property
def version(self):
return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=None)
@property
def hooks(self):
return self._get_instance_attribute(self.__class__.attr_hooks, default={})
@property
def implementations(self):
return self._get_instance_attribute(self.__class__.attr_implementations, default=[])
@property
def helpers(self):
return self._get_instance_attribute(self.__class__.attr_helpers, default={})
@property
def check(self):
return self._get_instance_attribute(self.__class__.attr_check, default=lambda: True)
@property
def init(self):
return self._get_instance_attribute(self.__class__.attr_init, default=lambda: True)
def _get_instance_attribute(self, attr, default=None):
if not hasattr(self.instance, attr):
return default
return getattr(self.instance, attr)
class PluginManager(object):
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=None):
self.logger = logging.getLogger(__name__)
if plugin_disabled_list is None:
plugin_disabled_list = []
self.plugin_folders = plugin_folders
self.plugin_types = plugin_types
self.plugin_entry_points = plugin_entry_points
self.plugin_disabled_list = plugin_disabled_list
self.plugins = dict()
self.plugin_hooks = defaultdict(list)
self.plugin_implementations = defaultdict(list)
self.registered_clients = []
self.reload_plugins()
def _find_plugins(self):
plugins = dict()
if self.plugin_folders:
self._add_plugins_from_folders(self.plugin_folders, plugins)
if self.plugin_entry_points:
self._add_plugins_from_entry_points(self.plugin_entry_points, plugins)
return plugins
def _add_plugins_from_folders(self, folders, plugins):
for folder in folders:
if not os.path.exists(folder):
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
continue
entries = os.listdir(folder)
for entry in entries:
path = os.path.join(folder, entry)
if os.path.isdir(path) and os.path.isfile(os.path.join(path, "__init__.py")):
key = entry
elif os.path.isfile(path) and entry.endswith(".py"):
key = entry[:-3] # strip off the .py extension
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
return plugins
def _add_plugins_from_entry_points(self, groups, plugins):
import pkg_resources
if not isinstance(groups, (list, tuple)):
groups = [groups]
for group in groups:
for entry_point in pkg_resources.iter_entry_points(group=group, name=None):
key = entry_point.name
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)
if plugin:
plugins[key] = plugin
return plugins
def _load_plugin_from_module(self, key, folder=None, module_name=None, version=None):
# TODO error handling
if folder:
module = imp.find_module(key, [folder])
elif module_name:
module = imp.find_module(module_name)
else:
return None
plugin = self._load_plugin(key, *module, version=version)
if plugin:
if plugin.check():
return plugin
else:
self.logger.warn("Plugin \"{plugin}\" did not pass check, disabling it".format(plugin=str(plugin)))
return None
def _load_plugin(self, key, f, filename, description, version=None):
try:
instance = imp.load_module(key, f, filename, description)
return PluginInfo(key, filename, instance, version=version)
except:
self.logger.exception("Error loading plugin {key}, disabling it".format(key=key))
return None
def _is_plugin_disabled(self, key):
return key in self.plugin_disabled_list or key.endswith('disabled')
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()
for name, plugin in self.plugins.items():
# initialize the plugin
plugin.init()
# 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 )
self.log_registered_plugins()
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()))))
def get_plugin(self, name):
if not name in self.plugins:
return None
return self.plugins[name].instance
def get_hooks(self, hook):
if not hook in self.plugin_hooks:
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]
if result is None:
result = set(implementations)
else:
result = result.intersection(implementations)
if result is None:
return dict()
return {impl[0]: impl[1] for impl in result}
def get_helpers(self, name, *helpers):
if not name in self.plugins:
return None
plugin = self.plugins[name]
all_helpers = plugin.helpers
if len(helpers):
return dict((k, v) for (k, v) in all_helpers.items() if k in helpers)
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
+234
View File
@@ -0,0 +1,234 @@
# 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 .core import Plugin
class StartupPlugin(Plugin):
"""
The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services
on or just after the startup of the server.
"""
def on_startup(self, host, port):
"""
Called just before the server is actually launched. Plugins get supplied with the ``host`` and ``port`` the server
will listen on. Note that the ``host`` may be ``0.0.0.0`` if it will listen on all interfaces, so you can't just
blindly use this for constructing publicly reachable URLs. Also note that when this method is called, the server
is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be
externally reachable, use ``on_after_startup`` instead or additionally.
:param host: the host the server will listen on, may be ``0.0.0.0``
:param port: the port the server will listen on
"""
pass
def on_after_startup(self):
"""
Called just after launch of the server, so when the listen loop is actually running already.
"""
pass
class ShutdownPlugin(Plugin):
"""
The ``ShutdownPlugin`` allows hooking into the shutdown of OctoPrint. It's usually used in conjunction with the
``StartupPlugin`` mixin, to cleanly shut down additional services again that where started by the ``StartupPlugin``
part of the plugin.
"""
def on_shutdown(self):
"""
Called upon the imminent shutdown of OctoPrint.
"""
pass
class AssetPlugin(Plugin):
"""
The ``AssetPlugin`` mixin allows plugins to define additional static assets such as Javascript or CSS files to
be automatically embedded into the pages delivered by the server to be used within the client sided part of
the plugin.
A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used on the settings page
of a ``SettingsPlugin``.
"""
def get_asset_folder(self):
"""
Defines the folder where the plugin stores its static assets as defined in ``get_assets``. Usually an
implementation such as
.. code-block:: python
def get_asset_folder(self):
import os
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "static")
should be sufficient here. This way, assets can be put into a sub folder ``static`` in the plugin directory.
:return: the absolute path to the folder where the plugin stores its static assets
"""
return None
def get_assets(self):
"""
Defines the static assets the plugin offers. The following asset types are recognized and automatically
imported at the appropriate places to be available:
js
Javascript files, such as additional view models
css
CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode.
less
LESS files with additional styles, will be embedded into delivered pages when running in LESS mode.
The expected format to be returned is a dictionary mapping one or more of these keys to a list of files of that
type, the files being represented as relative paths from the asset folder as defined via ``get_asset_folder``.
Example:
.. code-block:: python
def get_assets(self):
return dict(
js=['js/my_file.js', 'js/my_other_file.js'],
css=['css/my_styles.css'],
less=['less/my_styles.less']
)
The assets will be made available by OctoPrint under the URL ``/plugin_assets/<plugin name>/<path>``, with
``plugin_name`` being the plugin's name and ``path`` being the path as defined in the asset dictionary.
:return: a dictionary describing the static assets to publish for the plugin
"""
return []
class TemplatePlugin(Plugin):
def get_template_vars(self):
return dict()
def get_template_folder(self):
return None
class SimpleApiPlugin(Plugin):
def get_api_commands(self):
return None
def on_api_command(self, command, data):
return None
def on_api_get(self, request):
return None
class BlueprintPlugin(Plugin):
"""
The ``BlueprintPlugin`` mixin allows plugins to define their own full fledged endpoints for whatever purpose,
be it a more sophisticated API than what is possible via the ``SimpleApiPlugin`` or a custom web frontend.
The mechanism at work here is `Flask's <http://flask.pocoo.org/>`_ own `Blueprint mechanism <http://flask.pocoo.org/docs/0.10/blueprints/>`_.
Your plugin should define a blueprint like this:
.. code-block:: python
template_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates")
blueprint = flask.Blueprint("plugin.myplugin", __name__, template_folder=template_folder)
Use your blueprint just like any other Flask blueprint for defining your own endpoints, e.g.
.. code-block:: python
@blueprint.route("/echo", methods=["GET"])
def myEcho():
if not "text" in flask.request.values:
return flask.make_response("Expected a text to echo back.", 400)
return flask.request.values["text"]
Your blueprint will be published by OctoPrint under the URL ``/plugin/<pluginname>/``, so the above example
would be reachable under ``/plugin/myplugin/echo`` (given that you named your plugin "myplugin"). You'll be able
to create URLs via ``url_for`` under the prefix that you've chosen when constructing your blueprint, ``plugin.myplugin``
in the above example:
.. code-block:: python
flask.url_for("plugin.myplugin.echo") # will return "/plugin/myplugin/echo"
OctoPrint Blueprint plugins should always follow the naming scheme ``plugin.<plugin name>`` here
to avoid conflicts.
"""
def get_blueprint(self):
"""
Retrieves the blueprint as defined by your plugin.
:return: the blueprint ready to be registered with Flask
"""
return None
def is_blueprint_protected(self):
"""
Whether the blueprint is supposed to be protected by API key (the default) or not.
"""
return True
class SettingsPlugin(Plugin):
def on_settings_load(self):
return None
def on_settings_save(self, data):
pass
class EventHandlerPlugin(Plugin):
def on_event(self, event, payload):
pass
class SlicerPlugin(Plugin):
def is_slicer_configured(self):
return False
def get_slicer_properties(self):
return dict(
type=None,
name=None,
same_device=True,
progress_report=False
)
def get_slicer_profile_options(self):
return None
def get_slicer_profile(self, path):
return None
def get_slicer_default_profile(self):
return None
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
pass
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
pass
def cancel_slicing(self, machinecode_path):
pass
class AppPlugin(Plugin):
def get_additional_apps(self):
return []
+410
View File
@@ -0,0 +1,410 @@
# 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 octoprint.plugin
import octoprint.util
import octoprint.slicing
import octoprint.settings
default_settings = {
"cura_engine": None,
"default_profile": None,
"debug_logging": False
}
s = octoprint.plugin.plugin_settings("cura", defaults=default_settings)
from .profile import Profile
blueprint = flask.Blueprint("plugin.cura", __name__)
@blueprint.route("/import", methods=["POST"])
def importCuraProfile():
import datetime
import tempfile
from octoprint.server import slicingManager
input_name = "file"
input_upload_name = input_name + "." + s.globalGet(["server", "uploads", "nameSuffix"])
input_upload_path = input_name + "." + s.globalGet(["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.getFormattedDateTime(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
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._slicing_commands_mutex = threading.Lock()
self._cancelled_jobs = []
self._cancelled_jobs_mutex = threading.Lock()
##~~ StartupPlugin API
def on_startup(self, host, port):
# setup our custom logger
cura_logging_handler = logging.handlers.RotatingFileHandler(s.getPluginLogfilePath(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 s.getBoolean(["debug_logging"]) else logging.CRITICAL)
self._cura_logger.propagate = False
##~~ BlueprintPlugin API
def get_blueprint(self):
global blueprint
return blueprint
##~~ AssetPlugin API
def get_asset_folder(self):
import os
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "static")
def get_assets(self):
return {
"js": ["js/cura.js"],
"less": ["less/cura.less"],
"css": ["css/cura.css"]
}
##~~ SettingsPlugin API
def on_settings_load(self):
return dict(
cura_engine=s.get(["cura_engine"]),
default_profile=s.get(["default_profile"]),
debug_logging=s.getBoolean(["debug_logging"])
)
def on_settings_save(self, data):
if "cura_engine" in data and data["cura_engine"]:
s.set(["cura_engine"], data["cura_engine"])
if "default_profile" in data and data["default_profile"]:
s.set(["default_profile"], data["default_profile"])
if "debug_logging" in data:
old_debug_logging = s.getBoolean(["debug_logging"])
new_debug_logging = data["debug_logging"] in octoprint.settings.valid_boolean_trues
if old_debug_logging != new_debug_logging:
if new_debug_logging:
self._cura_logger.setLevel(logging.DEBUG)
else:
self._cura_logger.setLevel(logging.CRITICAL)
s.setBoolean(["debug_logging"], new_debug_logging)
##~~ TemplatePlugin API
def get_template_vars(self):
return dict(
_settings_menu_entry="Cura"
)
def get_template_folder(self):
import os
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates")
##~~ SlicerPlugin API
def is_slicer_configured(self):
cura_engine = s.get(["cura_engine"])
return cura_engine is not None and os.path.exists(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 = s.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):
if not profile_path:
profile_path = s.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 = s.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))
try:
p = sarge.run(command, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
try:
with self._slicing_commands_mutex:
self._slicing_commands[machinecode_path] = p.commands[0]
layer_count = None
step_factor = dict(
inset=0,
skin=1,
export=2
)
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)
finally:
p.close()
with self._cancelled_jobs_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, None
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._cancelled_jobs_mutex:
if machinecode_path in self._cancelled_jobs:
self._cancelled_jobs.remove(machinecode_path)
with self._slicing_commands_mutex:
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._slicing_commands_mutex:
if machinecode_path in self._slicing_commands:
with self._cancelled_jobs_mutex:
self._cancelled_jobs.append(machinecode_path)
self._slicing_commands[machinecode_path].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_implementations__ = [CuraPlugin()]
+971
View File
@@ -0,0 +1,971 @@
# 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 . import s
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.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")
bedTemp = 0
if self.get_boolean("has_heated_bed"):
bedTemp = self.get_float("print_bed_temperature")
include_bed_temps = bedTemp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
if include_bed_temps:
prefix += "M140 S{print_bed_temperature}\n"
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)
for n in xrange(1, extruder_count):
prefix += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
for n in xrange(0, extruder_count):
prefix += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
prefix += "T0\n"
else:
prefix += "M109 S{temp}\n".format(temp=temp)
if include_bed_temps:
prefix += "M190 S{print_bed_temperature}\n".format(bedTemp=bedTemp)
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,191 @@
$(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
ADDITIONAL_VIEWMODELS.push([CuraViewModel, ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], document.getElementById("settings_plugin_cura_dialog")]);
});
@@ -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,247 @@
<div id="settings_plugin_cura_dialog" data-bind="allowBindings: true">
<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>&nbsp;|&nbsp;<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">&times;</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.importCuraProfile") }}">
</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">&times;</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>
</div>
+690
View File
@@ -0,0 +1,690 @@
# 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"
"""
The SSDP/UPNP implementations has been largely inspired by https://gist.github.com/schlamar/2428250
"""
import logging
import os
import flask
import octoprint.plugin
import octoprint.util
try:
import pybonjour
except:
pybonjour = False
__plugin_name__ = "Discovery"
__plugin_version__ = "0.1"
__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
def __plugin_init__():
if not pybonjour:
# no pybonjour available, we can't use that
logging.getLogger("octoprint.plugins." + __name__).info("pybonjour is not installed, Zeroconf Discovery won't be available")
discovery_plugin = DiscoveryPlugin()
global __plugin_implementations__
__plugin_implementations__ = [discovery_plugin]
global __plugin_helpers__
__plugin_helpers__ = dict(
ssdp_browse=discovery_plugin.ssdp_browse
)
if pybonjour:
__plugin_helpers__.update(dict(
zeroconf_browse=discovery_plugin.zeroconf_browse,
zeroconf_register=discovery_plugin.zeroconf_register,
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 u"OctoPrint instance \"{}\"".format(name)
else:
import socket
return u"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):
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
# zeroconf
self._sd_refs = dict()
self._cnames = dict()
# upnp/ssdp
self._ssdp_monitor_active = False
self._ssdp_monitor_thread = None
self._ssdp_notify_timeout = 10
self._ssdp_last_notify = 0
##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML
def get_blueprint(self):
return blueprint
##~~ 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"])
if public_host:
host = public_host
public_port = s.get(["publicPort"])
if public_port:
port = public_port
self.host = host
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"]):
if "service" in zeroconf:
self.zeroconf_register(
zeroconf["service"],
zeroconf["name"] if "name" in zeroconf else get_instance_name(),
port=zeroconf["port"] if "port" in zeroconf else None,
txt_record=zeroconf["txtRecord"] if "txtRecord" in zeroconf else None
)
# SSDP
self._ssdp_register()
##~~ ShutdownPlugin API -- used for unregistering OctoPrint's Zeroconf and SSDP service upon application shutdown
def on_shutdown(self):
for key in self._sd_refs:
reg_type, port = key
self.zeroconf_unregister(reg_type, port)
self._ssdp_unregister()
##~~ helpers
# ZeroConf
def zeroconf_register(self, reg_type, name=None, port=None, txt_record=None):
"""
Registers a new service with Zeroconf/Bonjour/Avahi.
:param reg_type: type of service to register, e.g. "_gntp._tcp"
:param name: displayable name of the service, if not given defaults to the OctoPrint instance name
:param port: port to register for the service, if not given defaults to OctoPrint's (public) port
:param txt_record: optional txt record to attach to the service, dictionary of key-value-pairs
"""
if not pybonjour:
return
if not name:
name = get_instance_name()
if not port:
port = self.port
params = dict(
name=name,
regtype=reg_type,
port=port
)
if txt_record:
params["txtRecord"] = pybonjour.TXTRecord(txt_record)
key = (reg_type, port)
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
self.logger.info(u"Registered {name} for {reg_type}".format(**locals()))
def zeroconf_unregister(self, reg_type, port=None):
"""
Unregisteres a previously registered Zeroconf/Bonjour/Avahi service identified by service and port.
:param reg_type: the type of the service to be unregistered
:param port: the port of the service to be unregistered, defaults to OctoPrint's (public) port if not given
:return:
"""
if not pybonjour:
return
if not port:
port = self.port
key = (reg_type, port)
if not key in self._sd_refs:
return
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))
except:
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):
"""
Browses for services on the local network providing the specified service type. Can be used either blocking or
non-blocking.
The non-blocking version (default behaviour) will not return until the lookup has completed and
return all results that were found.
For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes.
If no callback is provided in non-blocking mode, a ValueError will be raised.
The results are provided as a list of discovered services, with each service being described by a dictionary
with the following keys:
* `name`: display name of the service
* `host`: host name of the service
* `post`: port the service is listening on
* `txt_record`: TXT record of the service as a dictionary, exact contents depend on the service
Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an
example for a valid callback:
def browse_callback(results):
for result in results:
print "Name: {name}, Host: {host}, Port: {port}, TXT: {txt_record!r}".format(**result)
:param service_type: the service type to browse for
:param block: whether to block, defaults to True
:param callback: callback to call once lookup has completed, must be set when `block` is set to `False`
:param browse_timeout: timeout for browsing operation
:param resolve_timeout: timeout for resolving operations for discovered records
:return: if `block` is `True` a list of the discovered services, an empty list otherwise (results will then be
supplied to the callback instead)
"""
if not pybonjour:
return None
import threading
import select
if not block and not callback:
raise ValueError("Non-blocking mode but no callback given")
result = []
result_available = threading.Event()
result_available.clear()
resolved = []
def resolve_callback(sd_ref, flags, interface_index, error_code, fullname, hosttarget, port, txt_record):
if error_code == pybonjour.kDNSServiceErr_NoError:
txt_record_dict = None
if txt_record:
record = pybonjour.TXTRecord.parse(txt_record)
txt_record_dict = dict()
for key, value in record:
txt_record_dict[key] = value
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))
result.append(dict(
name=name,
host=host,
port=port,
txt_record=txt_record_dict
))
resolved.append(True)
def browse_callback(sd_ref, flags, interface_index, error_code, service_name, regtype, reply_domain):
if error_code != pybonjour.kDNSServiceErr_NoError:
return
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))
resolve_ref = pybonjour.DNSServiceResolve(0, interface_index, service_name, regtype, reply_domain, resolve_callback)
try:
while not resolved:
ready = select.select([resolve_ref], [], [], resolve_timeout)
if resolve_ref not in ready[0]:
break
pybonjour.DNSServiceProcessResult(resolve_ref)
else:
resolved.pop()
finally:
resolve_ref.close()
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)
try:
while True:
ready = select.select([sd_ref], [], [], browse_timeout)
if not ready[0]:
break
if sd_ref in ready[0]:
pybonjour.DNSServiceProcessResult(sd_ref)
finally:
sd_ref.close()
if callback:
callback(result)
result_available.set()
browse_thread = threading.Thread(target=browse)
browse_thread.daemon = True
browse_thread.start()
if block:
result_available.wait()
return result
else:
return []
# SSDP/UPNP
def ssdp_browse(self, query, block=True, callback=None, timeout=1, retries=5):
"""
Browses for UPNP services matching the supplied query. Can be used either blocking or
non-blocking.
The non-blocking version (default behaviour) will not return until the lookup has completed and
return all results that were found.
For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes.
If no callback is provided in non-blocking mode, a ValueError will be raised.
The results are provided as a list of discovered locations of device descriptor files.
Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an
example for a valid callback:
def browse_callback(results):
for result in results:
print "Location: {}".format(result)
:param query: the SSDP query to send, e.g. "upnp:rootdevice" to search for all devices
:param block: whether to block, defaults to True
:param callback: callback to call in non-blocking mode when lookup has finished, must be set if block is False
:param timeout: timeout in seconds to wait for replies to the M-SEARCH query per interface, defaults to 1
:param retries: number of retries to perform the lookup on all interfaces, defaults to 5
:return: if `block` is `True` a list of the discovered devices, an empty list otherwise (results will then be
supplied to the callback instead)
"""
import threading
import httplib
import io
class Response(httplib.HTTPResponse):
def __init__(self, response_text):
self.fp = io.BytesIO(response_text)
self.debuglevel = 0
self.strict = 0
self.msg = None
self._method = None
self.begin()
result = []
result_available = threading.Event()
result_available.clear()
def browse():
import socket
socket.setdefaulttimeout(timeout)
search_message = "".join([
"M-SEARCH * HTTP/1.1\r\n",
"ST: {query}\r\n",
"MX: 3\r\n",
"MAN: \"ssdp:discovery\"\r\n",
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n"
])
for _ in xrange(retries):
for addr in octoprint.util.interface_addresses():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
sock.bind((addr, 0))
message = search_message.format(query=query,
mcast_addr=self.__class__.ssdp_multicast_addr,
mcast_port=self.__class__.ssdp_multicast_port)
for _ in xrange(2):
sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
try:
data = sock.recv(1024)
except socket.timeout:
pass
else:
response = Response(data)
result.append(response.getheader("Location"))
except:
pass
if callback:
callback(result)
result_available.set()
browse_thread = threading.Thread(target=browse)
browse_thread.daemon = True
browse_thread.start()
if block:
result_available.wait()
return result
else:
return []
##~~ internals
# Zeroconf
def _create_http_txt_record_dict(self):
"""
Creates a TXT record for the _http._tcp Zeroconf service supplied by this OctoPrint instance.
Defines the keys for _http._tcp as defined in http://www.dns-sd.org/txtrecords.html
:return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record
"""
# determine path entry
path = "/"
if s.get(["pathPrefix"]):
path = s.get(["pathPrefix"])
else:
prefix = s.globalGet(["server", "reverseProxy", "prefixFallback"])
if prefix:
path = prefix
# fetch username and password (if set)
username = s.get(["httpUsername"])
password = s.get(["httpPassword"])
entries = dict(
path=path
)
if username and password:
entries.update(dict(u=username, p=password))
return entries
def _create_octoprint_txt_record_dict(self):
"""
Creates a TXT record for the _octoprint._tcp Zeroconf service supplied by this OctoPrint instance.
The following keys are defined:
* `path`: path prefix to actual OctoPrint instance, inherited from _http._tcp
* `u`: username if HTTP Basic Auth is used, optional, inherited from _http._tcp
* `p`: password if HTTP Basic Auth is used, optional, inherited from _http._tcp
* `version`: OctoPrint software version
* `api`: OctoPrint API version
* `model`: Model of the device that is running OctoPrint
* `vendor`: Vendor of the device that is running OctoPrint
:return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record
"""
entries = self._create_http_txt_record_dict()
import octoprint.server
import octoprint.server.api
entries.update(dict(
version=octoprint.server.VERSION,
api=octoprint.server.api.VERSION,
))
modelName = s.get(["model", "name"])
if modelName:
entries.update(dict(model=modelName))
vendor = s.get(["model", "vendor"])
if vendor:
entries.update(dict(vendor=vendor))
return entries
# SSDP/UPNP
def _ssdp_register(self):
"""
Registers the OctoPrint instance as basic service with a presentation URL pointing to the web interface
"""
import threading
self._ssdp_monitor_active = True
self._ssdp_monitor_thread = threading.Thread(target=self._ssdp_monitor, kwargs=dict(timeout=self._ssdp_notify_timeout))
self._ssdp_monitor_thread.daemon = True
self._ssdp_monitor_thread.start()
def _ssdp_unregister(self):
"""
Unregisters the OctoPrint instance again
"""
self._ssdp_monitor_active = False
if self.host and self.port:
for _ in xrange(2):
self._ssdp_notify(alive=False)
def _ssdp_notify(self, alive=True):
"""
Sends an SSDP notify message across the connected networks.
:param alive: True to send an "ssdp:alive" message, False to send an "ssdp:byebye" message
"""
import socket
import time
if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > time.time():
# we just sent an alive, no need to send another one now
return
if alive and not self._ssdp_monitor_active:
# the monitor already shut down, alive messages don't make sense anymore as byebye will shortly follow
return
for addr in octoprint.util.interface_addresses():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
sock.bind((addr, 0))
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))
notify_message = "".join([
"NOTIFY * HTTP/1.1\r\n",
"Server: Python/2.7\r\n",
"Cache-Control: max-age=900\r\n",
"Location: {location}\r\n",
"NTS: {nts}\r\n",
"NT: upnp:rootdevice\r\n",
"USN: uuid:{uuid}::upnp:rootdevice\r\n",
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n"
])
message = notify_message.format(uuid=UUID,
location=location,
nts="ssdp:alive" if alive else "ssdp:byebye",
mcast_addr=self.__class__.ssdp_multicast_addr,
mcast_port=self.__class__.ssdp_multicast_port)
for _ in xrange(2):
# send twice, stuff might get lost, it's only UDP
sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
except:
pass
self._ssdp_last_notify = time.time()
def _ssdp_monitor(self, timeout=5):
"""
Monitor thread that listens on the multicast address for M-SEARCH requests and answers them if they are relevant
:param timeout: timeout after which to stop waiting for M-SEARCHs for a short while in order to put out an
alive message
"""
from BaseHTTPServer import BaseHTTPRequestHandler
from StringIO import StringIO
import socket
socket.setdefaulttimeout(timeout)
location_message = "".join([
"HTTP/1.1 200 OK\r\n",
"ST: upnp:rootdevice\r\n",
"USN: uuid:{uuid}::upnp:rootdevice\r\n",
"Location: {location}\r\n",
"Cache-Control: max-age=60\r\n\r\n"
])
class Request(BaseHTTPRequestHandler):
def __init__(self, request_text):
self.rfile = StringIO(request_text)
self.raw_requestline = self.rfile.readline()
self.error_code = self.error_message = None
self.parse_request()
def send_error(self, code, message=None):
self.error_code = code
self.error_message = message
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
sock.bind(('', self.__class__.ssdp_multicast_port))
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(u"Registered {} for SSDP".format(get_instance_name()))
self._ssdp_notify(alive=True)
try:
while (self._ssdp_monitor_active):
try:
data, address = sock.recvfrom(4096)
request = Request(data)
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))
continue
message = location_message.format(uuid=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))
except socket.timeout:
pass
finally:
self._ssdp_notify(alive=True)
finally:
try:
sock.close()
except:
pass
@@ -0,0 +1,22 @@
<?xml version="1.0"?>
<root xmlns="urn:schemas-upnp-org:device-1-0">
<specVersion>
<major>1</major>
<minor>0</minor>
</specVersion>
<device>
<deviceType>urn:schemas-upnp-org:device:Basic:1</deviceType>
<friendlyName>{{ friendlyName }}</friendlyName>
<manufacturer>{{ manufacturer }}</manufacturer>
{% if manufacturerUrl %}<manufacturerURL>{{ manufacturerUrl }}</manufacturerURL>{% endif %}
<modelName>{{ modelName }}</modelName>
{% if modelDescription %}<modelDescription>{{ modelDescription }}</modelDescription>{% endif %}
{% if modelNumber %}<modelNumber>{{ modelNumber }}</modelNumber>{% endif %}
{% if modelUrl %}<modelURL>{{ modelUrl }}</modelURL>{% endif %}
{% if serialNumber %}<serialNumber>{{ serialNumber }}</serialNumber>{% endif %}
<UDN>uuid:{{ uuid }}</UDN>
<serviceList>
</serviceList>
<presentationURL>{{ presentationUrl }}</presentationURL>
</device>
</root>
@@ -30,11 +30,14 @@ def getConnectionOptions():
}
class Printer():
def __init__(self, gcodeManager):
def __init__(self, fileManager, analysisQueue, printerProfileManager):
from collections import deque
self._gcodeManager = gcodeManager
self._gcodeManager.registerCallback(self)
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?
@@ -120,40 +123,32 @@ class Printer():
def _sendAddTemperatureCallbacks(self, data):
for callback in self._callbacks:
try: callback.addTemperature(data)
except: pass
except: self._logger.exception("Exception while adding temperature data point")
def _sendAddLogCallbacks(self, data):
for callback in self._callbacks:
try: callback.addLog(data)
except: pass
except: self._logger.exception("Exception while adding communication log entry")
def _sendAddMessageCallbacks(self, data):
for callback in self._callbacks:
try: callback.addMessage(data)
except: pass
except: self._logger.exception("Exception while adding printer message")
def _sendCurrentDataCallbacks(self, data):
for callback in self._callbacks:
try: callback.sendCurrentData(copy.deepcopy(data))
except: pass
except: self._logger.exception("Exception while pushing current data")
def _sendTriggerUpdateCallbacks(self, type):
for callback in self._callbacks:
try: callback.sendEvent(type)
except: pass
except: self._logger.exception("Exception while pushing trigger update")
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"])
except: self._logger.exception("Exception while pushing feedback command output")
#~~ callback from metadata analysis event
@@ -165,7 +160,7 @@ class Printer():
#~~ printer commands
def connect(self, port=None, baudrate=None):
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.
@@ -173,6 +168,7 @@ class Printer():
if self._comm is not None:
self._comm.close()
self._comm = comm.MachineCom(port, baudrate, callbackObject=self)
self._printerProfileManager.select(profile)
def disconnect(self):
"""
@@ -181,6 +177,7 @@ class Printer():
if self._comm is not None:
self._comm.close()
self._comm = None
self._printerProfileManager.deselect()
eventManager().fire(Events.DISCONNECTED)
def command(self, command):
@@ -200,15 +197,17 @@ class Printer():
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"])
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):
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"])
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 changeTool(self, tool):
try:
@@ -219,7 +218,9 @@ class Printer():
def setTemperature(self, type, value):
if type.startswith("tool"):
if settings().getInt(["printerParameters", "numExtruders"]) > 1:
printer_profile = self._printerProfileManager.get_current_or_default()
extruder_count = printer_profile["extruder"]["count"]
if extruder_count > 1:
try:
toolNum = int(type[len("tool"):])
self.command("M104 T%d S%f" % (toolNum, value))
@@ -256,7 +257,7 @@ class Printer():
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")
self._logger.info("Cannot load file: printer not connected or currently busy")
return
self._printAfterSelect = printAfterSelect
@@ -304,9 +305,12 @@ class Printer():
self._comm.cancelPrint()
if disableMotorsAndHeater:
printer_profile = self._printerProfileManager.get_current_or_default()
extruder_count = printer_profile["extruder"]["count"]
# 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(map(lambda x: "M104 T%d S0" % x, range(extruder_count)))
commands.extend(["M140 S0", "M106 S0"])
self.commands(commands)
@@ -316,7 +320,7 @@ class Printer():
# mark print as failure
if self._selectedFile is not None:
self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime())
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False)
payload = {
"file": self._selectedFile["filename"],
"origin": FileDestinations.LOCAL
@@ -388,6 +392,17 @@ class Printer():
}
else:
self._selectedFile = None
self._stateMonitor.setJobData({
"file": {
"name": None,
"origin": None,
"size": None,
"date": None
},
"estimatedPrintTime": None,
"filament": None,
})
return
estimatedPrintTime = None
lastPrintTime = None
@@ -399,13 +414,16 @@ class Printer():
if not sd:
date = int(os.stat(filename).st_ctime)
fileData = self._gcodeManager.getFileData(filename)
try:
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, filename)
except:
fileData = None
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 "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 "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"]
@@ -467,12 +485,12 @@ class Printer():
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())
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), True)
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
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False)
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._gcodeManager.pauseAnalysis() # do not analyse gcode while printing
self._analysisQueue.pause() # do not analyse files while printing
self._setState(state)
@@ -553,7 +571,7 @@ class Printer():
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")
self._logger.error("No connection to printer or printer is busy")
return
self._streamingFinishedCallback = streamingFinishedCallback
@@ -641,10 +659,11 @@ class Printer():
def getCurrentConnection(self):
if self._comm is None:
return "Closed", None, None
return "Closed", None, None, None
port, baudrate = self._comm.getConnection()
return self._comm.getStateString(), port, baudrate
printer_profile = self._printerProfileManager.get_current_or_default()
return self._comm.getStateString(), port, baudrate, printer_profile
def isClosedOrError(self):
return self._comm is None or self._comm.isClosedOrError()
+223
View File
@@ -0,0 +1,223 @@
# 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
from octoprint.settings import settings
from octoprint.util import dict_merge, dict_clean
from octoprint.events import Events, eventManager
class SaveError(Exception):
pass
class BedTypes(object):
RECTANGULAR = "rectangular"
CIRCULAR = "circular"
class PrinterProfileManager(object):
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")
def select(self, identifier):
if identifier is None or not self.exists(identifier):
self._current = self.get_default()
eventManager().fire(Events.PRINTER_PROFILE_SELECTED, payload=dict(profile=self._current["id"]))
return False
else:
self._current = self.get(identifier)
eventManager().fire(Events.PRINTER_PROFILE_SELECTED, payload=dict(profile=self._current["id"]))
return True
def deselect(self):
self._current = None
eventManager().fire(Events.PRINTER_PROFILE_DESELECTED)
def get_all(self):
return self._load_all()
def get(self, identifier):
if identifier == "_default":
return self._load_default()
elif self.exists(identifier):
return self._load_from_path(self._get_profile_path(identifier))
else:
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 ValueError("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)
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)
eventManager().fire(Events.PRINTER_PROFILE_MODIFIED, payload=dict(profile=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():
if identifier == "_default":
profile = self._load_default()
else:
profile = self._load_from_path(path)
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)
return profile
def _save_to_path(self, path, profile, allow_overwrite=False):
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_profile = settings().get(["printerProfiles", "defaultProfile"])
return dict_merge(copy.deepcopy(self.__class__.default), default_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
+168 -26
View File
@@ -7,7 +7,7 @@ __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
from flask import Flask, render_template, send_from_directory, g, request, make_response, session
from flask.ext.login import LoginManager
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
from flask.ext.babel import Babel
@@ -17,6 +17,7 @@ from watchdog.observers import Observer
import os
import logging
import logging.config
import atexit
SUCCESS = {}
NO_CONTENT = ("", 204)
@@ -26,10 +27,15 @@ 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"))
@@ -37,19 +43,28 @@ 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.profile import PrinterProfileManager
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
UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
VERSION = octoprint._version.get_versions()['version']
versions = octoprint._version.get_versions()
VERSION = versions['version']
BRANCH = versions['branch'] if 'branch' in versions else None
DISPLAY_VERSION = "%s (%s branch)" % (VERSION, BRANCH) if BRANCH else VERSION
del versions
def get_available_locale_identifiers(locales):
@@ -83,6 +98,19 @@ def get_locale():
@app.route("/")
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()
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()
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
template_plugin_names = template_plugins.keys()
return render_template(
"index.jinja2",
webcamStream=settings().get(["webcam", "stream"]),
@@ -95,10 +123,14 @@ def index():
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
uiApiKey=UI_API_KEY,
settingsPlugins=settings_plugin_template_vars,
templatePlugins=template_plugin_names,
assetPlugins=asset_plugin_urls
)
@@ -107,6 +139,20 @@ def robotsTxt():
return send_from_directory(app.static_folder, "robots.txt")
@app.route("/plugin_assets/<string:name>/<path:filename>")
def plugin_assets(name, filename):
asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin)
if not name in asset_plugins:
return make_response("Asset not found", 404)
asset_plugin = asset_plugins[name]
asset_folder = asset_plugin.get_asset_folder()
if asset_folder is None:
return make_response("Asset not found", 404)
return send_from_directory(asset_folder, filename)
@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
user = load_user(identity.id)
@@ -121,8 +167,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()
@@ -145,10 +202,15 @@ 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
@@ -162,14 +224,36 @@ class Server():
# then initialize logging
self._initLogging(self._debug, self._logConf)
logger = logging.getLogger(__name__)
logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)
logger.info("Starting OctoPrint (%s)" % VERSION)
logger.info("Starting OctoPrint (%s)" % VERSION)
# then initialize the plugin manager
pluginManager = octoprint.plugin.plugin_manager(init=True)
printerProfileManager = PrinterProfileManager()
eventManager = events.eventManager()
gcodeManager = gcodefiles.GcodeManager()
printer = Printer(gcodeManager)
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()
# configure additional template folders for jinja2
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
additional_template_folders = []
for plugin in template_plugins.values():
folder = plugin.get_template_folder()
if folder is not None:
additional_template_folders.append(plugin.get_template_folder())
import jinja2
jinja_loader = jinja2.ChoiceLoader([
app.jinja_loader,
jinja2.FileSystemLoader(additional_template_folders)
])
app.jinja_loader = jinja_loader
del jinja2
# configure timelapse
octoprint.timelapse.configureTimelapse()
@@ -195,7 +279,15 @@ class Server():
settings().get(["server", "reverseProxy", "prefixScheme"])
)
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
@@ -209,19 +301,37 @@ class Server():
if self._port is None:
self._port = settings().getInt(["server", "port"])
logger.info("Listening on http://%s:%d" % (self._host, self._port))
app.debug = self._debug
from octoprint.server.api import api
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
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))
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))", 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))
@@ -235,30 +345,59 @@ class Server():
eventManager.fire(events.Events.STARTUP)
if settings().getBoolean(["serial", "autoconnect"]):
(port, baudrate) = settings().get(["serial", "port"]), settings().getInt(["serial", "baudrate"])
printer_profile = printerProfileManager.get_default()
connectionOptions = getConnectionOptions()
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()
try:
IOLoop.instance().start()
except KeyboardInterrupt:
ioloop = IOLoop.instance()
# run our startup plugins
octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
"on_startup",
args=(self._host, self._port))
# prepare our after startup function
def on_after_startup():
logger.info("Listening on http://%s:%d" % (self._host, self._port))
# now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for
# which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons
# or service xmls or the like). While they are working though the ioloop would block. Therefore we'll
# create a single use thread in which to perform our after-startup-tasks, start that and hand back
# control to the ioloop
def work():
octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
"on_after_startup")
import threading
threading.Thread(target=work).start()
ioloop.add_callback(on_after_startup)
# prepare our shutdown function
def on_shutdown():
logger.info("Goodbye!")
observer.stop()
observer.join()
octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin,
"on_shutdown")
atexit.register(on_shutdown)
try:
ioloop.start()
except KeyboardInterrupt:
pass
except:
logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!")
logger.exception("Stacktrace follows:")
finally:
observer.stop()
observer.join()
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:
@@ -303,6 +442,9 @@ class Server():
"level": "CRITICAL",
"handlers": ["serialFile"],
"propagate": False
},
"tornado.application": {
"level": "ERROR"
}
},
"root": {
+54 -71
View File
@@ -16,9 +16,10 @@ from flask.ext.principal import Identity, identity_changed, AnonymousIdentity
import octoprint.util as util
import octoprint.users
import octoprint.server
from octoprint.server import admin_permission, NO_CONTENT, UI_API_KEY
import octoprint.plugin
from octoprint.server import admin_permission, NO_CONTENT
from octoprint.settings import settings as s, valid_boolean_trues
from octoprint.server.util import get_api_key, get_user_for_apikey
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
from octoprint.server.util.flask import restricted_access
@@ -34,78 +35,52 @@ 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"
api.before_request(apiKeyRequestHandler)
api.after_request(corsResponseHandler)
def optionsAllowOrigin(request):
""" Always reply 200 on OPTIONS request """
#~~ data from plugins
resp = current_app.make_default_options_response()
@api.route("/plugin/<string:name>", methods=["GET"])
def pluginData(name):
api_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SimpleApiPlugin)
if not name in api_plugins:
return make_response("Not found", 404)
# 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"
api_plugin = api_plugins[name]
response = api_plugin.on_api_get(request)
# '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
if response is not None:
return response
return NO_CONTENT
return resp
#~~ commands for plugins
@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.
"""
@api.route("/plugin/<string:name>", methods=["POST"])
@restricted_access
def pluginCommand(name):
api_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SimpleApiPlugin)
if not name in api_plugins:
return make_response("Not found", 404)
if request.method == 'OPTIONS' and s().getBoolean(["api", "allowCrossOrigin"]):
return optionsAllowOrigin(request)
api_plugin = api_plugins[name]
valid_commands = api_plugin.get_api_commands()
if valid_commands is None:
return make_response("Method not allowed", 405)
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
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
if response is not None:
return response
response = api_plugin.on_api_command(command, data)
if response is not None:
return response
return NO_CONTENT
#~~ first run setup
@@ -142,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():
@@ -204,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())
@@ -248,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)
+30 -8
View File
@@ -9,7 +9,7 @@ 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.server import printer, printerProfileManager, NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access
import octoprint.util as util
@@ -17,13 +17,15 @@ import octoprint.util as util
@api.route("/connection", methods=["GET"])
def connectionState():
state, port, baudrate = printer.getCurrentConnection()
state, port, baudrate, printer_profile = printer.getCurrentConnection()
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"])
@@ -39,28 +41,48 @@ def connectionCommand():
return response
if command == "connect":
options = getConnectionOptions()
connection_options = getConnectionOptions()
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 = getConnectionOptions()
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
+183 -31
View File
@@ -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 import printer, fileManager, slicingManager, eventManager, NO_CONTENT
from octoprint.server.util.flask import restricted_access
from octoprint.server.api import api
from octoprint.events import Events
import octoprint.filemanager
#~~ GCODE file handling
@@ -22,7 +22,10 @@ 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")))
@@ -48,7 +51,7 @@ def _getFileDetails(origin, filename):
return None
def _getFileList(origin):
def _getFileList(origin, filter=None):
if origin == FileDestinations.SDCARD:
sdFileList = printer.getSdFiles()
@@ -56,6 +59,7 @@ def _getFileList(origin):
if sdFileList is not None:
for sdFile, sdSize in sdFileList:
file = {
"type": "machinecode",
"name": sdFile,
"origin": FileDestinations.SDCARD,
"refs": {
@@ -66,8 +70,41 @@ 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 entry["success"] else 0
failure += 1 if not entry["success"] else 0
if not last or entry["timestamp"] > last["timestamp"]:
last = entry
if last:
prints = dict(
success=success,
failure=failure,
last=dict(
success=last["success"],
date=last["timestamp"],
printTime=last["printTime"]
)
)
file["prints"] = prints
file.update({
"refs": {
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file["name"], _external=True),
@@ -79,11 +116,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.getSdFiles())
else:
availableFiles = gcodeManager.getAllFilenames()
return filename in availableFiles
return fileManager.file_exists(origin, filename)
@api.route("/files/<string:target>", methods=["POST"])
@@ -130,8 +165,11 @@ 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 or not (slicingManager.slicing_enabled or octoprint.filemanager.valid_file_type(futureFilename, type="gcode")):
return make_response("Can not upload file %s, wrong format?" % upload.filename, 415)
# prohibit overwriting currently selected file while it's being printed
@@ -145,7 +183,8 @@ def uploadGcodeFile(target):
Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint.
"""
if destination == FileDestinations.SDCARD:
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"):
return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint)
else:
selectAndOrPrint(filename, absFilename, destination)
@@ -160,12 +199,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):
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)):
printer.selectFile(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.get_absolute_path(FileDestinations.LOCAL, added_file), target)
done = True
sdFilename = None
if isinstance(filename, tuple):
@@ -226,7 +271,8 @@ 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)
@@ -236,7 +282,7 @@ def gcodeFileCommand(filename, target):
if command == "select":
# selects/loads a file
printAfterLoading = False
if "print" in data.keys() and data["print"]:
if "print" in data.keys() and data["print"] in valid_boolean_trues:
if not printer.isOperational():
return make_response("Printer is not operational, cannot directly start printing", 409)
printAfterLoading = True
@@ -246,9 +292,113 @@ def gcodeFileCommand(filename, target):
filenameToSelect = filename
sd = True
else:
filenameToSelect = gcodeManager.getAbsolutePath(filename)
filenameToSelect = fileManager.get_absolute_path(target, filename)
printer.selectFile(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.isPrinting() or printer.isPaused()):
# 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.isPrinting() or printer.isPaused()):
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.isOperational():
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.isOperational():
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.get_absolute_path(target, gcode_name)
printer.selectFile(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 +411,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.isPrinting() or printer.isPaused()):
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()
# delete it
if sd:
if target == FileDestinations.SDCARD:
printer.deleteSdFile(filename)
else:
gcodeManager.removeFile(filename)
fileManager.remove_file(target, filename)
return NO_CONTENT
def _getCurrentFile():
currentJob = printer.getCurrentJob()
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
@@ -0,0 +1,167 @@
# 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 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
@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 None, None, make_response("Expected content-type JSON", 400)
json_data = request.json
if not "profile" in json_data:
return None, None, 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"]
profile = dict_merge(base_profile, json_data["profile"])
if not _validate_profile(profile):
return None, None, make_response("Profile is invalid, missing obligatory values", 400)
return _overwrite_profile(profile)
@api.route("/printerprofiles/<string:identifier>", methods=["GET"])
def printerProfilesGet(identifier):
profile = printerProfileManager.get(identifier)
if profile is None:
make_response("Unknown profile: %s" % identifier, 404)
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 None, None, make_response("Expected content-type JSON", 400)
json_data = request.json
if not "profile" in json_data:
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
if not _validate_profile(new_profile):
make_response("Combined profile is invalid, missing obligatory values", 400)
try:
saved_profile = printerProfileManager.save(new_profile, allow_overwrite=True, make_default=make_default)
except Exception as e:
make_response("Could not save profile: %s" % e.message)
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
def _validate_profile(profile):
if not "name" in profile \
and "volume" in profile \
and "width" in profile["volume"] \
and "depth" in profile["volume"] \
and "height" in profile["volume"] \
and "formFactor" in profile["volume"] \
and "heatedBed" in profile \
and "extruder" in profile \
and "count" in profile["extruder"] \
and "offsets" in profile["extruder"] \
and len(profile["extruder"]["offsets"]) == profile["extruder"]["count"]:
return False
for dimension in ("width", "depth", "height"):
try:
profile["volume"][dimension] = float(profile["volume"][dimension])
except:
return False
if not profile["volume"]["formFactor"] in ("rectangular", "circular"):
return False
try:
profile["heatedBed"] = bool(profile["heatedBed"])
except:
return False
try:
profile["extruder"]["count"] = int(profile["extruder"]["count"])
except:
return False
converted_offsets = []
for offset in profile["extruder"]["offsets"]:
try:
converted_offsets.append((float(offset[0]), float(offset[0])))
except:
return False
profile["extruder"]["offsets"] = converted_offsets
return True
def _overwrite_profile(profile):
if not "id" in profile and not "name" in profile:
return None, None, make_response("Profile must contain either id or name")
elif not "name" in profile:
return None, None, make_response("Profile must contain a name")
try:
saved_profile = printerProfileManager.save(profile, allow_overwrite=False)
except Exception as e:
return None, None, make_response("Could not save profile: %s" % e.message)
return jsonify(dict(profile=_convert_profile(saved_profile)))
+28 -31
View File
@@ -9,6 +9,7 @@ import logging
from flask import request, jsonify
from octoprint.events import eventManager, Events
from octoprint.settings import settings
from octoprint.printer import getConnectionOptions
@@ -16,6 +17,8 @@ from octoprint.server import admin_permission
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access
import octoprint.plugin
#~~ settings
@@ -24,30 +27,15 @@ from octoprint.server.util.flask import restricted_access
def getSettings():
s = settings()
[movementSpeedX, movementSpeedY, movementSpeedZ, movementSpeedE] \
= s.get(["printerParameters", "movementSpeed", ["x", "y", "z", "e"]])
connectionOptions = getConnectionOptions()
return jsonify({
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"])
},
"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": {
@@ -102,7 +90,21 @@ def getSettings():
"path": s.get(["cura", "path"]),
"config": s.get(["cura", "config"])
}
})
}
def process_plugin_result(name, plugin, result):
if result:
if not "plugins" in data:
data["plugins"] = dict()
if "__enabled" in result:
del result["__enabled"]
data["plugins"][name] = result
octoprint.plugin.call_plugin(octoprint.plugin.SettingsPlugin,
"on_settings_load",
callback=process_plugin_result)
return jsonify(data)
@api.route("/settings", methods=["POST"])
@@ -118,19 +120,7 @@ def setSettings():
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 "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 "webcam" in data.keys():
@@ -204,7 +194,14 @@ def setSettings():
enabled = cura.get("enabled")
s.setBoolean(["cura", "enabled"], enabled)
s.save()
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 s.save():
eventManager().fire(Events.SETTINGS_UPDATED)
return getSettings()
+147
View File
@@ -0,0 +1,147 @@
# 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 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
@api.route("/slicing", methods=["GET"])
def slicingListAll():
default_slicer = s().get(["slicing", "defaultSlicer"])
result = dict()
for slicer in slicingManager.registered_slicers:
result[slicer] = dict(
key=slicer,
displayName=slicingManager.get_slicer(slicer).get_slicer_properties()["name"],
default=default_slicer == slicer,
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)
return jsonify(_getSlicingProfilesData(slicer))
@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 None, None, make_response("Expected content-type JSON", 400)
json_data = request.json
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 None, None, make_response("Expected content-type JSON", 400)
profile = slicingManager.load_profile(slicer, name)
if not profile:
return make_response("Profile not found", 404)
json_data = request.json
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):
profiles = slicingManager.all_profiles(slicer)
if not profiles:
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
+120
View File
@@ -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
+80 -5
View File
@@ -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):
+69 -18
View File
@@ -10,6 +10,10 @@ 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
@@ -119,12 +123,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 +136,70 @@ 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)
+30 -14
View File
@@ -15,11 +15,7 @@ from octoprint.events import Events
class PrinterStateConnection(sockjs.tornado.SockJSConnection):
EVENTS = [Events.UPDATED_FILES, Events.METADATA_ANALYSIS_FINISHED, Events.MOVIE_RENDERING, Events.MOVIE_DONE,
Events.MOVIE_FAILED, Events.SLICING_STARTED, Events.SLICING_DONE, Events.SLICING_FAILED,
Events.TRANSFER_STARTED, Events.TRANSFER_DONE]
def __init__(self, printer, gcodeManager, userManager, eventManager, session):
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session):
sockjs.tornado.SockJSConnection.__init__(self, session)
self._logger = logging.getLogger(__name__)
@@ -32,9 +28,11 @@ 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
def _getRemoteAddress(self, info):
forwardedFor = info.headers.get("X-Forwarded-For")
@@ -47,14 +45,15 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
self._logger.info("New connection from client: %s" % 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})
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._fileManager.register_slicingprogress_callback(self)
octoprint.timelapse.registerCallback(self)
self._pluginManager.register_client(self)
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
for event in PrinterStateConnection.EVENTS:
for event in octoprint.events.all_events():
self._eventManager.subscribe(event, self._onEvent)
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
@@ -62,11 +61,12 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
def on_close(self):
self._logger.info("Client connection closed")
self._printer.unregisterCallback(self)
self._gcodeManager.unregisterCallback(self)
self._fileManager.unregister_slicingprogress_callback(self)
octoprint.timelapse.unregisterCallback(self)
self._pluginManager.unregister_client(self)
self._eventManager.fire(Events.CLIENT_CLOSED)
for event in PrinterStateConnection.EVENTS:
for event in octoprint.events.all_events():
self._eventManager.unsubscribe(event, self._onEvent)
def on_message(self, message):
@@ -86,10 +86,18 @@ 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.isPrinting() or self._printer.isPaused()):
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)
@@ -105,6 +113,14 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
def sendTimelapseConfig(self, timelapseConfig):
self._emit("timelapse", timelapseConfig)
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 addLog(self, data):
with self._logBacklogMutex:
self._logBacklog.append(data)
+9 -62
View File
@@ -24,6 +24,7 @@ import tornado.httpclient
import tornado.http1connection
import tornado.iostream
import tornado.tcpserver
import tornado.util
import octoprint.util
@@ -707,80 +708,26 @@ class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionPar
class LargeResponseHandler(tornado.web.StaticFileHandler):
CHUNK_SIZE = 16 * 1024
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None):
tornado.web.StaticFileHandler.initialize(self, path, default_filename)
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
self._as_attachment = as_attachment
self._access_validation = access_validation
def get(self, path, include_body=True):
if self._access_validation is not None:
self._access_validation(self.request)
path = self.parse_url_path(path)
abspath = os.path.abspath(os.path.join(self.root, path))
# os.path.abspath strips a trailing /
# it needs to be temporarily added back for requests to root/
if not (abspath + os.path.sep).startswith(self.root):
raise tornado.web.HTTPError(403, "%s is not in root static directory", path)
if os.path.isdir(abspath) and self.default_filename is not None:
# need to look at the request.path here for when path is empty
# but there is some prefix to the path that was already
# trimmed by the routing
if not self.request.path.endswith("/"):
self.redirect(self.request.path + "/")
return
abspath = os.path.join(abspath, self.default_filename)
if not os.path.exists(abspath):
raise tornado.web.HTTPError(404)
if not os.path.isfile(abspath):
raise tornado.web.HTTPError(403, "%s is not a file", path)
stat_result = os.stat(abspath)
modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])
self.set_header("Last-Modified", modified)
mime_type, encoding = mimetypes.guess_type(abspath)
if mime_type:
self.set_header("Content-Type", mime_type)
cache_time = self.get_cache_time(path, modified, mime_type)
if cache_time > 0:
self.set_header("Expires", datetime.datetime.utcnow() +
datetime.timedelta(seconds=cache_time))
self.set_header("Cache-Control", "max-age=" + str(cache_time))
self.set_extra_headers(path)
# Check the If-Modified-Since, and don't send the result if the
# content has not been modified
ims_value = self.request.headers.get("If-Modified-Since")
if ims_value is not None:
date_tuple = email.utils.parsedate(ims_value)
if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
if if_since >= modified:
self.set_status(304)
return
if not include_body:
assert self.request.method == "HEAD"
self.set_header("Content-Length", stat_result[stat.ST_SIZE])
else:
with open(abspath, "rb") as file:
while True:
data = file.read(LargeResponseHandler.CHUNK_SIZE)
if not data:
break
self.write(data)
self.flush()
result = tornado.web.StaticFileHandler.get(self, path, include_body=include_body)
return result
def set_extra_headers(self, path):
if self._as_attachment:
self.set_header("Content-Disposition", "attachment")
@classmethod
def get_content_version(cls, abspath):
import os
import stat
return os.stat(abspath)[stat.ST_MTIME]
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
+30 -32
View File
@@ -6,31 +6,10 @@ __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 logging
import os
import watchdog.events
import octoprint.gcodefiles
import octoprint.filemanager
import octoprint.util
from octoprint.settings import settings
class UploadCleanupWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
"""
Takes care of automatically deleting metadata entries for files that get deleted from the uploads folder
"""
patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.GCODE_EXTENSIONS)
def __init__(self, gcode_manager):
watchdog.events.PatternMatchingEventHandler.__init__(self)
self._gcode_manager = gcode_manager
def on_deleted(self, event):
filename = self._gcode_manager._getBasicFilename(event.src_path)
if not filename:
return
self._gcode_manager.removeFileFromMetadata(filename)
class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
@@ -38,27 +17,28 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
Takes care of automatically "uploading" files that get added to the watched folder.
"""
patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.SUPPORTED_EXTENSIONS)
patterns = map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions())
def __init__(self, gcodeManager, printer):
def __init__(self, file_manager, printer):
watchdog.events.PatternMatchingEventHandler.__init__(self)
self._logger = logging.getLogger(__name__)
self._gcodeManager = gcodeManager
self._file_manager = file_manager
self._printer = printer
def _upload(self, path):
class WatchdogFileWrapper(object):
def __init__(self, path):
import os
self._path = path
self.filename = os.path.basename(self._path)
def save(self, target):
octoprint.util.safeRename(self._path, target)
fileWrapper = WatchdogFileWrapper(path)
file_wrapper = WatchdogFileWrapper(path)
# determine current job
currentFilename = None
@@ -71,17 +51,35 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
futureFilename = self._gcodeManager.getFutureFilename(fileWrapper)
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not octoprint.gcodefiles.isGcodeFileName(futureFilename)):
self._logger.warn("Could not add %s: Invalid file" % fileWrapper.filename)
try:
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
except:
futureFilename = None
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename, type="gcode")):
return
# prohibit overwriting currently selected file while it's being printed
if futureFilename == currentFilename and not currentOrigin == octoprint.gcodefiles.FileDestinations.SDCARD and self._printer.isPrinting() or self._printer.isPaused():
self._logger.warn("Could not add %s: Trying to overwrite file that is currently being printed" % fileWrapper.filename)
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.isPrinting() or self._printer.isPaused():
return
self._gcodeManager.addFile(fileWrapper, octoprint.gcodefiles.FileDestinations.LOCAL)
added_file = self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
file_wrapper.filename,
file_wrapper,
allow_overwrite=True)
if added_file is None:
return
slicer_name = self._file_manager.default_slicer
if octoprint.filemanager.valid_file_type(added_file, "stl") and slicer_name:
# if it's an STL we now have to slice it before we can continue
import os
name, ext = os.path.splitext(added_file)
gcode_path = name + ".gco"
self._file_manager.slice(slicer_name,
octoprint.filemanager.FileDestinations.LOCAL,
added_file,
octoprint.filemanager.FileDestinations.LOCAL,
gcode_path)
def on_created(self, event):
self._upload(event.src_path)
+140 -53
View File
@@ -41,6 +41,7 @@ default_settings = {
"host": "0.0.0.0",
"port": 5000,
"firstRun": True,
"secretKey": None,
"reverseProxy": {
"prefixHeader": "X-Script-Name",
"schemeHeader": "X-Scheme",
@@ -49,8 +50,8 @@ default_settings = {
},
"uploads": {
"maxSize": 1 * 1024 * 1024 * 1024, # 1GB
"nameSuffix": ".name",
"pathSuffix": ".path"
"nameSuffix": "name",
"pathSuffix": "path"
},
"maxSize": 100 * 1024, # 100 KB
},
@@ -91,43 +92,32 @@ default_settings = {
"timelapse_tmp": None,
"logs": None,
"virtualSd": None,
"watched": None
"watched": None,
"plugins": None,
"slicingProfiles": None,
"printerProfiles": None
},
"temperature": {
"profiles":
[
{"name": "ABS", "extruder" : 210, "bed" : 100 },
{"name": "PLA", "extruder" : 180, "bed" : 60 }
]
"profiles": [
{"name": "ABS", "extruder" : 210, "bed" : 100 },
{"name": "PLA", "extruder" : 180, "bed" : 60 }
]
},
"printerProfiles": {
"default": None,
"defaultProfile": {}
},
"printerParameters": {
"movementSpeed": {
"x": 6000,
"y": 6000,
"z": 200,
"e": 300
},
"pauseTriggers": [],
"invertAxes": [],
"numExtruders": 1,
"extruderOffsets": [
{"x": 0.0, "y": 0.0}
],
"bedDimensions": {
"x": 200.0, "y": 200.0, "r": 100
},
"defaultExtrusionLength": 5
},
"appearance": {
"name": "",
"color": "default"
},
"controls": [],
"system": {
"actions": []
},
"accessControl": {
"enabled": True,
"salt": None,
"userManager": "octoprint.users.FilebasedUserManager",
"userfile": None,
"autologinLocal": False,
@@ -139,19 +129,26 @@ default_settings = {
"path": "/default/path/to/cura",
"config": "/default/path/to/your/cura/config.ini"
},
"slicing": {
"enabled": True,
"defaultSlicer": "cura",
"defaultProfiles": None
},
"events": {
"enabled": False,
"enabled": True,
"subscriptions": []
},
"api": {
"enabled": False,
"key": ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes),
"allowCrossOrigin": False
"enabled": True,
"key": None,
"allowCrossOrigin": False,
"apps": {}
},
"terminalFilters": [
{ "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok T\d*:)" },
{ "name": "Suppress M27 requests/responses", "regex": "(Send: M27)|(Recv: SD printing byte)" }
],
"plugins": {},
"devel": {
"stylesheet": "css",
"virtualPrinter": {
@@ -163,6 +160,7 @@ default_settings = {
"includeCurrentToolInTemps": True,
"hasBed": True,
"repetierStyleTargetTemperature": False,
"smoothieTemperatureReporting": False,
"extendedSdFileList": False
}
}
@@ -179,6 +177,7 @@ class Settings(object):
self._config = None
self._dirty = False
self._mtime = None
self._init_settings_dir(basedir)
@@ -188,12 +187,19 @@ class Settings(object):
self._configfile = os.path.join(self.settings_dir, "config.yaml")
self.load(migrate=True)
if self.get(["api", "key"]) is None:
self.set(["api", "key"], ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes))
self.save(force=True)
def _init_settings_dir(self, basedir):
if basedir is not None:
self.settings_dir = basedir
else:
self.settings_dir = _resolveSettingsDir(APPNAME)
if not os.path.isdir(self.settings_dir):
os.makedirs(self.settings_dir)
def _getDefaultFolder(self, type):
folder = default_settings["folder"][type]
if folder is None:
@@ -206,6 +212,7 @@ class Settings(object):
if os.path.exists(self._configfile) and os.path.isfile(self._configfile):
with open(self._configfile, "r") as f:
self._config = yaml.safe_load(f)
self._mtime = self._last_modified()
# changed from else to handle cases where the file exists, but is empty / 0 bytes
if not self._config:
self._config = {}
@@ -214,15 +221,81 @@ class Settings(object):
self._migrateConfig()
def _migrateConfig(self):
if not self._config:
return
dirty = False
for migrate in (self._migrate_event_config, self._migrate_reverse_proxy_config):
for migrate in (self._migrate_event_config, self._migrate_reverse_proxy_config, self._migrate_printer_parameters):
dirty = migrate() or dirty
if dirty:
self.save(force=True)
def _migrate_printer_parameters(self):
default_profile = self._config["printerProfiles"]["defaultProfile"] if "printerProfiles" in self._config and "defaultProfile" in self._config["printerProfiles"] else dict()
dirty = False
if "printerParameters" in self._config:
printer_parameters = self._config["printerParameters"]
if "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters:
default_profile["axes"] = dict(x=dict(), y=dict(), z=dict(), e=dict())
if "movementSpeed" in printer_parameters:
for axis in ("x", "y", "z", "e"):
if axis in printer_parameters["movementSpeed"]:
default_profile["axes"][axis]["speed"] = printer_parameters["movementSpeed"][axis]
del self._config["printerParameters"]["movementSpeed"]
if "invertedAxes" in printer_parameters:
for axis in ("x", "y", "z", "e"):
if axis in printer_parameters["invertedAxes"]:
default_profile["axes"][axis]["inverted"] = True
del self._config["printerParameters"]["invertedAxes"]
if "numExtruders" in printer_parameters or "extruderOffsets" in printer_parameters:
if not "extruder" in default_profile:
default_profile["extruder"] = dict()
if "numExtruders" in printer_parameters:
default_profile["extruder"]["count"] = printer_parameters["numExtruders"]
del self._config["printerParameters"]["numExtruders"]
if "extruderOffsets" in printer_parameters:
extruder_offsets = []
for offset in printer_parameters["extruderOffsets"]:
if "x" in offset and "y" in offset:
extruder_offsets.append((offset["x"], offset["y"]))
default_profile["extruder"]["offsets"] = extruder_offsets
del self._config["printerParameters"]["extruderOffsets"]
if "bedDimensions" in printer_parameters:
bed_dimensions = printer_parameters["bedDimensions"]
if not "volume" in default_profile:
default_profile["volume"] = dict()
if "circular" in bed_dimensions and "r" in bed_dimensions and bed_dimensions["circular"]:
default_profile["volume"]["formFactor"] = "circular"
default_profile["volume"]["width"] = 2 * bed_dimensions["r"]
default_profile["volume"]["depth"] = default_profile["volume"]["width"]
elif "x" in bed_dimensions or "y" in bed_dimensions:
default_profile["volume"]["formFactor"] = "rectangular"
if "x" in bed_dimensions:
default_profile["volume"]["width"] = bed_dimensions["x"]
if "y" in bed_dimensions:
default_profile["volume"]["depth"] = bed_dimensions["y"]
del self._config["printerParameters"]["bedDimensions"]
dirty = True
if "appearance" in self._config:
if "name" in self._config["appearance"]:
default_profile["name"] = self._config["appearance"]["name"]
if "color" in self._config["appearance"]:
default_profile["color"] = self._config["appearance"]["color"]
del self._config["appearance"]
dirty = True
if dirty:
if not "printerProfiles" in self._config:
self._config["printerProfiles"] = dict()
self._config["printerProfiles"]["defaultProfile"] = default_profile
return dirty
def _migrate_reverse_proxy_config(self):
if "server" in self._config.keys() and ("baseUrl" in self._config["server"] or "scheme" in self._config["server"]):
prefix = ""
@@ -335,21 +408,29 @@ class Settings(object):
def save(self, force=False):
if not self._dirty and not force:
return
return False
with open(self._configfile, "wb") as configFile:
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
self._dirty = False
self.load()
return True
def _last_modified(self):
stat = os.stat(self._configfile)
return stat.st_mtime
#~~ getter
def get(self, path, asdict=False):
def get(self, path, asdict=False, defaults=None, merged=False):
import octoprint.util as util
if len(path) == 0:
return None
config = self._config
defaults = default_settings
if defaults is None:
defaults = default_settings
while len(path) > 1:
key = path.pop(0)
@@ -375,6 +456,8 @@ class Settings(object):
for key in keys:
if key in config.keys():
value = config[key]
if merged and key in defaults:
value = util.dict_merge(defaults[key], value)
elif key in defaults:
value = defaults[key]
else:
@@ -393,8 +476,8 @@ class Settings(object):
else:
return results
def getInt(self, path):
value = self.get(path)
def getInt(self, path, defaults=None):
value = self.get(path, defaults=defaults)
if value is None:
return None
@@ -404,8 +487,8 @@ class Settings(object):
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
return None
def getFloat(self, path):
value = self.get(path)
def getFloat(self, path, defaults=None):
value = self.get(path, defaults=defaults)
if value is None:
return None
@@ -415,8 +498,8 @@ class Settings(object):
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
return None
def getBoolean(self, path):
value = self.get(path)
def getBoolean(self, path, defaults=None):
value = self.get(path, defaults=defaults)
if value is None:
return None
if isinstance(value, bool):
@@ -490,12 +573,16 @@ class Settings(object):
#~~ setter
def set(self, path, value, force=False):
def set(self, path, value, force=False, defaults=None):
if len(path) == 0:
return
if self._mtime is not None and self._last_modified() != self._mtime:
self.load()
config = self._config
defaults = default_settings
if defaults is None:
defaults = default_settings
while len(path) > 1:
key = path.pop(0)
@@ -520,9 +607,9 @@ class Settings(object):
config[key] = value
self._dirty = True
def setInt(self, path, value, force=False):
def setInt(self, path, value, force=False, defaults=None):
if value is None:
self.set(path, None, force)
self.set(path, None, force=force, defaults=defaults)
return
try:
@@ -533,9 +620,9 @@ class Settings(object):
self.set(path, intValue, force)
def setFloat(self, path, value, force=False):
def setFloat(self, path, value, force=False, defaults=None):
if value is None:
self.set(path, None, force)
self.set(path, None, force=force, defaults=defaults)
return
try:
@@ -546,13 +633,13 @@ class Settings(object):
self.set(path, floatValue, force)
def setBoolean(self, path, value, force=False):
def setBoolean(self, path, value, force=False, defaults=None):
if value is None or isinstance(value, bool):
self.set(path, value, force)
self.set(path, value, force=force, defaults=defaults)
elif value.lower() in valid_boolean_trues:
self.set(path, True, force)
self.set(path, True, force=force, defaults=defaults)
else:
self.set(path, False, force)
self.set(path, False, force=force, defaults=defaults)
def setBaseFolder(self, type, path, force=False):
if type not in default_settings["folder"].keys():
View File
Whitespace-only changes.
-76
View File
@@ -1,76 +0,0 @@
import sarge
__author__ = "Ross Hendrickson savorywatt"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
import logging
import os
from octoprint.settings import settings
class CuraFactory(object):
@staticmethod
def create_slicer(path=None):
"""Utilizes the factory pattern to setup a CuraEngine object
:param path: :class: `str`
"""
if path:
return Cura(path)
current_settings = settings(init=True)
path = current_settings.get(["cura", "path"])
return Cura(path)
class Cura(object):
def __init__(self, cura_path):
if not cura_path:
raise Exception("Unable to create CuraEngine - no path specified")
self.cura_path = cura_path
self._logger = logging.getLogger(__name__)
def process_file(
self, config, gcode, file_path, call_back=None,
call_back_args=None):
"""Wraps around the main.cpp processFile method.
:param config: :class: `string` :path to a cura config file:
:param gcode: :class: `string :path to write out the gcode generated:
:param file_path: :class: `string :path to the STL to be sliced:
:note: This will spawn a thread to handle the subprocess call and allow
us to be able to have a call back
"""
import threading
def start_thread(call_back, call_back_args, call_args, cwd):
self._logger.info("Running %r in %s" % (call_args, cwd))
command = " ".join(call_args)
try:
p = sarge.run(command, cwd=cwd)
if p.returncode == 0:
call_back(*call_back_args)
else:
self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode)
call_back_args.append("Got returncode %r" % p.returncode)
call_back(*call_back_args)
except:
self._logger.exception("Could not slice via Cura, got an unknown error")
call_back_args.append("Unknown error, please consult the log file")
call_back(*call_back_args)
executable = self.cura_path
(workingDir, ignored) = os.path.split(executable)
args = [executable, '-i', config, '-s', file_path, '-o', gcode]
thread = threading.Thread(target=start_thread, args=(call_back,
call_back_args, args, workingDir))
thread.start()
@@ -1,31 +0,0 @@
import unittest
from mock import patch
from octoprint.slicers.cura import CuraFactory
from octoprint.slicers.cura import Cura
class CuraFactoryTestCase(unittest.TestCase):
def test_cura_factory(self):
fake_path = 'my/temp/path'
result = CuraFactory.create_slicer(fake_path)
self.assertEqual(fake_path, result.cura_path)
@patch('threading.Thread')
def test_cura_engine_process_file(self, thread):
path = 'rosshendrickson/workspaces/opensource/CuraEngine/'
cura = CuraFactory.create_slicer(path)
file_path = './cura/tests/test.stl'
config_path = './cura/tests/config'
gcode_filename = './cura/tests/output.gcode'
cura.process_file(config_path, gcode_filename, file_path)
self.assertTrue(thread.called)
+284
View File
@@ -0,0 +1,284 @@
# 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 octoprint.plugin
import octoprint.events
from octoprint.settings import settings
class SlicingProfile(object):
def __init__(self, slicer, name, data, display_name=None, description=None):
self.slicer = slicer
self.name = name
self.data = data
self.display_name = display_name
self.description = description
class TemporaryProfile(object):
def __init__(self, save_profile, profile, overrides=None):
self.save_profile = save_profile
self.profile = profile
self.overrides = overrides
def __enter__(self):
import tempfile
temp_profile = tempfile.NamedTemporaryFile(prefix="slicing-profile-temp-", suffix=".profile", delete=False)
temp_profile.close()
self.temp_path = temp_profile.name
self.save_profile(self.temp_path, self.profile, overrides=self.overrides)
return self.temp_path
def __exit__(self, type, value, traceback):
import os
try:
os.remove(self.temp_path)
except:
pass
class SlicingCancelled(BaseException):
pass
class SlicingManager(object):
def __init__(self, profile_path, printer_profile_manager):
self._profile_path = profile_path
self._printer_profile_manager = printer_profile_manager
self._slicers = dict()
self._slicer_names = dict()
self._load_slicers()
self._progress_callbacks = []
self._last_progress_report = None
def register_progress_callback(self, callback):
self._progress_callbacks.append(callback)
def unregister_progress_callback(self, callback):
self._progress_callbacks.remove(callback)
def _load_slicers(self):
plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
for name, plugin in plugins.items():
if plugin.is_slicer_configured():
self._slicers[plugin.get_slicer_properties()["type"]] = plugin
@property
def slicing_enabled(self):
return len(self.configured_slicers) > 0
@property
def registered_slicers(self):
return self._slicers.keys()
@property
def configured_slicers(self):
return map(lambda slicer: slicer.get_slicer_properties()["type"], filter(lambda slicer: slicer.is_slicer_configured(), self._slicers.values()))
@property
def default_slicer(self):
slicer_name = settings().get(["slicing", "defaultSlicer"])
if slicer_name in self.configured_slicers:
return slicer_name
else:
return None
def get_slicer(self, slicer, require_configured=True):
return self._slicers[slicer] if slicer in self._slicers and (not require_configured or self._slicers[slicer].is_slicer_configured()) else None
def slice(self, slicer_name, source_path, dest_path, profile_name, callback, callback_args=None, callback_kwargs=None, overrides=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None, printer_profile_id=None, position=None):
if callback_args is None:
callback_args = ()
if callback_kwargs is None:
callback_kwargs = dict()
if not slicer_name in self.configured_slicers:
if not slicer_name in self.registered_slicers:
error = "No such slicer: {slicer_name}".format(**locals())
else:
error = "Slicer not configured: {slicer_name}".format(**locals())
callback_kwargs.update(dict(_error=error))
callback(*callback_args, **callback_kwargs)
return False, error
slicer = self.get_slicer(slicer_name)
printer_profile = None
if printer_profile_id is not None:
printer_profile = self._printer_profile_manager.get(printer_profile_id)
if printer_profile is None:
printer_profile = self._printer_profile_manager.get_current_or_default()
def slicer_worker(slicer, model_path, machinecode_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs):
try:
slicer_name = slicer.get_slicer_properties()["type"]
with self.temporary_profile(slicer_name, name=profile_name, overrides=overrides) as profile_path:
ok, result = slicer.do_slice(
model_path,
printer_profile,
machinecode_path=machinecode_path,
profile_path=profile_path,
position=position,
on_progress=on_progress,
on_progress_args=on_progress_args,
on_progress_kwargs=on_progress_kwargs
)
if not ok:
callback_kwargs.update(dict(_error=result))
except SlicingCancelled:
callback_kwargs.update(dict(_cancelled=True))
finally:
callback(*callback_args, **callback_kwargs)
import threading
slicer_worker_thread = threading.Thread(target=slicer_worker,
args=(slicer, source_path, dest_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs))
slicer_worker_thread.daemon = True
slicer_worker_thread.start()
return True, None
def cancel_slicing(self, slicer_name, source_path, dest_path):
if not slicer_name in self.registered_slicers:
return
slicer = self.get_slicer(slicer_name)
slicer.cancel_slicing(dest_path)
def load_profile(self, slicer, name):
if not slicer in self.registered_slicers:
return None
try:
path = self.get_profile_path(slicer, name, must_exist=True)
except IOError:
return None
return self._load_profile_from_path(slicer, path)
def save_profile(self, slicer, name, profile, overrides=None, allow_overwrite=True, display_name=None, description=None):
if not slicer in self.registered_slicers:
return
if not isinstance(profile, SlicingProfile):
if isinstance(profile, dict):
profile = SlicingProfile(slicer, name, profile, display_name=display_name, description=description)
else:
raise ValueError("profile must be a SlicingProfile")
else:
profile.slicer = slicer
profile.name = name
if display_name is not None:
profile.display_name = display_name
if description is not None:
profile.description = description
path = self.get_profile_path(slicer, name)
self._save_profile_to_path(slicer, path, profile, overrides=overrides, allow_overwrite=allow_overwrite)
return profile
def temporary_profile(self, slicer, name=None, overrides=None):
if not slicer in self.registered_slicers:
return None
profile = self._get_default_profile(slicer)
if name:
try:
profile = self.load_profile(slicer, name)
except IOError:
profile = self._get_default_profile(slicer)
else:
if profile is None:
profile = self._get_default_profile(slicer)
return TemporaryProfile(self.get_slicer(slicer).save_slicer_profile, profile, overrides=overrides)
def delete_profile(self, slicer, name):
if not slicer in self.registered_slicers:
return None
path = self.get_profile_path(slicer, name)
if not os.path.exists(path) or not os.path.isfile(path):
return
os.remove(path)
def all_profiles(self, slicer):
if not slicer in self.registered_slicers:
return None
profiles = dict()
slicer_profile_path = self.get_slicer_profile_path(slicer)
for entry in os.listdir(slicer_profile_path):
if not entry.endswith(".profile") or entry.startswith("."):
# we are only interested in profiles and no hidden files
continue
path = os.path.join(slicer_profile_path, entry)
profile_name = entry[:-len(".profile")]
profiles[profile_name] = self._load_profile_from_path(slicer, path)
return profiles
def get_slicer_profile_path(self, slicer):
if not slicer in self.registered_slicers:
return None
path = os.path.join(self._profile_path, slicer)
if not os.path.exists(path):
os.makedirs(path)
return path
def get_profile_path(self, slicer, name, must_exist=False):
if not slicer in self.registered_slicers:
return None
if not name:
return None
name = self._sanitize(name)
path = os.path.join(self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name))
if not os.path.realpath(path).startswith(self._profile_path):
raise IOError("Path to profile {name} tried to break out of allows sub path".format(**locals()))
if must_exist and not (os.path.exists(path) and os.path.isfile(path)):
raise IOError("Profile {name} doesn't exist".format(**locals()))
return path
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 _load_profile_from_path(self, slicer, path):
return self.get_slicer(slicer).get_slicer_profile(path)
def _save_profile_to_path(self, slicer, path, profile, allow_overwrite=True, overrides=None):
self.get_slicer(slicer).save_slicer_profile(path, profile, allow_overwrite=allow_overwrite, overrides=overrides)
def _get_default_profile(self, slicer):
default_profiles = settings().get(["slicing", "defaultProfiles"])
if default_profiles and slicer in default_profiles:
try:
return self.load_profile(slicer, default_profiles[slicer])
except:
pass
return self.get_slicer(slicer).get_slicer_default_profile()
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^=icon-],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^=icon-],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^=icon-],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.activeLine truncated
+156 -49
View File
@@ -1,16 +1,7 @@
function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewModel, temperatureViewModel, controlViewModel, terminalViewModel, gcodeFilesViewModel, timelapseViewModel, gcodeViewModel, logViewModel) {
function DataUpdater(allViewModels) {
var self = this;
self.loginStateViewModel = loginStateViewModel;
self.connectionViewModel = connectionViewModel;
self.printerStateViewModel = printerStateViewModel;
self.temperatureViewModel = temperatureViewModel;
self.controlViewModel = controlViewModel;
self.terminalViewModel = terminalViewModel;
self.gcodeFilesViewModel = gcodeFilesViewModel;
self.timelapseViewModel = timelapseViewModel;
self.gcodeViewModel = gcodeViewModel;
self.logViewModel = logViewModel;
self.allViewModels = allViewModels;
self._socket = undefined;
self._autoReconnecting = false;
@@ -40,9 +31,28 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
};
self._onclose = function() {
$("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below."));
if (!$("#offline_overlay").is(":visible"))
$("#offline_overlay").show();
var handled = false;
_.each(self.allViewModels, function(viewModel) {
if (handled == true) {
return;
}
if (viewModel.hasOwnProperty("onServerDisconnect")) {
if (!viewModel.onServerDisconnect()) {
handled = true;
}
}
});
if (handled) {
return;
}
showOfflineOverlay(
gettext("Server is offline"),
gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below."),
self.reconnect
);
if (self._autoReconnectTrial < self._autoReconnectTimeouts.length) {
var timeout = self._autoReconnectTimeouts[self._autoReconnectTrial];
@@ -55,13 +65,38 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
};
self._onreconnectfailed = function() {
var handled = false;
_.each(self.allViewModels, function(viewModel) {
if (handled == true) {
return;
}
if (viewModel.hasOwnProperty("onServerDisconnect")) {
if (!viewModel.onServerDisconnect()) {
handled = true;
}
}
});
if (handled) {
return;
}
$("#offline_overlay_title").text(gettext("Server is offline"));
$("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I <strong>could not reconnect automatically</strong>, but you may try a manual reconnect using the button below."));
};
self._onmessage = function(e) {
for (var prop in e.data) {
if (!e.data.hasOwnProperty(prop)) {
continue;
}
var data = e.data[prop];
var gcodeUploadProgress = $("#gcode_upload_progress");
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
switch (prop) {
case "connected": {
// update the current UI API key and send it with any request
@@ -70,45 +105,59 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
headers: {"X-Api-Key": UI_API_KEY}
});
var oldVersion = VERSION;
VERSION = data["version"];
$("span.version").text(VERSION);
DISPLAY_VERSION = data["display_version"];
$("span.version").text(DISPLAY_VERSION);
if ($("#offline_overlay").is(":visible")) {
$("#offline_overlay").hide();
self.logViewModel.requestData();
self.timelapseViewModel.requestData();
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
self.loginStateViewModel.requestData();
self.gcodeFilesViewModel.requestData();
self.gcodeViewModel.reset();
hideOfflineOverlay();
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onDataUpdaterReconnect")) {
viewModel.onDataUpdaterReconnect();
}
});
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
}
}
if (oldVersion != VERSION) {
// version change detected, force reloading UI - use randomized delay to reduce server load in
// the case of multiple clients
var delay = 5 + Math.floor(Math.random() * 5) + 1;
setTimeout(function() {location.reload(true);}, delay * 1000);
// TODO notify about that, or show confirmation
}
break;
}
case "history": {
self.connectionViewModel.fromHistoryData(data);
self.printerStateViewModel.fromHistoryData(data);
self.temperatureViewModel.fromHistoryData(data);
self.controlViewModel.fromHistoryData(data);
self.terminalViewModel.fromHistoryData(data);
self.timelapseViewModel.fromHistoryData(data);
self.gcodeViewModel.fromHistoryData(data);
self.gcodeFilesViewModel.fromCurrentData(data);
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("fromHistoryData")) {
viewModel.fromHistoryData(data);
}
});
break;
}
case "current": {
self.connectionViewModel.fromCurrentData(data);
self.printerStateViewModel.fromCurrentData(data);
self.temperatureViewModel.fromCurrentData(data);
self.controlViewModel.fromCurrentData(data);
self.terminalViewModel.fromCurrentData(data);
self.timelapseViewModel.fromCurrentData(data);
self.gcodeViewModel.fromCurrentData(data);
self.gcodeFilesViewModel.fromCurrentData(data);
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("fromCurrentData")) {
viewModel.fromCurrentData(data);
}
});
break;
}
case "slicingProgress": {
gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(data["progress"])}));
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onSlicingProgress")) {
viewModel.onSlicingProgress(data["slicer"], data["model_path"], data["machinecode_path"], data["progress"]);
}
});
break;
}
case "event": {
@@ -116,30 +165,57 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
var payload = data["payload"];
var html = "";
var gcodeUploadProgress = $("#gcode_upload_progress");
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
console.log("Got event " + type + " with payload: " + JSON.stringify(payload));
if ((type == "UpdatedFiles" && payload.type == "gcode") || type == "MetadataAnalysisFinished") {
gcodeFilesViewModel.requestData();
if (type == "UpdatedFiles") {
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onUpdatedFiles")) {
viewModel.onUpdatedFiles(payload);
}
});
} else if (type == "MetadataAnalysisFinished") {
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onMetadataAnalysisFinished")) {
viewModel.onMetadataAnalysisFinished(payload);
}
});
} else if (type == "MovieRendering") {
new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)});
} else if (type == "MovieDone") {
new PNotify({title: gettext("Timelapse ready"), text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload)});
timelapseViewModel.requestData();
} else if (type == "MovieFailed") {
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s"), payload) + "</p>";
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "</p>";
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false});
} else if (type == "SlicingStarted") {
gcodeUploadProgress.addClass("progress-striped").addClass("active");
gcodeUploadProgressBar.css("width", "100%");
gcodeUploadProgressBar.text(gettext("Slicing ..."));
if (payload.progressAvailable) {
gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0}));
} else {
gcodeUploadProgressBar.text(gettext("Slicing ..."));
}
} else if (type == "SlicingDone") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload)});
gcodeFilesViewModel.requestData(payload.gcode);
new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload), type: "success"});
_.each(self.allViewModels, function (viewModel) {
if (viewModel.hasOwnProperty("onSlicingDone")) {
viewModel.onSlicingDone(payload);
}
});
} else if (type == "SlicingCancelled") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
_.each(self.allViewModels, function (viewModel) {
if (viewModel.hasOwnProperty("onSlicingCancelled")) {
viewModel.onSlicingCancelled(payload);
}
});
} else if (type == "SlicingFailed") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
@@ -147,6 +223,11 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload);
new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false});
_.each(self.allViewModels, function (viewModel) {
if (viewModel.hasOwnProperty("onSlicingFailed")) {
viewModel.onSlicingFailed(payload);
}
});
} else if (type == "TransferStarted") {
gcodeUploadProgress.addClass("progress-striped").addClass("active");
gcodeUploadProgressBar.css("width", "100%");
@@ -155,19 +236,45 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
new PNotify({title: gettext("Streaming done"), text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload)});
new PNotify({
title: gettext("Streaming done"),
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
type: "success"
});
gcodeFilesViewModel.requestData(payload.remote, "sdcard");
}
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onEvent")) {
viewModel.onEvent(type, payload);
}
});
break;
}
case "feedbackCommandOutput": {
self.controlViewModel.fromFeedbackCommandData(data);
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("fromFeedbackCommandData")) {
viewModel.fromFeedbackCommandData(data);
}
});
break;
}
case "timelapse": {
self.printerStateViewModel.fromTimelapseData(data);
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("fromTimelapseData")) {
viewModel.fromTimelapseData(data);
}
});
break;
}
case "plugin": {
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onDataUpdaterPluginMessage")) {
viewModel.onDataUpdaterPluginMessage(data.plugin, data.data);
}
})
}
}
}
};
+60 -3
View File
@@ -11,7 +11,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
self.searchFunction = undefined;
self.allItems = [];
0
self.items = ko.observableArray([]);
self.pageSize = ko.observable(filesPerPage);
self.currentPage = ko.observable(0);
@@ -52,6 +52,19 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
return matcher(self.selectedItem());
};
self.removeItem = function(matcher) {
var item = self.getItem(matcher, true);
if (item === undefined) {
return;
}
var index = self.allItems.indexOf(item);
if (index > -1) {
self.allItems.splice(index, 1);
self._updateItems();
}
};
//~~ pagination
self.paginatedItems = ko.dependentObservable(function() {
@@ -131,8 +144,13 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
}
};
self.getItem = function(matcher) {
var itemList = self.items();
self.getItem = function(matcher, all) {
var itemList;
if (all !== undefined && all === true) {
itemList = self.allItems;
} else {
itemList = self.items();
}
for (var i = 0; i < itemList.length; i++) {
if (matcher(itemList[i])) {
return itemList[i];
@@ -359,3 +377,42 @@ function pnotifyAdditionalInfo(inner) {
+ '<div class="pnotify_more_container hide">' + inner + '</div>'
+ '</div>';
}
function ping(url, callback) {
var img = new Image();
var calledBack = false;
img.onload = function() {
callback(true);
calledBack = true;
};
img.onerror = function() {
if (!calledBack) {
callback(true);
calledBack = true;
}
};
img.src = url;
setTimeout(function() {
if (!calledBack) {
callback(false);
calledBack = true;
}
}, 1500);
}
function showOfflineOverlay(title, message, reconnectCallback) {
if (title == undefined) {
title = gettext("Server is offline");
}
$("#offline_overlay_title").text(title);
$("#offline_overlay_message").html(message);
$("#offline_overlay_reconnect").click(reconnectCallback);
if (!$("#offline_overlay").is(":visible"))
$("#offline_overlay").show();
}
function hideOfflineOverlay() {
$("#offline_overlay").hide();
}
+170 -65
View File
@@ -25,35 +25,6 @@ $(function() {
gettext("Transfering file to SD")
];
//~~ Initialize view models
var loginStateViewModel = new LoginStateViewModel();
var usersViewModel = new UsersViewModel(loginStateViewModel);
var settingsViewModel = new SettingsViewModel(loginStateViewModel, usersViewModel);
var connectionViewModel = new ConnectionViewModel(loginStateViewModel, settingsViewModel);
var timelapseViewModel = new TimelapseViewModel(loginStateViewModel);
var printerStateViewModel = new PrinterStateViewModel(loginStateViewModel, timelapseViewModel);
var appearanceViewModel = new AppearanceViewModel(settingsViewModel);
var temperatureViewModel = new TemperatureViewModel(loginStateViewModel, settingsViewModel);
var controlViewModel = new ControlViewModel(loginStateViewModel, settingsViewModel);
var terminalViewModel = new TerminalViewModel(loginStateViewModel, settingsViewModel);
var gcodeFilesViewModel = new GcodeFilesViewModel(printerStateViewModel, loginStateViewModel);
var gcodeViewModel = new GcodeViewModel(loginStateViewModel, settingsViewModel);
var navigationViewModel = new NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel);
var logViewModel = new LogViewModel(loginStateViewModel);
var dataUpdater = new DataUpdater(
loginStateViewModel,
connectionViewModel,
printerStateViewModel,
temperatureViewModel,
controlViewModel,
terminalViewModel,
gcodeFilesViewModel,
timelapseViewModel,
gcodeViewModel,
logViewModel
);
PNotify.prototype.options.styling = "bootstrap2";
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
@@ -69,15 +40,92 @@ $(function() {
});
//~~ Show settings - to ensure centered
var settingsDialog = $('#settings_dialog');
settingsDialog.on('show', function() {
_.each(allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onSettingsShown")) {
viewModel.onSettingsShown();
}
});
});
settingsDialog.on('hidden', function() {
_.each(allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onSettingsHidden")) {
viewModel.onSettingsHidden();
}
});
});
$('#navbar_show_settings').click(function() {
$('#settings_dialog').modal()
.css({
width: 'auto',
'margin-left': function() { return -($(this).width() /2); }
});
settingsDialog.modal()
.css({
width: 'auto',
'margin-left': function() { return -($(this).width() /2); }
});
return false;
});
//~~ Initialize view models
var loginStateViewModel = new LoginStateViewModel();
var printerProfilesViewModel = new PrinterProfilesViewModel();
var usersViewModel = new UsersViewModel(loginStateViewModel);
var timelapseViewModel = new TimelapseViewModel(loginStateViewModel);
var printerStateViewModel = new PrinterStateViewModel(loginStateViewModel, timelapseViewModel);
var settingsViewModel = new SettingsViewModel(loginStateViewModel, usersViewModel, printerProfilesViewModel);
var connectionViewModel = new ConnectionViewModel(loginStateViewModel, settingsViewModel, printerProfilesViewModel);
var appearanceViewModel = new AppearanceViewModel(settingsViewModel, printerStateViewModel);
var temperatureViewModel = new TemperatureViewModel(loginStateViewModel, settingsViewModel);
var controlViewModel = new ControlViewModel(loginStateViewModel, settingsViewModel);
var terminalViewModel = new TerminalViewModel(loginStateViewModel, settingsViewModel);
var slicingViewModel = new SlicingViewModel(loginStateViewModel, printerProfilesViewModel);
var gcodeFilesViewModel = new GcodeFilesViewModel(printerStateViewModel, loginStateViewModel, slicingViewModel);
var gcodeViewModel = new GcodeViewModel(loginStateViewModel, settingsViewModel);
var navigationViewModel = new NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel);
var logViewModel = new LogViewModel(loginStateViewModel);
var viewModelMap = {
loginStateViewModel: loginStateViewModel,
printerProfilesViewModel: printerProfilesViewModel,
usersViewModel: usersViewModel,
settingsViewModel: settingsViewModel,
connectionViewModel: connectionViewModel,
timelapseViewModel: timelapseViewModel,
printerStateViewModel: printerStateViewModel,
appearanceViewModel: appearanceViewModel,
temperatureViewModel: temperatureViewModel,
controlViewModel: controlViewModel,
terminalViewModel: terminalViewModel,
gcodeFilesViewModel: gcodeFilesViewModel,
gcodeViewModel: gcodeViewModel,
navigationViewModel: navigationViewModel,
logViewModel: logViewModel,
slicingViewModel: slicingViewModel
};
var allViewModels = _.values(viewModelMap);
var additionalViewModels = [];
_.each(ADDITIONAL_VIEWMODELS, function(viewModel) {
var viewModelClass = viewModel[0];
var viewModelParameters = viewModel[1];
var viewModelBindTarget = viewModel[2];
var constructorParameters = [];
_.each(viewModelParameters, function(parameter) {
if (_.has(viewModelMap, parameter)) {
constructorParameters.push(viewModelMap[parameter]);
} else {
constructorParameters.push(undefined);
}
});
var viewModelInstance = new viewModelClass(constructorParameters);
additionalViewModels.push([viewModelInstance, viewModelBindTarget]);
allViewModels.push(viewModelInstance);
});
var dataUpdater = new DataUpdater(allViewModels);
//~~ Temperature
$('#tabs a[data-toggle="tab"]').on('shown', function (e) {
@@ -110,6 +158,10 @@ $(function() {
}
gcodeFilesViewModel.requestData(filename, location);
if (_.endsWith(filename.toLowerCase(), ".stl")) {
slicingViewModel.show(location, filename);
}
if (data.result.done) {
$("#gcode_upload_progress .bar").css("width", "0%");
$("#gcode_upload_progress").removeClass("progress-striped").removeClass("active");
@@ -248,7 +300,7 @@ $(function() {
var foundLocal = false;
var foundSd = false;
var found = false
var found = false;
var node = e.target;
do {
if (dropZoneLocal && node === dropZoneLocal[0]) {
@@ -287,9 +339,6 @@ $(function() {
}, 100);
});
//~~ Offline overlay
$("#offline_overlay_reconnect").click(function() {dataUpdater.reconnect()});
//~~ Underscore setup
_.mixin(_.str.exports());
@@ -331,37 +380,93 @@ $(function() {
}
};
ko.applyBindings(connectionViewModel, document.getElementById("connection_accordion"));
ko.applyBindings(printerStateViewModel, document.getElementById("state_accordion"));
ko.applyBindings(gcodeFilesViewModel, document.getElementById("files_accordion"));
ko.applyBindings(temperatureViewModel, document.getElementById("temp"));
ko.applyBindings(controlViewModel, document.getElementById("control"));
ko.applyBindings(terminalViewModel, document.getElementById("term"));
var gcode = document.getElementById("gcode");
if (gcode) {
gcodeViewModel.initialize();
ko.applyBindings(gcodeViewModel, gcode);
}
ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog"));
ko.applyBindings(navigationViewModel, document.getElementById("navbar"));
ko.applyBindings(appearanceViewModel, document.getElementsByTagName("head")[0]);
ko.applyBindings(printerStateViewModel, document.getElementById("drop_overlay"));
ko.applyBindings(logViewModel, document.getElementById("logs"));
ko.bindingHandlers.qrcode = {
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var val = ko.utils.unwrapObservable(valueAccessor());
var timelapseElement = document.getElementById("timelapse");
if (timelapseElement) {
ko.applyBindings(timelapseViewModel, timelapseElement);
}
var defaultOptions = {
text: "",
size: 200,
fill: "#000",
background: null,
label: "",
fontname: "sans",
fontcolor: "#000",
radius: 0,
ecLevel: "L"
};
var options = {};
_.each(defaultOptions, function(value, key) {
options[key] = ko.utils.unwrapObservable(val[key]) || value;
});
$(element).empty().qrcode(options);
}
};
ko.bindingHandlers.invisible = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
if (!valueAccessor()) return;
ko.bindingHandlers.style.update(element, function() {
return { visibility: 'hidden' };
})
}
};
settingsViewModel.requestData(function() {
ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog"));
ko.applyBindings(connectionViewModel, document.getElementById("connection_accordion"));
ko.applyBindings(printerStateViewModel, document.getElementById("state_accordion"));
ko.applyBindings(gcodeFilesViewModel, document.getElementById("files_accordion"));
ko.applyBindings(temperatureViewModel, document.getElementById("temp"));
ko.applyBindings(controlViewModel, document.getElementById("control"));
ko.applyBindings(terminalViewModel, document.getElementById("term"));
var gcode = document.getElementById("gcode");
if (gcode) {
gcodeViewModel.initialize();
ko.applyBindings(gcodeViewModel, gcode);
}
//ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog"));
ko.applyBindings(navigationViewModel, document.getElementById("navbar"));
ko.applyBindings(appearanceViewModel, document.getElementsByTagName("head")[0]);
ko.applyBindings(printerStateViewModel, document.getElementById("drop_overlay"));
ko.applyBindings(logViewModel, document.getElementById("logs"));
var timelapseElement = document.getElementById("timelapse");
if (timelapseElement) {
ko.applyBindings(timelapseViewModel, timelapseElement);
}
ko.applyBindings(slicingViewModel, document.getElementById("slicing_configuration_dialog"));
// apply bindings and signal startup
_.each(additionalViewModels, function(additionalViewModel) {
if (additionalViewModel[1] === undefined) {
return;
}
if (additionalViewModel[0].hasOwnProperty("onBeforeBinding")) {
additionalViewModel[0].onBeforeBinding();
}
// model instance, target container
ko.applyBindings(additionalViewModel[0], additionalViewModel[1]);
if (additionalViewModel[0].hasOwnProperty("onAfterBinding")) {
additionalViewModel[0].onAfterBinding();
}
});
});
//~~ startup commands
loginStateViewModel.requestData();
connectionViewModel.requestData();
controlViewModel.requestData();
gcodeFilesViewModel.requestData();
timelapseViewModel.requestData();
settingsViewModel.requestData();
logViewModel.requestData();
_.each(allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onStartup")) {
viewModel.onStartup();
}
});
loginStateViewModel.subscribe(function(change, data) {
if ("login" == change) {
@@ -1,20 +1,33 @@
function AppearanceViewModel(settingsViewModel) {
function AppearanceViewModel(settingsViewModel, printerStateViewModel) {
var self = this;
self.name = settingsViewModel.appearance_name;
self.color = settingsViewModel.appearance_color;
self.settings = settingsViewModel;
self.printerState = printerStateViewModel;
self.connected = ko.observable(false);
self.printerState.isErrorOrClosed.subscribe(function() {
self.connected(!self.printerState.isErrorOrClosed());
});
self.brand = ko.computed(function() {
if (self.name())
return gettext("OctoPrint") + ": " + self.name();
if (self.settings.printerProfiles.currentProfileData().name() && self.connected())
return gettext("OctoPrint") + ": " + self.settings.printerProfiles.currentProfileData().name();
else
return gettext("OctoPrint");
});
self.title = ko.computed(function() {
if (self.name())
return self.name() + " [" + gettext("OctoPrint") + "]";
if (self.settings.printerProfiles.currentProfileData().name() && self.connected())
return self.settings.printerProfiles.currentProfileData().name() + " [" + gettext("OctoPrint") + "]";
else
return gettext("OctoPrint");
});
self.color = ko.computed(function() {
if (self.settings.printerProfiles.currentProfileData().color() && self.connected())
return self.settings.printerProfiles.currentProfileData().color();
else
return "default";
});
}
@@ -1,13 +1,30 @@
function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
function ConnectionViewModel(loginStateViewModel, settingsViewModel, printerProfilesViewModel) {
var self = this;
self.loginState = loginStateViewModel;
self.settings = settingsViewModel;
self.printerProfiles = printerProfilesViewModel;
self.printerProfiles.profiles.items.subscribe(function() {
var allProfiles = self.printerProfiles.profiles.items();
var printerOptions = [];
_.each(allProfiles, function(profile) {
printerOptions.push({id: profile.id, name: profile.name});
});
self.printerOptions(printerOptions);
});
self.printerProfiles.currentProfile.subscribe(function() {
self.selectedPrinter(self.printerProfiles.currentProfile());
});
self.portOptions = ko.observableArray(undefined);
self.baudrateOptions = ko.observableArray(undefined);
self.printerOptions = ko.observableArray(undefined);
self.selectedPort = ko.observable(undefined);
self.selectedBaudrate = ko.observable(undefined);
self.selectedPrinter = ko.observable(undefined);
self.saveSettings = ko.observable(undefined);
self.autoconnect = ko.observable(undefined);
@@ -24,7 +41,7 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
return gettext("Connect");
else
return gettext("Disconnect");
})
});
self.previousIsOperational = undefined;
@@ -37,13 +54,14 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
self.fromResponse(response);
}
})
}
};
self.fromResponse = function(response) {
var ports = response.options.ports;
var baudrates = response.options.baudrates;
var portPreference = response.options.portPreference;
var baudratePreference = response.options.baudratePreference;
var printerPreference = response.options.printerProfilePreference;
self.portOptions(ports);
self.baudrateOptions(baudrates);
@@ -52,17 +70,19 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
self.selectedPort(portPreference);
if (!self.selectedBaudrate() && baudrates && baudrates.indexOf(baudratePreference) >= 0)
self.selectedBaudrate(baudratePreference);
if (!self.selectedPrinter() && printerProfiles && printerProfiles.indexOf(printerPreference) >= 0)
self.selectedPrinter(printerPreference);
self.saveSettings(false);
}
};
self.fromHistoryData = function(data) {
self._processStateData(data.state);
}
};
self.fromCurrentData = function(data) {
self._processStateData(data.state);
}
};
self._processStateData = function(data) {
self.previousIsOperational = self.isOperational();
@@ -85,7 +105,7 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
connectionTab.collapse("show");
}
}
}
};
self.connect = function() {
if (self.isErrorOrClosed()) {
@@ -93,6 +113,7 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
"command": "connect",
"port": self.selectedPort(),
"baudrate": self.selectedBaudrate(),
"printerProfile": self.selectedPrinter(),
"autoconnect": self.settings.serial_autoconnect()
};
@@ -106,7 +127,8 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data),
success: function(response) {
self.settings.requestData()
self.settings.requestData();
self.settings.printerProfiles.requestData();
}
});
} else {
@@ -119,5 +141,9 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
data: JSON.stringify({"command": "disconnect"})
})
}
}
};
self.onStartup = function() {
self.requestData();
};
}
@@ -26,10 +26,14 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
self.feedbackControlLookup = {};
self.settings.printer_numExtruders.subscribe(function(oldVal, newVal) {
self.settings.printerProfiles.currentProfileData.subscribe(function() {
self._updateExtruderCount();
self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._updateExtruderCount);
});
self._updateExtruderCount = function() {
var tools = [];
var numExtruders = self.settings.printer_numExtruders();
var numExtruders = self.settings.printerProfiles.currentProfileData().extruder.count();
if (numExtruders > 1) {
// multiple extruders
for (var extruder = 0; extruder < numExtruders; extruder++) {
@@ -45,7 +49,7 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
}
self.tools(tools);
});
};
self.fromCurrentData = function(data) {
self._processStateData(data.state);
@@ -190,6 +194,15 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
if (!command)
return;
var callback = function (){
$.ajax({
url: API_BASEURL + "printer/command",
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data)
})
}
var data = undefined;
if (command.type == "command" || command.type == "parametric_command" || command.type == "feedback_command") {
// single command
@@ -207,16 +220,25 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
}
}
if (command.confirm) {
var confirmationDialog = $("#confirmation_dialog");
var confirmationDialogAck = $(".confirmation_dialog_acknowledge", confirmationDialog);
$(".confirmation_dialog_message", confirmationDialog).text(command.confirm);
confirmationDialogAck.unbind("click");
confirmationDialogAck.bind("click", function(e) {
e.preventDefault();
$("#confirmation_dialog").modal("hide");
callback();
});
confirmationDialog.modal("show");
} else {
callback();
}
if (data === undefined)
return;
$.ajax({
url: API_BASEURL + "printer/command",
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data)
})
};
self.displayMode = function(customControl) {
@@ -236,6 +258,9 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
default:
return "customControls_emptyTemplate";
}
}
};
self.onStartup = function() {
self.requestData();
};
}
+49 -16
View File
@@ -1,8 +1,9 @@
function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel, slicingViewModel) {
var self = this;
self.printerState = printerStateViewModel;
self.loginState = loginStateViewModel;
self.slicing = slicingViewModel;
self.isErrorOrClosed = ko.observable(undefined);
self.isOperational = ko.observable(undefined);
@@ -57,11 +58,17 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
},
"local": function(file) {
return !(file["origin"] && file["origin"] == "sdcard");
},
"machinecode": function(file) {
return file["type"] && file["type"] == "machinecode";
},
"model": function(file) {
return file["type"] && file["type"] == "model";
}
},
"name",
[],
[["sd", "local"]],
["machinecode"],
[["sd", "local"], ["machinecode", "model"]],
0
);
@@ -152,8 +159,7 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
self.highlightFilename(self.printerState.filename());
};
self.loadFile = function(filename, printAfterLoad) {
var file = self.listHelper.getItem(function(item) {return item.name == filename});
self.loadFile = function(file, printAfterLoad) {
if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return;
$.ajax({
@@ -165,17 +171,9 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
});
};
self.removeFile = function(filename) {
var file = self.listHelper.getItem(function(item) {return item.name == filename});
self.removeFile = function(file) {
if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return;
var origin;
if (file.origin === undefined) {
origin = "local";
} else {
origin = file.origin;
}
$.ajax({
url: file.refs.resource,
type: "DELETE",
@@ -185,6 +183,12 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
});
};
self.sliceFile = function(file) {
if (!file) return;
self.slicing.show(file.origin, file.name);
};
self.initSdCard = function() {
self._sendSdCommand("init");
};
@@ -230,8 +234,12 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
return data["prints"]["last"]["success"] ? "text-success" : "text-error";
};
self.templateFor = function(data) {
return "files_template_" + data.type;
};
self.getEntryId = function(data) {
return "gcode_file_" + md5(data["name"] + ":" + data["origin"]);
return "gcode_file_" + md5(data["origin"] + ":" + data["name"]);
};
self.getEntryElement = function(data) {
@@ -245,7 +253,7 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
};
self.enableRemove = function(data) {
return self.loginState.isUser() && !(self.listHelper.isSelected(data) && (self.isPrinting() || self.isPaused()));
return self.loginState.isUser() && !_.contains(self.printerState.busyFiles(), data.origin + ":" + data.name);
};
self.enableSelect = function(data, printAfterSelect) {
@@ -253,6 +261,10 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
return isLoadActionPossible && !self.listHelper.isSelected(data);
};
self.enableSlicing = function(data) {
return self.loginState.isUser() && !(self.isPrinting() || self.isPaused());
};
self.enableAdditionalData = function(data) {
return data["gcodeAnalysis"] || data["prints"] && data["prints"]["last"];
};
@@ -304,5 +316,26 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
}
};
self.onDataUpdaterReconnect = function() {
self.requestData();
};
self.onStartup = function() {
self.requestData();
};
self.onUpdatedFiles = function(payload) {
if (payload.type == "gcode") {
self.requestData();
}
};
self.onSlicingDone = function(payload) {
self.requestData();
};
self.onMetadataAnalysisFinished = function(payload) {
self.requestData();
};
}
+134 -46
View File
@@ -95,42 +95,103 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions);
// subscribe to relevant printer settings...
self.settings.printer_extruderOffsets.subscribe(function() {
if (!self.enabled) return;
if (!self.settings.printer_extruderOffsets()) return;
GCODE.ui.updateOptions({
reader: {
toolOffsets: self.settings.printer_extruderOffsets()
}
});
});
self.settings.printer_bedDimensions.subscribe(function() {
self.settings.printerProfiles.currentProfileData.subscribe(function() {
if (!self.enabled) return;
var bedDimensions = self.settings.printer_bedDimensions();
if (!bedDimensions || (!bedDimensions.hasOwnProperty("x") && !bedDimensions.hasOwnProperty("y") && !bedDimensions.hasOwnProperty("r"))) return;
var currentProfileData = self.settings.printerProfiles.currentProfileData();
if (!currentProfileData) return;
GCODE.ui.updateOptions({
renderer: {
bed: bedDimensions
}
});
});
self.settings.printer_invertAxes.subscribe(function() {
if (!self.enabled) return;
if (!self.settings.printer_invertAxes()) return;
var updatedOptions = {
reader: {},
renderer: {}
};
GCODE.ui.updateOptions({
renderer: {
invertAxes: {
x: self.settings.printer_invertX(),
y: self.settings.printer_invertY()
}
}
});
var toolOffsets = self._retrieveToolOffsets(currentProfileData);
if (toolOffsets) {
updatedOptions["reader"]["toolOffsets"] = toolOffsets;
}
var bedDimensions = self._retrieveBedDimensions(currentProfileData);
if (toolOffsets) {
updatedOptions["renderer"]["bed"] = bedDimensions;
}
var axesConfiguration = self._retrieveAxesConfiguration(currentProfileData);
if (axesConfiguration) {
updatedOptions["renderer"]["invertAxes"] = axesConfiguration;
}
GCODE.ui.updateOptions(updatedOptions);
});
self._retrieveBedDimensions = function(currentProfileData) {
if (currentProfileData == undefined) {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
if (currentProfileData && currentProfileData.volume && currentProfileData.volume.formFactor() && currentProfileData.volume.width() && currentProfileData.volume.depth()) {
var x = undefined, y = undefined, r = undefined, circular = false;
var formFactor = currentProfileData.volume.formFactor();
if (formFactor == "circular") {
r = currentProfileData.volume.width() / 2;
circular = true;
} else {
x = currentProfileData.volume.width();
y = currentProfileData.volume.depth();
}
return {
x: x,
y: y,
r: r,
circular: circular
};
} else {
return undefined;
}
};
self._retrieveToolOffsets = function(currentProfileData) {
if (currentProfileData == undefined) {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets()) {
var offsets = [];
_.each(currentProfileData.extruder.offsets(), function(offset) {
offsets.push({x: offset[0], y: offset[1]})
});
return offsets;
} else {
return undefined;
}
};
self._retrieveAxesConfiguration = function(currentProfileData) {
if (currentProfileData == undefined) {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
if (currentProfileData && currentProfileData.axes) {
var invertX = false, invertY = false;
if (currentProfileData.axes.x) {
invertX = currentProfileData.axes.x.inverted();
}
if (currentProfileData.axes.y) {
invertY = currentProfileData.axes.y.inverted();
}
return {
x: invertX,
y: invertY
}
} else {
return undefined;
}
};
self.loadedFilename = undefined;
self.loadedFileDate = undefined;
self.status = 'idle';
@@ -146,21 +207,14 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
self.currentLayer = undefined;
self.currentCommand = undefined;
self.printerProfileChanged = false;
self.initialize = function() {
self._configureLayerSlider();
self._configureLayerCommandSlider();
self.settings.requestData(function() {
GCODE.ui.init({
container: "#gcode_canvas",
onProgress: self._onProgress,
onModelLoaded: self._onModelLoaded,
onLayerSelected: self._onLayerSelected,
bed: self.settings.printer_bedDimensions(),
toolOffsets: self.settings.printer_extruderOffsets()
});
self.synchronizeOptions();
self.enabled = true;
self.initGcodeUi();
});
};
@@ -171,6 +225,19 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
self.clear();
};
self.initGcodeUi = function() {
GCODE.ui.init({
container: "#gcode_canvas",
onProgress: self._onProgress,
onModelLoaded: self._onModelLoaded,
onLayerSelected: self._onLayerSelected,
bed: self._retrieveBedDimensions(),
toolOffsets: self._retrieveToolOffsets(),
invertAxes: self._retrieveAxesConfiguration()
});
self.synchronizeOptions();
};
self.clear = function() {
GCODE.ui.clear();
};
@@ -332,7 +399,7 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
}
output.push(gettext("Estimated print time") + ": " + formatDuration(model.printTime));
output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext(printed) + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
self.ui_modelInfo(output.join("<br>"));
@@ -354,11 +421,13 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
output.push(gettext("Layer number") + ": " + (layer.number + 1));
output.push(gettext("Layer height") + " (mm): " + layer.height);
output.push(gettext("GCODE commands in layer") + ": " + layer.commands);
if (layer.filament.length == 1) {
output.push(gettext("Filament used by layer") + ": " + layer.filament[0].toFixed(2) + "mm");
} else {
for (var i = 0; i < layer.filament.length; i++) {
output.push(gettext("Filament used by layer") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
if (layer.filament != undefined) {
if (layer.filament.length == 1) {
output.push(gettext("Filament used by layer") + ": " + layer.filament[0].toFixed(2) + "mm");
} else {
for (var i = 0; i < layer.filament.length; i++) {
output.push(gettext("Filament used by layer") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
}
}
}
output.push(gettext("Print time for layer") + ": " + formatDuration(layer.printTime));
@@ -405,4 +474,23 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]);
};
self.onEvent = function(type, payload) {
switch (type) {
case "PrinterProfileSelected": {
break;
}
case "PrinterProfileModified": {
if (payload.hasOwnProperty("profile") && payload.profile == self.settings.printerProfiles.currentProfileData().id) {
self.initGcodeUi();
}
break;
}
}
};
self.onDataUpdaterReconnect = function() {
self.reset();
}
}
+10 -2
View File
@@ -49,7 +49,7 @@ function LogViewModel(loginStateViewModel) {
return;
self.listHelper.updateItems(files);
}
};
self.removeFile = function(filename) {
$.ajax({
@@ -58,5 +58,13 @@ function LogViewModel(loginStateViewModel) {
dataType: "json",
success: self.requestData
});
}
};
self.onDataUpdaterReconnect = function() {
self.requestData();
};
self.onStartup = function() {
self.requestData();
};
}
@@ -10,7 +10,7 @@ function LoginStateViewModel() {
self.userMenuText = ko.computed(function() {
if (self.loggedIn()) {
return "\"" + self.username() + "\"";
return self.username();
} else {
return gettext("Login");
}
@@ -29,7 +29,7 @@ function LoginStateViewModel() {
data: {"passive": true},
success: self.fromResponse
})
}
};
self.fromResponse = function(response) {
if (response && response.name) {
@@ -85,5 +85,13 @@ function LoginStateViewModel() {
self.fromResponse(response);
}
})
}
};
self.onDataUpdaterReconnect = function() {
self.requestData();
};
self.onStartup = function() {
self.requestData();
};
}
@@ -0,0 +1,321 @@
function PrinterProfilesViewModel() {
var self = this;
self._cleanProfile = function() {
return {
id: "",
name: "",
model: "",
color: "default",
volume: {
formFactor: "rectangular",
width: 200,
depth: 200,
height: 200
},
heatedBed: false,
axes: {
x: {speed: 6000, inverted: false},
y: {speed: 6000, inverted: false},
z: {speed: 200, inverted: false},
e: {speed: 300, inverted: false}
},
extruder: {
count: 1,
offsets: [
[0,0]
],
nozzleDiameter: 0.4
}
}
};
self.profiles = new ItemListHelper(
"printerProfiles",
{
"name": function(a, b) {
// sorts ascending
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
return 0;
}
},
{},
"name",
[],
[],
5
);
self.defaultProfile = ko.observable();
self.currentProfile = ko.observable();
self.currentProfileData = ko.observable(ko.mapping.fromJS(self._cleanProfile()));
self.editorNew = ko.observable(false);
self.editorName = ko.observable();
self.editorColor = ko.observable();
self.editorIdentifier = ko.observable();
self.editorModel = ko.observable();
self.editorVolumeWidth = ko.observable();
self.editorVolumeDepth = ko.observable();
self.editorVolumeHeight = ko.observable();
self.editorVolumeFormFactor = ko.observable();
self.editorHeatedBed = ko.observable();
self.editorNozzleDiameter = ko.observable();
self.editorExtruders = ko.observable();
self.editorExtruderOffsets = ko.observableArray();
self.editorAxisXSpeed = ko.observable();
self.editorAxisYSpeed = ko.observable();
self.editorAxisZSpeed = ko.observable();
self.editorAxisESpeed = ko.observable();
self.editorAxisXInverted = ko.observable(false);
self.editorAxisYInverted = ko.observable(false);
self.editorAxisZInverted = ko.observable(false);
self.editorAxisEInverted = ko.observable(false);
self.availableColors = ko.observable([
{key: "default", name: gettext("default")},
{key: "red", name: gettext("red")},
{key: "orange", name: gettext("orange")},
{key: "yellow", name: gettext("yellow")},
{key: "green", name: gettext("green")},
{key: "blue", name: gettext("blue")},
{key: "black", name: gettext("black")}
]);
self.koEditorExtruderOffsets = ko.computed(function() {
var extruderOffsets = self.editorExtruderOffsets();
var numExtruders = self.editorExtruders();
if (!numExtruders) {
numExtruders = 1;
}
if (numExtruders > extruderOffsets.length) {
for (var i = extruderOffsets.length; i < numExtruders; i++) {
extruderOffsets[i] = {
x: ko.observable(0),
y: ko.observable(0)
}
}
self.editorExtruderOffsets(extruderOffsets);
}
return extruderOffsets.slice(0, numExtruders);
});
self.makeDefault = function(data) {
var profile = {
id: data.id,
default: true
};
self.updateProfile(profile);
};
self.requestData = function() {
$.ajax({
url: API_BASEURL + "printerprofiles",
type: "GET",
dataType: "json",
success: self.fromResponse
})
};
self.fromResponse = function(data) {
var items = [];
var defaultProfile = undefined;
var currentProfile = undefined;
var currentProfileData = undefined;
_.each(data.profiles, function(entry) {
if (entry.default) {
defaultProfile = entry.id;
}
if (entry.current) {
currentProfile = entry.id;
currentProfileData = ko.mapping.fromJS(entry, self.currentProfileData);
}
entry["isdefault"] = ko.observable(entry.default);
entry["iscurrent"] = ko.observable(entry.current);
items.push(entry);
});
self.profiles.updateItems(items);
self.defaultProfile(defaultProfile);
self.currentProfile(currentProfile);
self.currentProfileData(currentProfileData);
};
self.addProfile = function(callback) {
var profile = self._editorData();
$.ajax({
url: API_BASEURL + "printerprofiles",
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({profile: profile}),
success: function() {
if (callback !== undefined) {
callback();
}
self.requestData();
}
});
};
self.removeProfile = function(data) {
$.ajax({
url: data.resource,
type: "DELETE",
dataType: "json",
success: self.requestData
})
};
self.updateProfile = function(profile, callback) {
if (profile == undefined) {
profile = self._editorData();
}
$.ajax({
url: API_BASEURL + "printerprofiles/" + profile.id,
type: "PATCH",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({profile: profile}),
success: function() {
if (callback !== undefined) {
callback();
}
self.requestData();
}
});
};
self.showEditProfileDialog = function(data) {
var add = false;
if (data == undefined) {
data = self._cleanProfile();
add = true;
}
self.editorNew(add);
self.editorIdentifier(data.id);
self.editorName(data.name);
self.editorColor(data.color);
self.editorModel(data.model);
self.editorVolumeWidth(data.volume.width);
self.editorVolumeDepth(data.volume.depth);
self.editorVolumeHeight(data.volume.height);
self.editorVolumeFormFactor(data.volume.formFactor);
self.editorHeatedBed(data.volume.heatedBed);
self.editorNozzleDiameter(data.extruder.nozzleDiameter);
self.editorExtruders(data.extruder.count);
var offsets = [];
_.each(data.extruder.offsets, function(offset) {
offsets.push({
x: ko.observable(offset[0]),
y: ko.observable(offset[1])
});
});
self.editorExtruderOffsets(offsets);
self.editorAxisXSpeed(data.axes.x.speed);
self.editorAxisXInverted(data.axes.x.inverted);
self.editorAxisYSpeed(data.axes.y.speed);
self.editorAxisYInverted(data.axes.y.inverted);
self.editorAxisZSpeed(data.axes.z.speed);
self.editorAxisZInverted(data.axes.z.inverted);
self.editorAxisESpeed(data.axes.e.speed);
self.editorAxisEInverted(data.axes.e.inverted);
var editDialog = $("#settings_printerProfiles_editDialog");
var confirmButton = $("button.btn-confirm", editDialog);
var dialogTitle = $("h3.modal-title", editDialog);
dialogTitle.text(add ? gettext("Add Printer Profile") : _.sprintf(gettext("Edit Printer Profile \"%(name)s\""), {name: data.name}));
confirmButton.unbind("click");
confirmButton.bind("click", function() {
self.confirmEditProfile(add);
});
editDialog.modal("show");
};
self.confirmEditProfile = function(add) {
var callback = function() {
$("#settings_printerProfiles_editDialog").modal("hide");
};
if (add) {
self.addProfile(callback);
} else {
self.updateProfile(undefined, callback);
}
};
self._editorData = function() {
var profile = {
id: self.editorIdentifier(),
name: self.editorName(),
color: self.editorColor(),
model: self.editorModel(),
volume: {
width: self.editorVolumeWidth(),
depth: self.editorVolumeDepth(),
height: self.editorVolumeHeight(),
formFactor: self.editorVolumeFormFactor()
},
heatedBed: self.editorHeatedBed(),
extruder: {
count: self.editorExtruders(),
offsets: [
[0.0, 0.0]
],
nozzleDiameter: self.editorNozzleDiameter()
},
axes: {
x: {
speed: self.editorAxisXSpeed(),
inverted: self.editorAxisXInverted()
},
y: {
speed: self.editorAxisYSpeed(),
inverted: self.editorAxisYInverted()
},
z: {
speed: self.editorAxisZSpeed(),
inverted: self.editorAxisZInverted()
}
}
};
if (self.editorExtruders() > 1) {
for (var i = 1; i < self.editorExtruders(); i++) {
var offset = [0.0, 0.0];
if (i < self.editorExtruderOffsets().length) {
offset = self.editorExtruderOffsets()[i];
}
profile.extruder.offsets.push(offset);
}
}
return profile;
};
self.onEvent = function(type, payload) {
if (type == "PrinterProfileSelected" || type == "PrinterProfileDeselected" || type == "PrinterProfileModified") {
self.requestData();
}
};
self.onSettingsShown = self.requestData;
self.onStartup = self.requestData;
}
@@ -22,12 +22,22 @@ function PrinterStateViewModel(loginStateViewModel) {
self.sd = ko.observable(undefined);
self.timelapse = ko.observable(undefined);
self.busyFiles = ko.observableArray([]);
self.filament = ko.observableArray([]);
self.estimatedPrintTime = ko.observable(undefined);
self.lastPrintTime = ko.observable(undefined);
self.currentHeight = ko.observable(undefined);
self.TITLE_PRINT_BUTTON_PAUSED = gettext("Restarts the print job from the beginning");
self.TITLE_PRINT_BUTTON_UNPAUSED = gettext("Starts the print job");
self.TITLE_PAUSE_BUTTON_PAUSED = gettext("Resumes the print job");
self.TITLE_PAUSE_BUTTON_UNPAUSED = gettext("Pauses the print job");
self.titlePrintButton = ko.observable(self.TITLE_PRINT_BUTTON_UNPAUSED);
self.titlePauseButton = ko.observable(self.TITLE_PAUSE_BUTTON_UNPAUSED);
self.estimatedPrintTimeString = ko.computed(function() {
if (self.lastPrintTime())
return formatDuration(self.lastPrintTime());
@@ -101,9 +111,12 @@ function PrinterStateViewModel(loginStateViewModel) {
self._processJobData(data.job);
self._processProgressData(data.progress);
self._processZData(data.currentZ);
self._processBusyFiles(data.busyFiles);
};
self._processStateData = function(data) {
var prevPaused = self.isPaused();
self.stateString(gettext(data.text));
self.isErrorOrClosed(data.flags.closedOrError);
self.isOperational(data.flags.operational);
@@ -112,6 +125,16 @@ function PrinterStateViewModel(loginStateViewModel) {
self.isError(data.flags.error);
self.isReady(data.flags.ready);
self.isSdReady(data.flags.sdReady);
if (self.isPaused() != prevPaused) {
if (self.isPaused()) {
self.titlePrintButton(self.TITLE_PRINT_BUTTON_PAUSED);
self.titlePauseButton(self.TITLE_PAUSE_BUTTON_PAUSED);
} else {
self.titlePrintButton(self.TITLE_PRINT_BUTTON_UNPAUSED);
self.titlePauseButton(self.TITLE_PAUSE_BUTTON_UNPAUSED);
}
}
};
self._processJobData = function(data) {
@@ -157,6 +180,16 @@ function PrinterStateViewModel(loginStateViewModel) {
self.currentHeight(data);
};
self._processBusyFiles = function(data) {
var busyFiles = [];
_.each(data, function(entry) {
if (entry.hasOwnProperty("name") && entry.hasOwnProperty("origin")) {
busyFiles.push(entry.origin + ":" + entry.name);
}
});
self.busyFiles(busyFiles);
};
self.print = function() {
var restartCommand = function() {
self._jobCommand("restart");
@@ -181,13 +214,18 @@ function PrinterStateViewModel(loginStateViewModel) {
self._jobCommand("cancel");
};
self._jobCommand = function(command) {
self._jobCommand = function(command, callback) {
$.ajax({
url: API_BASEURL + "job",
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({command: command})
data: JSON.stringify({command: command}),
success: function(response) {
if (callback != undefined) {
callback();
}
}
});
}
}
@@ -1,126 +1,16 @@
function SettingsViewModel(loginStateViewModel, usersViewModel) {
function SettingsViewModel(loginStateViewModel, usersViewModel, printerProfilesViewModel) {
var self = this;
self.loginState = loginStateViewModel;
self.users = usersViewModel;
self.printerProfiles = printerProfilesViewModel;
self.api_enabled = ko.observable(undefined);
self.api_key = ko.observable(undefined);
self.api_allowCrossOrigin = ko.observable(undefined);
self.appearance_name = ko.observable(undefined);
self.appearance_color = ko.observable(undefined);
self.appearance_available_colors = ko.observable([
{key: "default", name: gettext("default")},
{key: "red", name: gettext("red")},
{key: "orange", name: gettext("orange")},
{key: "yellow", name: gettext("yellow")},
{key: "green", name: gettext("green")},
{key: "blue", name: gettext("blue")},
{key: "violet", name: gettext("violet")},
{key: "black", name: gettext("black")},
]);
self.appearance_colorName = function(color) {
switch (color) {
case "red":
return gettext("red");
case "orange":
return gettext("orange");
case "yellow":
return gettext("yellow");
case "green":
return gettext("green");
case "blue":
return gettext("blue");
case "violet":
return gettext("violet");
case "black":
return gettext("black");
case "default":
return gettext("default");
default:
return color;
}
};
self.printer_movementSpeedX = ko.observable(undefined);
self.printer_movementSpeedY = ko.observable(undefined);
self.printer_movementSpeedZ = ko.observable(undefined);
self.printer_movementSpeedE = ko.observable(undefined);
self.printer_invertAxes = ko.observable(undefined);
self.printer_numExtruders = ko.observable(undefined);
self.printer_defaultExtrusionLength = ko.observable(undefined);
self._printer_extruderOffsets = ko.observableArray([]);
self.printer_extruderOffsets = ko.computed({
read: function() {
var extruderOffsets = self._printer_extruderOffsets();
var result = [];
for (var i = 0; i < extruderOffsets.length; i++) {
result[i] = {
x: parseFloat(extruderOffsets[i].x()),
y: parseFloat(extruderOffsets[i].y())
}
}
return result;
},
write: function(value) {
var result = [];
if (value && Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
result[i] = {
x: ko.observable(value[i].x),
y: ko.observable(value[i].y)
}
}
}
self._printer_extruderOffsets(result);
},
owner: self
});
self.ko_printer_extruderOffsets = ko.computed(function() {
var extruderOffsets = self._printer_extruderOffsets();
var numExtruders = self.printer_numExtruders();
if (!numExtruders) {
numExtruders = 1;
}
if (numExtruders > extruderOffsets.length) {
for (var i = extruderOffsets.length; i < numExtruders; i++) {
extruderOffsets[i] = {
x: ko.observable(0),
y: ko.observable(0)
}
}
self._printer_extruderOffsets(extruderOffsets);
}
return extruderOffsets.slice(0, numExtruders);
});
self.printer_bedDimensionX = ko.observable(undefined);
self.printer_bedDimensionY = ko.observable(undefined);
self.printer_bedDimensionR = ko.observable(undefined);
self.printer_bedCircular = ko.observable(undefined);
self.printer_bedDimensions = ko.computed({
read: function () {
return {
x: parseFloat(self.printer_bedDimensionX()),
y: parseFloat(self.printer_bedDimensionY()),
r: parseFloat(self.printer_bedDimensionR()),
circular: self.printer_bedCircular()
};
},
write: function(value) {
self.printer_bedDimensionX(value.x);
self.printer_bedDimensionY(value.y);
self.printer_bedDimensionR(value.r);
self.printer_bedCircular(value.circular);
},
owner: self
});
self.webcam_streamUrl = ko.observable(undefined);
self.webcam_snapshotUrl = ko.observable(undefined);
self.webcam_ffmpegPath = ko.observable(undefined);
@@ -166,6 +56,8 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
self.terminalFilters = ko.observableArray([]);
self.settings = undefined;
self.addTemperatureProfile = function() {
self.temperature_profiles.push({name: "New", extruder:0, bed:0});
};
@@ -182,31 +74,10 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
self.terminalFilters.remove(filter);
};
self.getPrinterInvertAxis = function(axis) {
return _.contains((self.printer_invertAxes() || []), axis.toLowerCase());
self.onSettingsShown = function() {
self.requestData();
};
self.setPrinterInvertAxis = function(axis, value) {
var currInvert = self.printer_invertAxes() || [];
var currValue = self.getPrinterInvertAxis(axis);
if (value && !currValue) {
currInvert.push(axis.toLowerCase());
} else if (!value && currValue) {
currInvert = _.without(currInvert, axis.toLowerCase());
}
self.printer_invertAxes(currInvert);
};
self.koInvertAxis = function (axis) { return ko.computed({
read: function () { return self.getPrinterInvertAxis(axis); },
write: function (value) { self.setPrinterInvertAxis(axis, value); },
owner: self
})};
self.printer_invertX = self.koInvertAxis('x');
self.printer_invertY = self.koInvertAxis('y');
self.printer_invertZ = self.koInvertAxis('z');
self.requestData = function(callback) {
$.ajax({
url: API_BASEURL + "settings",
@@ -220,21 +91,16 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
};
self.fromResponse = function(response) {
if (self.settings === undefined) {
self.settings = ko.mapping.fromJS(response);
} else {
ko.mapping.fromJS(response, self.settings);
}
self.api_enabled(response.api.enabled);
self.api_key(response.api.key);
self.api_allowCrossOrigin(response.api.allowCrossOrigin);
self.appearance_name(response.appearance.name);
self.appearance_color(response.appearance.color);
self.printer_movementSpeedX(response.printer.movementSpeedX);
self.printer_movementSpeedY(response.printer.movementSpeedY);
self.printer_movementSpeedZ(response.printer.movementSpeedZ);
self.printer_movementSpeedE(response.printer.movementSpeedE);
self.printer_invertAxes(response.printer.invertAxes);
self.printer_numExtruders(response.printer.numExtruders);
self.printer_extruderOffsets(response.printer.extruderOffsets);
self.printer_bedDimensions(response.printer.bedDimensions);
self.printer_defaultExtrusionLength(response.printer.defaultExtrusionLength);
self.webcam_streamUrl(response.webcam.streamUrl);
@@ -284,25 +150,15 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
};
self.saveData = function() {
var data = {
var data = ko.mapping.toJS(self.settings);
data = _.extend(data, {
"api" : {
"enabled": self.api_enabled(),
"key": self.api_key(),
"allowCrossOrigin": self.api_allowCrossOrigin()
},
"appearance" : {
"name": self.appearance_name(),
"color": self.appearance_color()
},
"printer": {
"movementSpeedX": self.printer_movementSpeedX(),
"movementSpeedY": self.printer_movementSpeedY(),
"movementSpeedZ": self.printer_movementSpeedZ(),
"movementSpeedE": self.printer_movementSpeedE(),
"invertAxes": self.printer_invertAxes(),
"numExtruders": self.printer_numExtruders(),
"extruderOffsets": self.printer_extruderOffsets(),
"bedDimensions": self.printer_bedDimensions(),
"defaultExtrusionLength": self.printer_defaultExtrusionLength()
},
"webcam": {
@@ -354,7 +210,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
"config": self.cura_config()
},
"terminalFilters": self.terminalFilters()
};
});
$.ajax({
url: API_BASEURL + "settings",
@@ -367,6 +223,5 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
$("#settings_dialog").modal("hide");
}
});
}
};
}
@@ -0,0 +1,166 @@
function SlicingViewModel(loginStateViewModel, printerProfilesViewModel) {
var self = this;
self.loginState = loginStateViewModel;
self.printerProfiles = printerProfilesViewModel;
self.target = undefined;
self.file = undefined;
self.data = undefined;
self.defaultSlicer = undefined;
self.defaultProfile = undefined;
self.gcodeFilename = ko.observable();
self.title = ko.observable();
self.slicer = ko.observable();
self.slicers = ko.observableArray();
self.profile = ko.observable();
self.profiles = ko.observableArray();
self.printerProfile = ko.observable();
self.afterSlicingOptions = [
{"value": "none", "text": gettext("Do nothing")},
{"value": "select", "text": gettext("Select for printing")},
{"value": "print", "text": gettext("Start printing")}
];
self.afterSlicing = ko.observable("none");
self.show = function(target, file) {
self.target = target;
self.file = file;
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file}));
self.gcodeFilename(self.file.substr(0, self.file.lastIndexOf(".")));
self.printerProfile(self.printerProfiles.currentProfile());
self.afterSlicing("none");
$("#slicing_configuration_dialog").modal("show");
};
self.slicer.subscribe(function(newValue) {
self.profilesForSlicer(newValue);
});
self.enableSliceButton = ko.computed(function() {
return self.gcodeFilename() != undefined
&& self.gcodeFilename().trim() != ""
&& self.slicer() != undefined
&& self.profile() != undefined;
});
self.requestData = function() {
$.ajax({
url: API_BASEURL + "slicing",
type: "GET",
dataType: "json",
success: self.fromResponse
})
};
self.fromResponse = function(data) {
self.data = data;
var selectedSlicer = undefined;
self.slicers.removeAll();
_.each(_.values(data), function(slicer) {
var name = slicer.displayName;
if (name == undefined) {
name = slicer.key;
}
if (slicer.default) {
selectedSlicer = slicer.key;
}
self.slicers.push({
key: slicer.key,
name: name
});
});
if (selectedSlicer != undefined) {
self.slicer(selectedSlicer);
}
self.defaultSlicer = selectedSlicer;
};
self.profilesForSlicer = function(key) {
if (key == undefined) {
key = self.slicer();
}
if (key == undefined || !self.data.hasOwnProperty(key)) {
return;
}
var slicer = self.data[key];
var selectedProfile = undefined;
self.profiles.removeAll();
_.each(_.values(slicer.profiles), function(profile) {
var name = profile.displayName;
if (name == undefined) {
name = profile.key;
}
if (profile.default) {
selectedProfile = profile.key;
}
self.profiles.push({
key: profile.key,
name: name
})
});
if (selectedProfile != undefined) {
self.profile(selectedProfile);
}
self.defaultProfile = selectedProfile;
};
self.slice = function() {
var gcodeFilename = self._sanitize(self.gcodeFilename());
if (!_.endsWith(gcodeFilename.toLowerCase(), ".gco")
&& !_.endsWith(gcodeFilename.toLowerCase(), ".gcode")
&& !_.endsWith(gcodeFilename.toLowerCase(), ".g")) {
gcodeFilename = gcodeFilename + ".gco";
}
var data = {
command: "slice",
slicer: self.slicer(),
profile: self.profile(),
printerProfile: self.printerProfile(),
gcode: gcodeFilename
};
if (self.afterSlicing() == "print") {
data["print"] = true;
} else if (self.afterSlicing() == "select") {
data["select"] = true;
}
$.ajax({
url: API_BASEURL + "files/" + self.target + "/" + self.file,
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data)
});
$("#slicing_configuration_dialog").modal("hide");
self.gcodeFilename(undefined);
self.slicer(self.defaultSlicer);
self.profile(self.defaultProfile);
};
self._sanitize = function(name) {
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
};
self.onStartup = function() {
self.requestData();
};
}
@@ -40,7 +40,7 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) {
var tools = self.tools();
// tools
var numExtruders = self.settingsViewModel.printer_numExtruders();
var numExtruders = self.settingsViewModel.printerProfiles.currentProfileData().extruder.count();
if (numExtruders && numExtruders > 1) {
// multiple extruders
for (var extruder = 0; extruder < numExtruders; extruder++) {
@@ -73,7 +73,10 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) {
self.heaterOptions(heaterOptions);
self.tools(tools);
};
self.settingsViewModel.printer_numExtruders.subscribe(self._numExtrudersUpdated);
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
self._numExtrudersUpdated();
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._numExtrudersUpdated);
});
self.temperatures = [];
self.plotOptions = {
@@ -94,15 +94,15 @@ function TimelapseViewModel(loginStateViewModel) {
self.persist(false);
self.isDirty(false);
}
};
self.fromCurrentData = function(data) {
self._processStateData(data.state);
}
};
self.fromHistoryData = function(data) {
self._processStateData(data.state);
}
};
self._processStateData = function(data) {
self.isErrorOrClosed(data.flags.closedOrError);
@@ -112,7 +112,7 @@ function TimelapseViewModel(loginStateViewModel) {
self.isError(data.flags.error);
self.isReady(data.flags.ready);
self.isLoading(data.flags.loading);
}
};
self.removeFile = function(filename) {
$.ajax({
@@ -121,25 +121,33 @@ function TimelapseViewModel(loginStateViewModel) {
dataType: "json",
success: self.requestData
});
}
};
self.save = function(data, event) {
var data = {
var payload = {
"type": self.timelapseType(),
"postRoll": self.timelapsePostRoll(),
"save": self.persist()
}
};
if (self.timelapseType() == "timed") {
data["interval"] = self.timelapseTimedInterval();
payload["interval"] = self.timelapseTimedInterval();
}
$.ajax({
url: API_BASEURL + "timelapse",
type: "POST",
dataType: "json",
data: data,
data: payload,
success: self.fromResponse
});
}
};
self.onDataUpdaterReconnect = function() {
self.requestData();
};
self.onStartup = function() {
self.requestData();
};
}
+1 -1
View File
@@ -1 +1 @@
window.BABEL_TO_LOAD_de = {"locale": "de", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-08-28 15:56+0100\nLast-Translator: Gina H\u00e4u\u00dfge <osd@foosel.net>\nLanguage-Team: German (http://www.transifex.com/projects/p/octoprint/language/de/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Verbleibende Druckdauer", "Proceed": "Fortfahren", "Timelapse Temp Folder": "Tempor\u00e4res Zeitrafferverzeichnis", "Title": "Titel", "Only show files stored locally": "Nur lokal abgelegte Dateien anzeigen", "yellow": "Gelb", "Path to Cura": "Pfad zu Cura", "Action": "Aktion", "Passwords do not match": "Passw\u00f6rter nicht identisch", "Sort by name": "Nach Name sortieren", "Save connection settings": "Verbindungseinstellungen speichern", "Rendering timelapse": "Zeitraffer wird gerendert", "Cura": "Cura", "Files": "Dateien", "Bed Size": "Bettdimensionen", "Always assume SD card is present": "Immer davon ausgehen, dass eine SD-Karte vorhanden ist", "Load and Print": "Laden und Drucken", "Sending file to SD": "Sende Datei zu SD", "Number of Extruders": "Anzahl Extruder", "black": "Schwarz", "Last Printed": "Zuletzt gedruckt", "Sourcecode": "Quellcode", "Estimated layer height": "Gesch\u00e4tzte Schichth\u00f6he", "You are now logged out": "Du bist jetzt ausgeloggt", "Uploaded": "Hochgeladen", "Opening serial port": "\u00d6ffnet Serialport", "New timelapse %(movie_basename)s is done rendering.": "Neue Zeitrafferaufnahme %(movie_basename)s wurde fertig gerendert", "Invert control": "Invertieren", "Webcam": "Webcam", "Remember me": "Login merken", "Enable GCode Visualizer": "GCode Viewer aktivieren", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich werde <strong>\u00fcber die n\u00e4chsten Minuten</strong> versuchen, zu reconnecten, aber Du kannst mittels des folgenden Buttons auch jederzeit einen manuellen Reconnect ansto\u00dfen.", "Rendering failed": "Rendering fehlgeschlagen", "Upload Folder": "Uploadverzeichnis", "descending": "absteigend", "X": "X", "Add user": "Nutzer hinzuf\u00fcgen", "GCODE commands in layer": "GCODE Kommandos in Schicht", "Estimated print time": "Gesch\u00e4tzte Druckzeit", "Serial Connection": "Serielle Verbindung", "Control": "Kontrolle", "Password": "Passwort", "Also show next layer": "Auch n\u00e4chste Schicht anzeigen", "Print Time": "Druckdauer", "Sort by file size": "Nach Gr\u00f6\u00dfe sortieren", "Machine State": "Druckerstatus", "default": "Standard", "API": "API", "Printing from SD": "Drucke von SD", "Terminal filters": "Terminalfilter", "Change password for user \"%(user)s\"": "Passwort\u00e4nderung f\u00fcr Nutzer \"%(user)s\"", "Enable Temperature Graph": "Temperaturgraph aktivieren", "Delete user": "Nutzer l\u00f6schen", "Confirm Password": "Passwort best\u00e4tigen", "Disconnect": "Trennen", "Slicing done": "Slicing abgeschlossen", "Initialize SD card": "SD-Karte initialisieren", "System": "System", "Send": "Senden", "State": "Status", "Version": "Version", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH:mm", "Attempt to reconnect": "Erneut verbinden", "Streaming done": "Streaming abgeschlossen", "violet": "Violett", "Print": "Drucken", "Layer count": "Schichtanzahl", "OctoPrint Settings": "OctoPrint Einstellungen", "Are you sure?": "Bist Du sicher?", "blue": "Blau", "Printer": "Drucker", "Tool": "Werkzeug", "Settings": "Einstellungen", "Path to FFMPEG": "Pfad zu FFMPEG", "Upload to SD": "Upload (SD)", "The command \"%(command)s\" could not be executed.": "Das Kommando \"%(command)s\" konnte nicht ausgef\u00fchrt werden.", "Printed": "Gedruckt", "Layer number": "Schichtnummer", "Sync with job progress": "Job mit Fortschritt synchronisieren", "Circular": "Rund", "Total filament used": "Gesamtmenge genutzten Filaments", "red": "Rot", "Save as default": "Als Standard speichern", "Slicing ...": "Slice ...", "Last Print Time": "Letzte Druckdauer", "Target": "Soll", "Streaming ...": "Streame ...", "Logout successful": "Logout erfolgreich", "Now rendering timelapse %(movie_basename)s": "Rendere Zeitrafferaufnahme %(movie_basename)s", "Documentation": "Dokumentation", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Upload", "ascending": "aufsteigend", "Model size": "Modelgr\u00f6\u00dfe", "Temperatures": "Temperaturen", "visited": "besucht", "Timed": "Nach Zeit", "Edit user \"%(user)s\"": "Editiere Nutzer \"%(user)s\"", "Snapshot URL": "Snapshot-URL", "Release SD card": "SD-KLine truncated
window.BABEL_TO_LOAD_de = {"locale": "de", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-10-20 09:44+0200\nPO-Revision-Date: 2014-10-20 09:48+0100\nLast-Translator: Gina H\u00e4u\u00dfge <osd@foosel.net>\nLanguage-Team: German (http://www.transifex.com/projects/p/octoprint/language/de/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Verbleibende Druckdauer", "Proceed": "Fortfahren", "Timelapse Temp Folder": "Tempor\u00e4res Zeitrafferverzeichnis", "Title": "Titel", "Only show files stored locally": "Nur lokal abgelegte Dateien anzeigen", "yellow": "Gelb", "Action": "Aktion", "Passwords do not match": "Passw\u00f6rter nicht identisch", "Sort by name": "Nach Name sortieren", "Save connection settings": "Verbindungseinstellungen speichern", "Rendering timelapse": "Zeitraffer wird gerendert", "Temperature": "Temperatur", "Files": "Dateien", "Bed Size": "Bettdimensionen", "Resume": "Weiter", "Always assume SD card is present": "Immer davon ausgehen, dass eine SD-Karte vorhanden ist", "Load and Print": "Laden und Drucken", "Sending file to SD": "Sende Datei zu SD", "Number of Extruders": "Anzahl Extruder", "black": "Schwarz", "Last Printed": "Zuletzt gedruckt", "Sourcecode": "Quellcode", "Estimated layer height": "Gesch\u00e4tzte Schichth\u00f6he", "You are now logged out": "Du bist jetzt ausgeloggt", "Uploaded": "Hochgeladen", "Opening serial port": "\u00d6ffnet Serialport", "New timelapse %(movie_basename)s is done rendering.": "Neue Zeitrafferaufnahme %(movie_basename)s wurde fertig gerendert", "Invert control": "Invertieren", "Webcam": "Webcam", "Remember me": "Login merken", "Enable GCode Visualizer": "GCode Viewer aktivieren", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich werde <strong>\u00fcber die n\u00e4chsten Minuten</strong> versuchen, zu reconnecten, aber Du kannst mittels des folgenden Buttons auch jederzeit einen manuellen Reconnect ansto\u00dfen.", "Rendering failed": "Rendering fehlgeschlagen", "Upload Folder": "Uploadverzeichnis", "descending": "absteigend", "Only show files stored on SD": "Nur auf SD abgelegte Dateien anzeigen", "X": "X", "Add user": "Nutzer hinzuf\u00fcgen", "GCODE commands in layer": "GCODE Kommandos in Schicht", "Estimated print time": "Gesch\u00e4tzte Druckdauer", "Serial Connection": "Serielle Verbindung", "Control": "Kontrolle", "Password": "Passwort", "Also show next layer": "Auch n\u00e4chste Schicht anzeigen", "Print Time": "Druckdauer", "Slicer": "Slicer", "Sort by file size": "Nach Gr\u00f6\u00dfe sortieren", "Machine State": "Druckerstatus", "Slicing Profile": "Slicingprofil", "Pauses the print job": "Pausiert den Druckjob", "API": "API", "Printing from SD": "Drucke von SD", "Stream URL": "Stream-URL", "Terminal filters": "Terminalfilter", "Change password for user \"%(user)s\"": "Passwort\u00e4nderung f\u00fcr Nutzer \"%(user)s\"", "mm": "mm", "Enable Temperature Graph": "Temperaturgraph aktivieren", "Delete user": "Nutzer l\u00f6schen", "Confirm Password": "Passwort best\u00e4tigen", "Disconnect": "Trennen", "Slicing done": "Slicing abgeschlossen", "Initialize SD card": "SD-Karte initialisieren", "System": "System", "Send": "Senden", "State": "Status", "Version": "Version", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH:mm", "Attempt to reconnect": "Erneut verbinden", "Streaming done": "Streaming abgeschlossen", "violet": "Violett", "Print": "Drucken", "Layer count": "Schichtanzahl", "OctoPrint Settings": "OctoPrint Einstellungen", "Are you sure?": "Bist Du sicher?", "blue": "Blau", "Printer": "Drucker", "Tool": "Werkzeug", "Settings": "Einstellungen", "Path to FFMPEG": "Pfad zu FFMPEG", "Upload to SD": "Upload (SD)", "The command \"%(command)s\" could not be executed.": "Das Kommando \"%(command)s\" konnte nicht ausgef\u00fchrt werden.", "Printed": "Gedruckt", "Wait for <code>start</code> on connect": "Bei der Verbindung auf <code>start</code> warten", "Layer number": "Schichtnummer", "Sync with job progress": "Job mit Fortschritt synchronisieren", "Circular": "Rund", "Total filament used": "Gesamtmenge genutzten Filaments", "red": "Rot", "Save as default": "Als Standard speichern", "Slicing ...": "Slice ...", "Last Print Time": "Letzte Druckdauer", "Target": "Soll", "Streaming ...": "Streame ...", "Default extrusion length": "Standard Extrusionsl\u00e4nge", "Logout successful": "Logout erfolgreich", "Now rendering timelapse %(movie_basename)s": "Rendere Zeitrafferaufnahme %(movie_basename)s", "Documentation": "Dokumentation", "%(hLine truncated
+1
View File
@@ -0,0 +1 @@
window.BABEL_TO_LOAD_nl = {"locale": "nl", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-09-01 20:11+0000\nLast-Translator: leon.bek <leon.bek@gmail.com>\nLanguage-Team: Dutch (http://www.transifex.com/projects/p/octoprint/language/nl/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Resterende print tijd", "Proceed": "Verder", "Timelapse Temp Folder": "Tijdelijke timelapse map", "Title": "Titel", "Only show files stored locally": "Laat alleen lokale bestanden zien", "yellow": "geel", "Path to Cura": "Lokatie van Cura", "Action": "Actie", "Passwords do not match": "Wachtwoorden komen niet overeen", "Sort by name": "Sorteer op naam", "Save connection settings": "Verbindings instellingen opslaan", "Rendering timelapse": "Renderen van timelapse", "Cura": "Cura", "Files": "Bestanden", "Bed Size": "Platform grootte", "Always assume SD card is present": "Neem aan dat SD kaart altijd aanwezig is", "Load and Print": "Laad en print", "Sending file to SD": "Verstuur bestand naar SD", "Number of Extruders": "Aantal Extruders", "black": "zwart", "Last Printed": "Laats geprint", "Sourcecode": "Broncode", "Estimated layer height": "Geschatte laag hooge", "You are now logged out": "Je bent nu uitgelogd", "Uploaded": "Geupload", "Opening serial port": "Openen van seri\u00eble poort", "New timelapse %(movie_basename)s is done rendering.": "Nieuwe timelapse %(movie_basename)s is gereed", "Invert control": "Bedieining spiegelen", "Webcam": "Webcam", "Remember me": "Onthoud me", "Enable GCode Visualizer": "Schakel GCode Visualizer in", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "De server lijkt offline te zijn, dat wil zeggen dat ik er geen reactie van krijg. Ik zal proberen om <strong>gedurende een paar minuten</strong> opnieuw te verbinden. Maar je bent op elk moment vrij om handmatig proberen te verbinden met onderstaande knop.", "Rendering failed": "Renderen mislukt", "Upload Folder": "Lokatie voor Uploads", "descending": "Aflopend", "X": "X", "Add user": "Gebruiker toevoegen", "GCODE commands in layer": "GCODE commando's in laag", "Estimated print time": "Geschatte print tijd", "Serial Connection": "Seri\u00eble verbinding", "Control": "Controle", "Password": "Wachtwoord", "Also show next layer": "Laat ook volgende laag zien", "Print Time": "Print tijd", "Sort by file size": "Sorteer op bestands grootte", "Machine State": "Machine status", "default": "Standaard", "API": "API", "Printing from SD": "Printen vanaf SD", "Terminal filters": "Terminal filters", "Change password for user \"%(user)s\"": "Verander wachtwoord voor gebruiker \"%(user)s\"", "Enable Temperature Graph": "Schakel temperatuur grafiek in", "Delete user": "Gebruiker verwijderen", "Confirm Password": "Bevestig wachtwoord", "Disconnect": "Verbreken", "Slicing done": "Slicing klaar", "Initialize SD card": "Formateer SD kaart", "System": "Systeem", "Send": "Verstuur", "State": "Status", "Version": "Versie", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Probeer opnieuw te verbinden", "Streaming done": "Streaming klaar", "violet": "violet", "Print": "Print", "Layer count": "Aantal lagen", "OctoPrint Settings": "OctoPrint instellingen", "Are you sure?": "Weet je het zeker?", "blue": "blauw", "Printer": "Printer", "Tool": "Gereedschap", "Settings": "Instellingen", "Path to FFMPEG": "Lokatie van FFMPEG", "Upload to SD": "Uploaden naar SD", "The command \"%(command)s\" could not be executed.": "Het commando \"%(command)s\" kon niet uitgevoerd worden.", "Printed": "Geprint", "Layer number": "Laag nummer", "Sync with job progress": "Synchroniseer met taak voortgang", "Circular": "Cirkelvormig", "Total filament used": "Totaal gebruikte filament", "red": "rood", "Save as default": "Stel in als standaard", "Slicing ...": "Slicing ...", "Last Print Time": "Laatste print tijd", "Target": "Doel", "Streaming ...": "Streaming ...", "Logout successful": "Uitloggen succesvol", "Now rendering timelapse %(movie_basename)s": "Aan het renderen van timelapse %(movie_basename)s", "Documentation": "Documentatie", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Upload", "ascending": "Oplopend", "Model size": "Model grootte", "Temperatures": "Temperaturen", "visited": "bezocht", "Timed": "Getimed", "Edit user \"%(user)s\"": "Bewerk gebruiker \"%(user)s\"", "Snapshot URL": "Snapshot URL", "Release SD card": "Geef SD kaart vrij", "Server is offline": "Server is offline", "Log communication to serial.log (might negatively impact Line truncated
+1
View File
@@ -0,0 +1 @@
window.BABEL_TO_LOAD_no = {"locale": "nb_NO", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-09-03 16:07+0000\nLast-Translator: lobster2b <ch.eikefjord@gmail.com>\nLanguage-Team: Norwegian (http://www.transifex.com/projects/p/octoprint/language/no/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Gjenst\u00e5ende utskriftstid", "Proceed": "Fortsett", "Timelapse Temp Folder": "Timelapse midlertidig mappe", "Title": "Tittel", "Only show files stored locally": "Bare vis filer lagret lokalt", "yellow": "gul", "Path to Cura": "Sti til Cura", "Action": "Handling", "Passwords do not match": "Passordet er ikke likt", "Sort by name": "Sorter ved navn", "Save connection settings": "Lagre tilkoblingsinnstillinger", "Rendering timelapse": "Sammensetter timelapse", "Cura": "Cura", "Files": "Filer", "Bed Size": "Plattformst\u00f8rrelse", "Always assume SD card is present": "Alltid anta at minnekort er p\u00e5 plass", "Load and Print": "Last og skriv ut", "Sending file to SD": "Sender fil til minnekort", "Number of Extruders": "Antall dyser", "black": "svart", "Last Printed": "Sist utskrevet", "Sourcecode": "Kildekode", "Estimated layer height": "Estimert lagh\u00f8yde", "You are now logged out": "Du er n\u00e5 logget ut", "Uploaded": "Opplastet", "Opening serial port": "\u00c5pner serialport", "New timelapse %(movie_basename)s is done rendering.": "Ny timelapse for %(movie_basename)s er ferdig sammensatt", "Invert control": "Inverter kontroller", "Webcam": "Nettkamera", "Remember me": "Husk meg", "Enable GCode Visualizer": "Aktiver GCode framviser", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Serveren er tilsynelatende frakoblet, i det minste f\u00e5r jeg ikke noen respons fra den. Jeg pr\u00f8ver \u00e5 koble til automatisk <strong>over de neste minuttene</strong>, du kan pr\u00f8ve en manuell oppkobling n\u00e5r du \u00f8nsker det ved \u00e5 bruke knappen nedenfor.", "Rendering failed": "Sammensetting feilet", "Upload Folder": "Opplastningsmappe", "descending": "synkende", "X": "X", "Add user": "Legg til bruker", "GCODE commands in layer": "GCODE kommandoer i lag", "Estimated print time": "Beregnet printtid", "Serial Connection": "Seriell kontakt", "Control": "Kontroll", "Password": "Passord", "Also show next layer": "Ogs\u00e5 vis neste lag", "Print Time": "Utskriftstid", "Sort by file size": "Sorter filer etter st\u00f8rrelse", "Machine State": "Maskintilstand", "default": "standard", "API": "API", "Printing from SD": "Utskrift fra minnekort", "Terminal filters": "Terminal filtre", "Change password for user \"%(user)s\"": "Endre passord for bruker \"%(user)s\"", "Enable Temperature Graph": "Aktiver temperaturgraf", "Delete user": "Slett bruker", "Confirm Password": "Bekreft passord", "Disconnect": "Koble fra", "Slicing done": "Slicing ferdig", "Initialize SD card": "Start minnekortet", "System": "System", "Send": "Send", "State": "Tilstand", "Version": "Versjon", "YYYY-MM-DD HH:mm": "YYYY-MM-DD HH:mm", "Attempt to reconnect": "Fors\u00f8k \u00e5 koble til p\u00e5 nytt", "Streaming done": "Streaming ferdig", "violet": "fiolett", "Print": "Utskriv", "Layer count": "Antall lag", "OctoPrint Settings": "OctoPrint innstillinger", "Are you sure?": "Er du sikker?", "blue": "bl\u00e5", "Printer": "Printer", "Tool": "Verkt\u00f8y", "Settings": "Innstillinger", "Path to FFMPEG": "Sti til FFMPEG", "Upload to SD": "Last opp til minnekort", "The command \"%(command)s\" could not be executed.": "Kommando \"%(command)s\" mislykkes", "Printed": "Utskrevet", "Layer number": "Lag nummer", "Sync with job progress": "Synkroniser med jobbprogresjon", "Circular": "Sirkul\u00e6r", "Total filament used": "Totalt tr\u00e5dforbruk", "red": "r\u00f8d", "Save as default": "Lagre som standard", "Slicing ...": "Slicing ...", "Last Print Time": "Siste utskriftstid", "Target": "M\u00e5l", "Streaming ...": "Streaming ...", "Logout successful": "Logg ut vellykket", "Now rendering timelapse %(movie_basename)s": "Sammensetter timelapse %(movie_basename)s", "Documentation": "Dokumentasjon", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Last opp", "ascending": "stigende", "Model size": "Modellst\u00f8rrelse", "Temperatures": "Temperaturer", "visited": "bes\u00f8kt", "Timed": "Tidtakes", "Edit user \"%(user)s\"": "Endre bruker \"%(user)s\"", "Snapshot URL": "Hurtigbilde URL", "Release SD card": "L\u00f8s ut minnekort", "Server is offline": "Server er frakoblet", "Log communication to serial.log (might negatively imLine truncated
@@ -0,0 +1,2 @@
/* jQuery.qrcode 0.11.0 - http://larsjung.de/jquery-qrcode/ - uses //github.com/kazuhikoarase/qrcode-generator (MIT) */
!function(){"use strict";function r(r,t,e,n){function o(r,t){return r-=n,t-=n,0>r||r>=a||0>t||t>=a?!1:i.isDark(r,t)}var i=y(e,t);i.addData(r),i.make(),n=n||0;var a=i.getModuleCount(),u=i.getModuleCount()+2*n,f=function(r,t,e,n){var o=this.isDark,i=1/u;this.isDark=function(a,u){var f=u*i,l=a*i,c=f+i,g=l+i;return o(a,u)&&(r>c||f>e||t>g||l>n)}};this.text=r,this.level=t,this.version=e,this.moduleCount=u,this.isDark=o,this.addBlank=f}function t(t,e,n,o,i){n=Math.max(1,n||1),o=Math.min(40,o||40);for(var a=n;o>=a;a+=1)try{return new r(t,e,a,i)}catch(u){}}function e(r,t,e){var n=e.size,o="bold "+e.mSize*n+"px "+e.fontname,i=d("<canvas/>")[0].getContext("2d");i.font=o;var a=i.measureText(e.label).width,u=e.mSize,f=a/n,l=(1-f)*e.mPosX,c=(1-u)*e.mPosY,g=l+f,s=c+u,h=.01;1===e.mode?r.addBlank(0,c-h,n,s+h):r.addBlank(l-h,c-h,g+h,s+h),t.fillStyle=e.fontcolor,t.font=o,t.fillText(e.label,l*n,c*n+.75*e.mSize*n)}function n(r,t,e){var n=e.size,o=e.image.naturalWidth||1,i=e.image.naturalHeight||1,a=e.mSize,u=a*o/i,f=(1-u)*e.mPosX,l=(1-a)*e.mPosY,c=f+u,g=l+a,s=.01;3===e.mode?r.addBlank(0,l-s,n,g+s):r.addBlank(f-s,l-s,c+s,g+s),t.drawImage(e.image,f*n,l*n,u*n,a*n)}function o(r,t,o){d(o.background).is("img")?t.drawImage(o.background,0,0,o.size,o.size):o.background&&(t.fillStyle=o.background,t.fillRect(o.left,o.top,o.size,o.size));var i=o.mode;1===i||2===i?e(r,t,o):(3===i||4===i)&&n(r,t,o)}function i(r,t,e,n,o,i,a,u){r.isDark(a,u)&&t.rect(n,o,i,i)}function a(r,t,e,n,o,i,a,u,f,l){a?r.moveTo(t+i,e):r.moveTo(t,e),u?(r.lineTo(n-i,e),r.arcTo(n,e,n,o,i)):r.lineTo(n,e),f?(r.lineTo(n,o-i),r.arcTo(n,o,t,o,i)):r.lineTo(n,o),l?(r.lineTo(t+i,o),r.arcTo(t,o,t,e,i)):r.lineTo(t,o),a?(r.lineTo(t,e+i),r.arcTo(t,e,n,e,i)):r.lineTo(t,e)}function u(r,t,e,n,o,i,a,u,f,l){a&&(r.moveTo(t+i,e),r.lineTo(t,e),r.lineTo(t,e+i),r.arcTo(t,e,t+i,e,i)),u&&(r.moveTo(n-i,e),r.lineTo(n,e),r.lineTo(n,e+i),r.arcTo(n,e,n-i,e,i)),f&&(r.moveTo(n-i,o),r.lineTo(n,o),r.lineTo(n,o-i),r.arcTo(n,o,n-i,o,i)),l&&(r.moveTo(t+i,o),r.lineTo(t,o),r.lineTo(t,o-i),r.arcTo(t,o,t+i,o,i))}function f(r,t,e,n,o,i,f,l){var c=r.isDark,g=n+i,s=o+i,h=e.radius*i,v=f-1,d=f+1,w=l-1,m=l+1,T=c(f,l),y=c(v,w),p=c(v,l),B=c(v,m),E=c(f,m),k=c(d,m),A=c(d,l),M=c(d,w),D=c(f,w);T?a(t,n,o,g,s,h,!p&&!D,!p&&!E,!A&&!E,!A&&!D):u(t,n,o,g,s,h,p&&D&&y,p&&E&&B,A&&E&&k,A&&D&&M)}function l(r,t,e){var n,o,a=r.moduleCount,u=e.size/a,l=i;for(m&&e.radius>0&&e.radius<=.5&&(l=f),t.beginPath(),n=0;a>n;n+=1)for(o=0;a>o;o+=1){var c=e.left+o*u,g=e.top+n*u,s=u;l(r,t,e,c,g,s,n,o)}if(d(e.fill).is("img")){t.strokeStyle="rgba(0,0,0,0.5)",t.lineWidth=2,t.stroke();var h=t.globalCompositeOperation;t.globalCompositeOperation="destination-out",t.fill(),t.globalCompositeOperation=h,t.clip(),t.drawImage(e.fill,0,0,e.size,e.size),t.restore()}else t.fillStyle=e.fill,t.fill()}function c(r,e){var n=t(e.text,e.ecLevel,e.minVersion,e.maxVersion,e.quiet);if(!n)return null;var i=d(r).data("qrcode",n),a=i[0].getContext("2d");return o(n,a,e),l(n,a,e),i}function g(r){var t=d("<canvas/>").attr("width",r.size).attr("height",r.size);return c(t,r)}function s(r){return d("<img/>").attr("src",g(r)[0].toDataURL("image/png"))}function h(r){var e=t(r.text,r.ecLevel,r.minVersion,r.maxVersion,r.quiet);if(!e)return null;var n,o,i=r.size,a=r.background,u=Math.floor,f=e.moduleCount,l=u(i/f),c=u(.5*(i-l*f)),g={position:"relative",left:0,top:0,padding:0,margin:0,width:i,height:i},s={position:"absolute",padding:0,margin:0,width:l,height:l,"background-color":r.fill},h=d("<div/>").data("qrcode",e).css(g);for(a&&h.css("background-color",a),n=0;f>n;n+=1)for(o=0;f>o;o+=1)e.isDark(n,o)&&d("<div/>").css(s).css({left:c+o*l,top:c+n*l}).appendTo(h);return h}function v(r){return w&&"canvas"===r.render?g(r):w&&"image"===r.render?s(r):h(r)}var d=jQuery,w=function(){var r=document.createElement("canvas");return!(!r.getContext||!r.getContext("2d"))}(),m="[object Opera]"!==Object.prototype.toString.call(window.opera),T={render:"canvas",minVersion:1,maxVersion:40,ecLevel:"L",left:0,top:0,size:200,fill:"#000",background:null,text:"no text",radius:0,quiet:0,mode:0,mSize:.1,mPosX:.5,mPosY:.5,label:"no label",fontname:"sans",fontcolor:"#000",image:null};d.fn.qrcode=function(r){var t=d.extend({},T,r);return this.each(function(){"canvas"===this.nodeName.toLowerCase()?c(this,t):d(this).append(v(t))})};var y=function(){function r(t,e){if("undefined"==typeof t.length)throw new Error(t.length+"/"+e);var n=function(){for(var r=0;r<t.length&&0==t[r];)r+=1;for(var n=new Array(t.length-r+e),o=0;o<t.length-r;o+=1)n[o]=t[o+r];return n}(),o={};return o.get=function(r){return n[r]},o.getLength=function(){return n.length},o.multiply=function(t){for(var e=new Array(o.getLength()+t.getLength()-1),n=0;n<o.getLength();n+=1)for(var i=0;i<t.getLength();i+=1)e[n+i]^=a.gexp(a.glog(o.get(n))+a.glog(t.get(i)));return r(e,0)},o.mod=function(t){if(o.getLength()-t.getLength()<0)return o;for(var e=a.glog(o.get(0))-a.glog(t.get(0)),n=new Array(o.getLength()),i=0;i<o.getLength();i+=1)n[i]=o.get(i);for(var i=0;i<t.getLeLine truncated
@@ -0,0 +1,22 @@
/// Knockout Mapping plugin v2.4.1
/// (c) 2013 Steven Sanderson, Roy Jacobs - http://knockoutjs.com/
/// License: MIT (http://www.opensource.org/licenses/mit-license.php)
(function(e){"function"===typeof require&&"object"===typeof exports&&"object"===typeof module?e(require("knockout"),exports):"function"===typeof define&&define.amd?define(["knockout","exports"],e):e(ko,ko.mapping={})})(function(e,f){function y(b,c){var a,d;for(d in c)if(c.hasOwnProperty(d)&&c[d])if(a=f.getType(b[d]),d&&b[d]&&"array"!==a&&"string"!==a)y(b[d],c[d]);else if("array"===f.getType(b[d])&&"array"===f.getType(c[d])){a=b;for(var e=d,l=b[d],n=c[d],t={},g=l.length-1;0<=g;--g)t[l[g]]=l[g];for(g=
n.length-1;0<=g;--g)t[n[g]]=n[g];l=[];n=void 0;for(n in t)l.push(t[n]);a[e]=l}else b[d]=c[d]}function E(b,c){var a={};y(a,b);y(a,c);return a}function z(b,c){for(var a=E({},b),e=L.length-1;0<=e;e--){var f=L[e];a[f]&&(a[""]instanceof Object||(a[""]={}),a[""][f]=a[f],delete a[f])}c&&(a.ignore=h(c.ignore,a.ignore),a.include=h(c.include,a.include),a.copy=h(c.copy,a.copy),a.observe=h(c.observe,a.observe));a.ignore=h(a.ignore,j.ignore);a.include=h(a.include,j.include);a.copy=h(a.copy,j.copy);a.observe=h(a.observe,
j.observe);a.mappedProperties=a.mappedProperties||{};a.copiedProperties=a.copiedProperties||{};return a}function h(b,c){"array"!==f.getType(b)&&(b="undefined"===f.getType(b)?[]:[b]);"array"!==f.getType(c)&&(c="undefined"===f.getType(c)?[]:[c]);return e.utils.arrayGetDistinctValues(b.concat(c))}function F(b,c,a,d,k,l,n){var t="array"===f.getType(e.utils.unwrapObservable(c));l=l||"";if(f.isMapped(b)){var g=e.utils.unwrapObservable(b)[p];a=E(g,a)}var j=n||k,h=function(){return a[d]&&a[d].create instanceof
Function},x=function(b){var f=G,g=e.dependentObservable;e.dependentObservable=function(a,b,c){c=c||{};a&&"object"==typeof a&&(c=a);var d=c.deferEvaluation,M=!1;c.deferEvaluation=!0;a=new H(a,b,c);if(!d){var g=a,d=e.dependentObservable;e.dependentObservable=H;a=e.isWriteableObservable(g);e.dependentObservable=d;d=H({read:function(){M||(e.utils.arrayRemoveItem(f,g),M=!0);return g.apply(g,arguments)},write:a&&function(a){return g(a)},deferEvaluation:!0});d.__DO=g;a=d;f.push(a)}return a};e.dependentObservable.fn=
H.fn;e.computed=e.dependentObservable;b=e.utils.unwrapObservable(k)instanceof Array?a[d].create({data:b||c,parent:j,skip:N}):a[d].create({data:b||c,parent:j});e.dependentObservable=g;e.computed=e.dependentObservable;return b},u=function(){return a[d]&&a[d].update instanceof Function},v=function(b,f){var g={data:f||c,parent:j,target:e.utils.unwrapObservable(b)};e.isWriteableObservable(b)&&(g.observable=b);return a[d].update(g)};if(n=I.get(c))return n;d=d||"";if(t){var t=[],s=!1,m=function(a){return a};
a[d]&&a[d].key&&(m=a[d].key,s=!0);e.isObservable(b)||(b=e.observableArray([]),b.mappedRemove=function(a){var c="function"==typeof a?a:function(b){return b===m(a)};return b.remove(function(a){return c(m(a))})},b.mappedRemoveAll=function(a){var c=C(a,m);return b.remove(function(a){return-1!=e.utils.arrayIndexOf(c,m(a))})},b.mappedDestroy=function(a){var c="function"==typeof a?a:function(b){return b===m(a)};return b.destroy(function(a){return c(m(a))})},b.mappedDestroyAll=function(a){var c=C(a,m);return b.destroy(function(a){return-1!=
e.utils.arrayIndexOf(c,m(a))})},b.mappedIndexOf=function(a){var c=C(b(),m);a=m(a);return e.utils.arrayIndexOf(c,a)},b.mappedGet=function(a){return b()[b.mappedIndexOf(a)]},b.mappedCreate=function(a){if(-1!==b.mappedIndexOf(a))throw Error("There already is an object with the key that you specified.");var c=h()?x(a):a;u()&&(a=v(c,a),e.isWriteableObservable(c)?c(a):c=a);b.push(c);return c});n=C(e.utils.unwrapObservable(b),m).sort();g=C(c,m);s&&g.sort();s=e.utils.compareArrays(n,g);n={};var J,A=e.utils.unwrapObservable(c),
y={},z=!0,g=0;for(J=A.length;g<J;g++){var r=m(A[g]);if(void 0===r||r instanceof Object){z=!1;break}y[r]=A[g]}var A=[],B=0,g=0;for(J=s.length;g<J;g++){var r=s[g],q,w=l+"["+g+"]";switch(r.status){case "added":var D=z?y[r.value]:K(e.utils.unwrapObservable(c),r.value,m);q=F(void 0,D,a,d,b,w,k);h()||(q=e.utils.unwrapObservable(q));w=O(e.utils.unwrapObservable(c),D,n);q===N?B++:A[w-B]=q;n[w]=!0;break;case "retained":D=z?y[r.value]:K(e.utils.unwrapObservable(c),r.value,m);q=K(b,r.value,m);F(q,D,a,d,b,w,
k);w=O(e.utils.unwrapObservable(c),D,n);A[w]=q;n[w]=!0;break;case "deleted":q=K(b,r.value,m)}t.push({event:r.status,item:q})}b(A);a[d]&&a[d].arrayChanged&&e.utils.arrayForEach(t,function(b){a[d].arrayChanged(b.event,b.item)})}else if(P(c)){b=e.utils.unwrapObservable(b);if(!b){if(h())return s=x(),u()&&(s=v(s)),s;if(u())return v(s);b={}}u()&&(b=v(b));I.save(c,b);if(u())return b;Q(c,function(d){var f=l.length?l+"."+d:d;if(-1==e.utils.arrayIndexOf(a.ignore,f))if(-1!=e.utils.arrayIndexOf(a.copy,f))b[d]=
c[d];else if("object"!=typeof c[d]&&"array"!=typeof c[d]&&0<a.observe.length&&-1==e.utils.arrayIndexOf(a.observe,f))b[d]=c[d],a.copiedProperties[f]=!0;else{var g=I.get(c[d]),k=F(b[d],c[d],a,d,b,f,b),g=g||k;if(0<a.observe.length&&-1==e.utils.arrayIndexOf(a.observe,f))b[d]=g(),a.copiedProperties[f]=!0;else{if(e.isWriteableObservable(b[d])){if(g=e.utils.unwrapObservable(g),b[d]()!==g)b[d](g)}else g=void 0===b[d]?g:e.utils.unwrapObservable(g),b[d]=g;a.mappedProperties[f]=!0}}})}else switch(f.getType(c)){case "function":u()?
e.isWriteableObservable(c)?(c(v(c)),b=c):b=v(c):b=c;break;default:if(e.isWriteableObservable(b))return q=u()?v(b):e.utils.unwrapObservable(c),b(q),q;h()||u();b=h()?x():e.observable(e.utils.unwrapObservable(c));u()&&b(v(b))}return b}function O(b,c,a){for(var d=0,e=b.length;d<e;d++)if(!0!==a[d]&&b[d]===c)return d;return null}function R(b,c){var a;c&&(a=c(b));"undefined"===f.getType(a)&&(a=b);return e.utils.unwrapObservable(a)}function K(b,c,a){b=e.utils.unwrapObservable(b);for(var d=0,f=b.length;d<
f;d++){var l=b[d];if(R(l,a)===c)return l}throw Error("When calling ko.update*, the key '"+c+"' was not found!");}function C(b,c){return e.utils.arrayMap(e.utils.unwrapObservable(b),function(a){return c?R(a,c):a})}function Q(b,c){if("array"===f.getType(b))for(var a=0;a<b.length;a++)c(a);else for(a in b)c(a)}function P(b){var c=f.getType(b);return("object"===c||"array"===c)&&null!==b}function T(){var b=[],c=[];this.save=function(a,d){var f=e.utils.arrayIndexOf(b,a);0<=f?c[f]=d:(b.push(a),c.push(d))};
this.get=function(a){a=e.utils.arrayIndexOf(b,a);return 0<=a?c[a]:void 0}}function S(){var b={},c=function(a){var c;try{c=a}catch(e){c="$$$"}a=b[c];void 0===a&&(a=new T,b[c]=a);return a};this.save=function(a,b){c(a).save(a,b)};this.get=function(a){return c(a).get(a)}}var p="__ko_mapping__",H=e.dependentObservable,B=0,G,I,L=["create","update","key","arrayChanged"],N={},x={include:["_destroy"],ignore:[],copy:[],observe:[]},j=x;f.isMapped=function(b){return(b=e.utils.unwrapObservable(b))&&b[p]};f.fromJS=
function(b){if(0==arguments.length)throw Error("When calling ko.fromJS, pass the object you want to convert.");try{B++||(G=[],I=new S);var c,a;2==arguments.length&&(arguments[1][p]?a=arguments[1]:c=arguments[1]);3==arguments.length&&(c=arguments[1],a=arguments[2]);a&&(c=E(c,a[p]));c=z(c);var d=F(a,b,c);a&&(d=a);if(!--B)for(;G.length;){var e=G.pop();e&&(e(),e.__DO.throttleEvaluation=e.throttleEvaluation)}d[p]=E(d[p],c);return d}catch(f){throw B=0,f;}};f.fromJSON=function(b){var c=e.utils.parseJson(b);
arguments[0]=c;return f.fromJS.apply(this,arguments)};f.updateFromJS=function(){throw Error("ko.mapping.updateFromJS, use ko.mapping.fromJS instead. Please note that the order of parameters is different!");};f.updateFromJSON=function(){throw Error("ko.mapping.updateFromJSON, use ko.mapping.fromJSON instead. Please note that the order of parameters is different!");};f.toJS=function(b,c){j||f.resetDefaultOptions();if(0==arguments.length)throw Error("When calling ko.mapping.toJS, pass the object you want to convert.");
if("array"!==f.getType(j.ignore))throw Error("ko.mapping.defaultOptions().ignore should be an array.");if("array"!==f.getType(j.include))throw Error("ko.mapping.defaultOptions().include should be an array.");if("array"!==f.getType(j.copy))throw Error("ko.mapping.defaultOptions().copy should be an array.");c=z(c,b[p]);return f.visitModel(b,function(a){return e.utils.unwrapObservable(a)},c)};f.toJSON=function(b,c){var a=f.toJS(b,c);return e.utils.stringifyJson(a)};f.defaultOptions=function(){if(0<arguments.length)j=
arguments[0];else return j};f.resetDefaultOptions=function(){j={include:x.include.slice(0),ignore:x.ignore.slice(0),copy:x.copy.slice(0)}};f.getType=function(b){if(b&&"object"===typeof b){if(b.constructor===Date)return"date";if(b.constructor===Array)return"array"}return typeof b};f.visitModel=function(b,c,a){a=a||{};a.visitedObjects=a.visitedObjects||new S;var d,k=e.utils.unwrapObservable(b);if(P(k))a=z(a,k[p]),c(b,a.parentName),d="array"===f.getType(k)?[]:{};else return c(b,a.parentName);a.visitedObjects.save(b,
d);var l=a.parentName;Q(k,function(b){if(!(a.ignore&&-1!=e.utils.arrayIndexOf(a.ignore,b))){var j=k[b],g=a,h=l||"";"array"===f.getType(k)?l&&(h+="["+b+"]"):(l&&(h+="."),h+=b);g.parentName=h;if(!(-1===e.utils.arrayIndexOf(a.copy,b)&&-1===e.utils.arrayIndexOf(a.include,b)&&k[p]&&k[p].mappedProperties&&!k[p].mappedProperties[b]&&k[p].copiedProperties&&!k[p].copiedProperties[b]&&"array"!==f.getType(k)))switch(f.getType(e.utils.unwrapObservable(j))){case "object":case "array":case "undefined":g=a.visitedObjects.get(j);
d[b]="undefined"!==f.getType(g)?g:f.visitModel(j,c,a);break;default:d[b]=c(j,a.parentName)}}});return d}});
+27 -1
View File
@@ -305,6 +305,32 @@ table {
}
}
// Printer profiles
&.settings_printerProfiles_profiles_name {
text-overflow: ellipsis;
text-align: left;
}
&.settings_printerProfiles_profiles_model {
text-align: left;
width: 250px;
}
&.settings_printerProfiles_profiles_action {
text-align: center;
width: 80px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
}
}
}
@@ -338,7 +364,7 @@ ul.dropdown-menu li a {
/** Connection settings */
#connection_ports, #connection_baudrates {
#connection_ports, #connection_baudrates, #connection_printers {
width: 100%;
}
+50 -1
View File
@@ -1,9 +1,58 @@
<div id="slicing_configuration_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 data-bind="text: title"></h3>
</div>
<div class="modal-body">
<p>{{ _('Please configure which slicer and which slicing profile to use and name the GCode file to slice to below, or click "Cancel" if you do not wish to slice the file now.') }}</p>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Slicer') }}</label>
<div class="controls">
<select data-bind="options: slicers, optionsText: 'name', optionsValue: 'key', optionsCaption: '{{ _('Select a slicer...') }}', value: slicer, valueAllowUnset: true"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Slicing Profile') }}</label>
<div class="controls">
<select data-bind="options: profiles, optionsText: 'name', optionsValue: 'key', optionsCaption: '{{ _('Select a slicing profile...') }}', value: profile, valueAllowUnset: true"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Printer Profile') }}</label>
<div class="controls">
<select data-bind="options: printerProfiles.profiles.items, optionsText: 'name', optionsValue: 'id', value: printerProfile, optionsCaption: '{{ _('Select a printer profile...') }}'"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('GCode Filename') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" data-bind="value: gcodeFilename">
<span class="add-on">.gco</span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('After slicing...') }}</label>
<div class="controls">
<select data-bind="options: afterSlicingOptions, optionsText: 'text', optionsValue: 'value', value: afterSlicing"></select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="#" class="btn btn-primary" data-bind="click: function() { if ($root.enableSliceButton()) { $root.slice() } }, enabled: enableSliceButton, css: {disabled: !$root.enableSliceButton()}">{{ _('Slice') }}</a>
</div>
</div>
<div id="offline_overlay" xmlns="http://www.w3.org/1999/html">
<div id="offline_overlay_background"></div>
<div id="offline_overlay_wrapper">
<div class="container">
<div class="hero-unit">
<h1>{{ _('Server is offline') }}</h1>
<h1 id="offline_overlay_title">{{ _('Server is offline') }}</h1>
<p id="offline_overlay_message"></p>
<p>
<a class="btn btn-primary btn-large" id="offline_overlay_reconnect">{{ _('Attempt to reconnect') }}</a>
+78 -10
View File
@@ -13,16 +13,38 @@
<link href="{{ url_for('static', filename='css/font-awesome.min.css') }}" rel="stylesheet" media="screen">
<link href="{{ url_for('static', filename='css/jquery.fileupload-ui.css') }}" rel="stylesheet" media="screen">
<link href="{{ url_for('static', filename='css/pnotify.min.css') }}" rel="stylesheet" media="screen">
{% if stylesheet == "less" %}
<link href="{{ url_for('static', filename='less/octoprint.less') }}" rel="stylesheet/less" type="text/css" media="screen">
<!-- Plugin files -->
{% for name, assets in assetPlugins.items() %}
{% if "less" in assets %}
{% for asset in assets["less"] %}
<link href="{{ url_for('plugin_assets', name=name, filename=asset) }}" rel="stylesheet/less" type="text/css" media="screen">
{% endfor %}
{% endif %}
{% endfor %}
<!-- /Plugin files -->
<script src="{{ url_for('static', filename='js/lib/less.min.js') }}" type="text/javascript"></script>
{% else %}
<link href="{{ url_for('static', filename='css/octoprint.css') }}" rel="stylesheet" type="text/css" media="screen">
<!-- Plugin files -->
{% for name, assets in assetPlugins.items() %}
{% if "css" in assets %}
{% for asset in assets["css"] %}
<link href="{{ url_for('plugin_assets', name=name, filename=asset) }}" rel="stylesheet" type="text/css" media="screen">
{% endfor %}
{% endif %}
{% endfor %}
<!-- /Plugin files -->
{% endif %}
<script lang="javascript">
var BASEURL = "{{ url_for('index') }}";
var API_BASEURL = BASEURL + "api/";
var PLUGIN_BASEURL = BASEURL + "plugin/";
var GCODE_WORKER = "{{ url_for('static', filename='gcodeviewer/js/Worker.js') }}";
var CONFIG_GCODEFILESPERPAGE = 5000;
@@ -42,7 +64,10 @@
var UI_API_KEY = "{{ uiApiKey }}";
var VERSION = "{{ version }}";
var DISPLAY_VERSION = "{{ display_version }}";
var LOCALE = "{{ g.locale }}";
var ADDITIONAL_VIEWMODELS = [];
</script>
</head>
<body>
@@ -76,7 +101,7 @@
</a>
<div id="login_dropdown_loggedout" style="padding: 15px" class="dropdown-menu" data-bind="css: {hide: loginState.loggedIn(), 'dropdown-menu': !loginState.loggedIn()}">
<label for="login_user">{{ _('Username') }}</label>
<input type="text" id="login_user" placeholder="{{ _('Username') }}">
<input type="text" id="login_user" placeholder="{{ _('Username') }}" autocapitalize="none">
<label for="login_pass">{{ _('Password') }}</label>
<input type="password" id="login_pass" placeholder="{{ _('Password') }}">
<label class="checkbox">
@@ -108,6 +133,8 @@
<select id="connection_ports" data-bind="options: portOptions, optionsCaption: 'AUTO', value: selectedPort, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"></select>
<label for="connection_baudrates" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()">{{ _('Baudrate') }}</label>
<select id="connection_baudrates" data-bind="options: baudrateOptions, optionsCaption: 'AUTO', value: selectedBaudrate, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"></select>
<label for="connection_printers" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()">{{ _('Printer Profile') }}</label>
<select id="connection_printers" data-bind="options: printerOptions, optionsText: 'name', optionsValue: 'id', value: selectedPrinter, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"></select>
<label class="checkbox">
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"> {{ _('Save connection settings') }}
</label>
@@ -140,9 +167,9 @@
</div>
<div class="row-fluid print-control" style="display: none;" data-bind="visible: loginState.isUser">
<button class="btn btn-primary span4" data-bind="click: print, enable: isOperational() && isReady() && !isPrinting() && loginState.isUser(), css: {'btn-danger': isPaused()}" id="job_print"><i class="icon-white" data-bind="css: {'icon-print': !isPaused(), 'icon-undo': isPaused()}"></i> <span data-bind="text: (isPaused() ? '{{ _('Restart') }}' : '{{ _('Print') }}')">{{ _('Print') }}</span></button>
<button class="btn span4" id="job_pause" data-bind="click: pause, enable: isOperational() && (isPrinting() || isPaused()) && loginState.isUser(), css: {active: isPaused()}"><i class="icon-pause"></i> <span>{{ _('Pause') }}</span></button>
<button class="btn span4" id="job_cancel" data-bind="click: cancel, enable: isOperational() && (isPrinting() || isPaused()) && loginState.isUser()"><i class="icon-stop"></i> {{ _('Cancel') }}</button>
<button class="btn btn-primary span4" data-bind="click: print, enable: isOperational() && isReady() && !isPrinting() && loginState.isUser(), css: {'btn-danger': isPaused()}, attr: {title: titlePrintButton}" id="job_print"><i class="icon-white" data-bind="css: {'icon-print': !isPaused(), 'icon-undo': isPaused()}"></i> <span data-bind="text: (isPaused() ? '{{ _('Restart') }}' : '{{ _('Print') }}')">{{ _('Print') }}</span></button>
<button class="btn span4" id="job_pause" data-bind="click: pause, enable: isOperational() && (isPrinting() || isPaused()) && loginState.isUser(), css: {active: isPaused()}, attr: {title: titlePauseButton}"><i data-bind="css: {'icon-pause': !isPaused(), 'icon-play': isPaused()}"></i> <span data-bind="visible: !isPaused()">{{ _('Pause') }}</span><span data-bind="visible: isPaused()">{{ _('Resume') }}</span></button>
<button class="btn span4" id="job_cancel" data-bind="click: cancel, enable: isOperational() && (isPrinting() || isPaused()) && loginState.isUser()" title="{{ _('Cancels the print job') }}"><i class="icon-stop"></i> {{ _('Cancel') }}</button>
</div>
</div>
</div>
@@ -159,6 +186,9 @@
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('name'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'name' ? 'visible' : 'hidden'}"></i> {{ _('Sort by name') }} ({{ _('ascending') }})</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('upload'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'upload' ? 'visible' : 'hidden'}"></i> {{ _('Sort by upload date') }} ({{ _('descending') }})</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('size'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'size' ? 'visible' : 'hidden'}"></i> {{ _('Sort by file size') }} ({{ _('descending') }})</a></li>
<li class="divider"></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('machinecode'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'machinecode') ? 'visible' : 'hidden'}"></i> {{ _('Only show GCode files') }}</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('model'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'model') ? 'visible' : 'hidden'}"></i> {{ _('Only show STL files') }}</a></li>
{% if enableSdSupport %}
<li class="divider"></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('local'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'local') ? 'visible' : 'hidden'}"></i> {{ _('Only show files stored locally') }}</a></li>
@@ -188,7 +218,9 @@
<input type="text" class="input-block search-query" data-bind="value: searchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...') }}">
</form>
<div class="gcode_files" data-bind="slimScrolledForeach: listHelper.paginatedItems">
<div class="entry" data-bind="attr: { id: $root.getEntryId($data) }">
<div class="entry" data-bind="attr: { id: $root.getEntryId($data) }, template: { name: $root.templateFor($data), data: $data }"></div>
<script type="text/html" id="files_template_machinecode">
<div class="title" data-bind="css: $root.getSuccessClass($data), style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }, text: name"></div>
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
@@ -196,11 +228,25 @@
<div class="btn-group action-buttons">
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }"><i class="icon-chevron-down"></i></div>
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="{{ _('Download') }}"></i></a>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data.name); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data.name, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-folder-open" title="{{ _('Load') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data.name, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-print" title="{{ _('Load and Print') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-folder-open" title="{{ _('Load') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-print" title="{{ _('Load and Print') }}"></i></div>
</div>
</div>
</script>
<script type="text/html" id="files_template_model">
<div class="title muted" data-bind="text: name"></div>
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
<div class="btn-group action-buttons">
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSlicing($data)) { $root.sliceFile($data); } else { return; } }, css: {disabled: !$root.enableSlicing($data)}"><i class="icon-magic" title="{{ _('Slice') }}"></i></div>
</div>
</script>
<script type="text/html" id="files_template_folder">
<div class="title" data-bind="text: name"></div>
</script>
</div>
<div class="muted text-right">
<small>{{ _('Free') }}: <span data-bind="text: freeSpaceString"></span></small>
@@ -589,7 +635,7 @@
</div>
<div class="footer">
<ul class="pull-left muted">
<li><small>{{ _('Version') }}: <span class="version">{{ version }}</span></small></li>
<li><small>{{ _('Version') }}: <span class="version">{{ display_version }}</span></small></li>
</ul>
<ul class="pull-right">
<li><a href="http://octoprint.org"><i class="icon-home"></i> {{ _('Homepage') }}</a></li>
@@ -603,11 +649,20 @@
{% include 'settings.jinja2' %}
{% include 'dialogs.jinja2' %}
<!-- Plugin template files -->
{% if templatePlugins %}
{% for plugin_name in templatePlugins %}
{% include plugin_name+".jinja2" ignore missing %}
{% endfor %}
{% endif %}
<!-- End plugin template files -->
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/jquery/jquery.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/modernizr.custom.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/underscore-min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/underscore.string.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/knockout.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/knockout.mapping-latest.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/babel.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/avltree.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/bootstrap/bootstrap.js') }}"></script>
@@ -621,6 +676,7 @@
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/jquery/jquery.iframe-transport.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/jquery/jquery.fileupload.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/jquery/jquery.slimscroll.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/jquery/jquery.qrcode.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/sockjs-0.3.4.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/moment-with-locales.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/pusher.color.min.js') }}"></script>
@@ -639,13 +695,25 @@
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/loginstate.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/navigation.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/printerstate.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/printerprofiles.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/settings.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/slicing.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/temperature.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/terminal.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/timelapse.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/users.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/log.js') }}"></script>
<!-- Plugin files -->
{% for name, assets in assetPlugins.items() %}
{% if "js" in assets %}
{% for asset in assets["js"] %}
<script type="text/javascript" src="{{ url_for('plugin_assets', name=name, filename=asset) }}"></script>
{% endfor %}
{% endif %}
{% endfor %}
<!-- /Plugin files -->
<script type="text/javascript" src="{{ url_for('static', filename='js/app/dataupdater.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/helpers.js') }}"></script>
+202 -141
View File
@@ -8,19 +8,25 @@
<ul class="nav nav-list span4" id="settingsTabs">
<li class="nav-header">{{ _('Printer') }}</li>
<li class="active"><a href="#settings_serialConnection" data-toggle="tab">{{ _('Serial Connection') }}</a></li>
<li><a href="#settings_printerParameters" data-toggle="tab">{{ _('Printer Parameters') }}</a></li>
<li><a href="#settings_printerProfiles" data-toggle="tab">{{ _('Printer Profiles') }}</a></li>
<li><a href="#settings_temperature" data-toggle="tab">{{ _('Temperatures') }}</a></li>
<li><a href="#settings_terminalFilters" data-toggle="tab">{{ _('Terminal filters') }}</a></li>
<li class="nav-header">{{ _('Features') }}</li>
<li><a href="#settings_features" data-toggle="tab">{{ _('Features') }}</a></li>
<li><a href="#settings_webcam" data-toggle="tab">{{ _('Webcam') }}</a></li>
<li><a href="#settings_cura" data-toggle="tab">{{ _('Cura') }}</a></li>
{% if enableAccessControl %}<li><a href="#settings_users" data-toggle="tab">{{ _('Access Control') }}</a></li>{% endif %}
<li><a href="#settings_api" data-toggle="tab">{{ _('API') }}</a></li>
<li class="nav-header">OctoPrint</li>
<li><a href="#settings_folder" data-toggle="tab">{{ _('Folders') }}</a></li>
<li><a href="#settings_appearance" data-toggle="tab">{{ _('Appearance') }}</a></li>
<li><a href="#settings_logs" data-toggle="tab">{{ _('Logs') }}</a></li>
{% if settingsPlugins %}
<li class="nav-header">Plugins</li>
{% for plugin_name, vars in settingsPlugins.items() %}
{% if vars._settings_menu_entry %}
<li><a href="#settings_plugin_{{ plugin_name }}" data-toggle="tab">{{ vars._settings_menu_entry }}</a></li>
{% endif %}
{% endfor %}
{% endif %}
</ul>
<div class="tab-content span8">
@@ -99,105 +105,179 @@
</div>
</form>
</div>
<div class="tab-pane" id="settings_printerParameters">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Axis') }}</label>
<div class="controls form-inline">
<label>{{ _('X') }}:</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printer_movementSpeedX" id="settings-movementSpeedX">
<span class="add-on">mm/min</span>
</div>
<label class="checkbox">
<input type="checkbox" data-bind="checked: printer_invertX" id="settings-printerInvertX"> {{ _('Invert control') }}
</label>
</div>
<div class="controls form-inline">
<label>{{ _('Y') }}:</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printer_movementSpeedY" id="settings-movementSpeedY">
<span class="add-on">mm/min</span>
</div>
<label class="checkbox">
<input type="checkbox" data-bind="checked: printer_invertY" id="settings-printerInvertY"> {{ _('Invert control') }}
</label>
</div>
<div class="controls form-inline">
<label>{{ _('Z') }}:</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printer_movementSpeedZ" id="settings-movementSpeedZ">
<span class="add-on">mm/min</span>
</div>
<label class="checkbox">
<input type="checkbox" data-bind="checked: printer_invertZ" id="settings-printerInvertZ"> {{ _('Invert control') }}
</label>
</div>
<div class="controls form-inline">
<label>{{ _('E') }}:</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printer_movementSpeedE" id="settings-movementSpeedE">
<span class="add-on">mm/min</span>
</div>
</div>
<div class="tab-pane" id="settings_printerProfiles">
<h3>{{ _('Printer Profiles') }}</h3>
<table class="table table-striped table-hover table-condensed table-hover" id="settings_printerProfiles_profiles">
<thead>
<tr>
<th class="settings_printerProfiles_profiles_name">{{ _('Name') }}</th>
<th class="settings_printerProfiles_profiles_model">{{ _('Model') }}</th>
<th class="settings_printerProfiles_profiles_action">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: printerProfiles.profiles.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="settings_printerProfiles_profiles_name"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: name"></span></td>
<td class="settings_printerProfiles_profiles_model" data-bind="text: model"></td>
<td class="settings_printerProfiles_profiles_action">
<a href="#" class="icon-star" title="{{ _('Set as default profile') }}" data-bind="click: function() { $root.printerProfiles.makeDefault($data); }"></a>&nbsp;|&nbsp;<a href="#" class="icon-pencil" title="{{ _('Edit Profile') }}" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog($data); }"></a>&nbsp;|&nbsp;<a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="click: function() { $root.printerProfiles.removeProfile($data); }"></a>
</td>
</tr>
</tbody>
</table>
<button class="btn pull-right" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog(); }">{{ _('Add Profile...') }}</button>
<div id="settings_printerProfiles_editDialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 class="modal-title"></h3>
</div>
<div class="control-group">
<label class="control-label" for="settings-defaultExtrusionLength">{{ _('Default extrusion length') }}</label>
<div class="controls">
<input type="number" class="input-mini text-right" min="1" data-bind="value: printer_defaultExtrusionLength" id="settings-defaultExtrusionLength">
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input type="text" data-bind="value: printerProfiles.editorName">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input type="text" data-bind="value: printerProfiles.editorIdentifier, enable: $root.printerProfiles.editorNew, css: {disabled: !$root.printerProfiles.editorNew()}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Model') }}</label>
<div class="controls">
<input type="text" data-bind="value: printerProfiles.editorModel">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Color') }}</label>
<div class="controls">
<select data-bind="value: printerProfiles.editorColor, options: printerProfiles.availableColors, optionsText: 'name', optionsValue: 'key'">
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Form Factor') }}</label>
<div class="controls">
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="rectangular" data-bind="checked: printerProfiles.editorVolumeFormFactor"> {{ _('Rectangular') }}</label>
</div>
<div class="controls">
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="circular" data-bind="checked: printerProfiles.editorVolumeFormFactor"> {{ _('Circular') }}</label>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Volume') }}</label>
<div class="controls form-inline">
<label>{{ _('X') }}</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printerProfiles.editorVolumeWidth">
<span class="add-on">mm</span>
</div>
</div>
<div class="controls form-inline">
<label>{{ _('Y') }}</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printerProfiles.editorVolumeDepth">
<span class="add-on">mm</span>
</div>
</div>
<div class="controls form-inline">
<label>{{ _('Z') }}</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printerProfiles.editorVolumeHeight">
<span class="add-on">mm</span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Heated Bed') }}</label>
<div class="controls">
<input type="checkbox" data-bind="checked: printerProfiles.editorHeatedBed">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Axis') }}</label>
<div class="controls form-inline">
<label>{{ _('X') }}</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printerProfiles.editorAxisXSpeed">
<span class="add-on">mm/min</span>
</div>
<label class="checkbox">
<input type="checkbox" data-bind="checked: printerProfiles.editorAxisXInverted"> {{ _('Invert control') }}
</label>
</div>
<div class="controls form-inline">
<label>{{ _('Y') }}</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printerProfiles.editorAxisYSpeed">
<span class="add-on">mm/min</span>
</div>
<label class="checkbox">
<input type="checkbox" data-bind="checked: printerProfiles.editorAxisYInverted"> {{ _('Invert control') }}
</label>
</div>
<div class="controls form-inline">
<label>{{ _('Z') }}</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printerProfiles.editorAxisZSpeed">
<span class="add-on">mm/min</span>
</div>
<label class="checkbox">
<input type="checkbox" data-bind="checked: printerProfiles.editorAxisZInverted"> {{ _('Invert control') }}
</label>
</div>
<div class="controls form-inline">
<label>{{ _('E') }}</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printerProfiles.editorAxisESpeed">
<span class="add-on">mm/min</span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Nozzle Diameter') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printerProfiles.editorNozzleDiameter">
<span class="add-on">mm</span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Number of Extruders') }}</label>
<div class="controls">
<input type="number" class="input-mini text-right" min="1" max="5" data-bind="value: printerProfiles.editorExtruders">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Extruder Offsets') }}</label>
<!-- ko foreach: printerProfiles.koEditorExtruderOffsets -->
<div class="controls form-inline">
<label>X:</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: x">
<span class="add-on">mm</span>
</div>
<label>Y:</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: y">
<span class="add-on">mm</span>
</div>
</div>
<!-- /ko -->
</div>
</form>
</div>
<div class="control-group">
<label class="control-label" for="settings-numExtruders">{{ _('Number of Extruders') }}</label>
<div class="controls">
<input type="number" class="input-mini text-right" min="1" max="5" data-bind="value: printer_numExtruders" id="settings-numExtruders">
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary btn-confirm">{{ _('Confirm') }}</button>
</div>
<div class="control-group">
<label class="control-label" for="settings-extruderOffsets">{{ _('Extruder Offsets') }}</label>
<!-- ko foreach: ko_printer_extruderOffsets -->
<div class="controls form-inline">
<label>X:</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: x">
<span class="add-on">mm</span>
</div>
<label>Y:</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: y">
<span class="add-on">mm</span>
</div>
</div>
<!-- /ko -->
</div>
<div class="control-group">
<label class="control-label" for="settings-bedSize">{{ _('Bed Size') }}</label>
<div class="controls form-inline" data-bind="ifnot: printer_bedCircular">
<label>{{ _('X') }}:</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printer_bedDimensionX" id="settings-bedX">
<span class="add-on">mm</span>
</div>
<label>{{ _('Y') }}:</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printer_bedDimensionY" id="settings-bedY">
<span class="add-on">mm</span>
</div>
</div>
<div class="controls form-inline" data-bind="if: printer_bedCircular">
<label>{{ _('Radius') }}:</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printer_bedDimensionR" id="settings-bedR">
<span class="add-on">mm</span>
</div>
</div>
<div class="controls form-inline">
<label class="checkbox">
<input type="checkbox" data-bind="checked: printer_bedCircular" id="settings-bedCircular"> {{ _('Circular') }}
</label>
</div>
</div>
</form>
</div>
</div>
<div class="tab-pane" id="settings_webcam">
<form class="form-horizontal">
@@ -397,47 +477,8 @@
</div>
</form>
</div>
<div class="tab-pane" id="settings_appearance">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-appearanceName">{{ _('Title') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: appearance_name" id="settings-appearanceName">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-appearanceColor">{{ _('Color') }}</label>
<div class="controls">
<select id="settings-appearanceColor" data-bind="value: appearance_color, options: appearance_available_colors, optionsText: 'name', optionsValue: 'key'">
</select>
</div>
</div>
</form>
</div>
<div class="tab-pane" id="settings_cura">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-curaEnabled">{{ _('Enable slicing via Cura') }}</label>
<div class="controls">
<input type="checkbox" data-bind="checked: cura_enabled">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-curaPath">{{ _('Path to Cura') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: cura_path">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-curaConfig">{{ _('Path to Cura config') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: cura_config">
</div>
</div>
</form>
</div>
<div class="tab-pane" id="settings_api">
<form class="form-horizontal">
<form class="form-horizontal" onsubmit="return false;">
<div class="control-group">
<div class="controls">
<label class="checkbox">
@@ -455,7 +496,13 @@
<div class="control-group">
<label class="control-label" for="settings-apiKey">{{ _('API Key') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: api_key" id="settings-apikey">
<input type="text" class="input-block-level" data-bind="value: api_key, valueUpdate: 'afterkeydown'" id="settings-apikey">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('QR Code') }}</label>
<div class="controls">
<div data-bind="qrcode: {text: api_key, size: 180}"></div>
</div>
</div>
</form>
@@ -602,13 +649,21 @@
<label class="control-label">{{ _('Current API Key') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level uneditable-input" data-bind="value: $root.users.editorApikey, attr: {placeholder: '{{ _('N/A') }}'}">
<input type="text" class="input-block-level uneditable-input" data-bind="value: $root.users.editorApikey, valueUpdate: 'input', attr: {placeholder: '{{ _('N/A') }}'}">
<a class="btn" title="Generate new Apikey" data-bind="click: function() { $root.users.confirmGenerateApikey(); }"><i class="icon-refresh"></i></a>
<a class="btn btn-danger" title="Delete Apikey" data-bind="click: function() { $root.users.confirmDeleteApikey(); }"><i class="icon-trash"></i></a>
</div>
</div>
</div>
<!-- TODO Figure out issue where text isn't properly bound and hence the QR code is worthless
<div class="control-group">
<label class="control-label">{{ _('QR Code') }}</label>
<div class="controls">
<div data-bind="qrcode: {text: $root.users.editorApiKey, size: 150}"></div>
</div>
</div>
-->
</fieldset>
</form>
</div>
@@ -621,6 +676,12 @@
</div>
{% endif %}
{% for plugin_name, vars in settingsPlugins.items() %}
<div class="tab-pane" id="settings_plugin_{{ plugin_name }}" data-bind="allowBindings: false">
{% include plugin_name+"_settings_dialog.jinja2" ignore missing %}
</div>
{% endfor %}
<div class="tab-pane" id="settings_logs" data-bind="allowBindings: false">
<div id="logs">
<h1>{{ _('Logs') }}</h1>
+1 -1
View File
@@ -61,7 +61,7 @@ def notifyCallbacks(timelapse):
config = timelapse.configData()
for callback in updateCallbacks:
try: callback.sendTimelapseConfig(config)
except: pass
except: logging.getLogger(__name__).exception("Exception while pushing timelapse configuration")
def configureTimelapse(config=None, persist=False):
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+141 -9
View File
@@ -1,22 +1,110 @@
# 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.ext.login import UserMixin
from flask.ext.principal import Identity
from werkzeug.local import LocalProxy
import hashlib
import os
import yaml
import uuid
import logging
from octoprint.settings import settings
class UserManager(object):
valid_roles = ["user", "admin"]
def __init__(self):
self._logger = logging.getLogger(__name__)
self._session_users_by_session = dict()
self._session_users_by_username = dict()
def login_user(self, user):
self._cleanup_sessions()
if user is None \
or (isinstance(user, LocalProxy) and not isinstance(user._get_current_object(), User)) \
or (not isinstance(user, LocalProxy) and not isinstance(user, User)):
return None
if not isinstance(user, SessionUser):
user = SessionUser(user)
self._session_users_by_session[user.get_session()] = user
if not user.get_name() in self._session_users_by_username:
self._session_users_by_username[user.get_name()] = []
self._session_users_by_username[user.get_name()].append(user)
self._logger.debug("Logged in user: %r" % user)
return user
def logout_user(self, user):
if user is None:
return
if not isinstance(user, SessionUser):
return
if user.get_name() in self._session_users_by_username:
users_by_username = self._session_users_by_username[user.get_name()]
for u in users_by_username:
if u.get_session() == user.get_session():
users_by_username.remove(u)
break
if user.get_session() in self._session_users_by_session:
del self._session_users_by_session[user.get_session()]
self._logger.debug("Logged out user: %r" % user)
def _cleanup_sessions(self):
import time
for session, user in self._session_users_by_session.items():
if not isinstance(user, SessionUser):
continue
if user._created + (24 * 60 * 60) < time.time():
self.logout_user(user)
@staticmethod
def createPasswordHash(password):
return hashlib.sha512(password + "mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW").hexdigest()
def createPasswordHash(password, salt=None):
if not salt:
salt = settings().get(["accessControl", "salt"])
if salt is None:
import string
from random import choice
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
salt = "".join(choice(chars) for _ in xrange(32))
settings().set(["accessControl", "salt"], salt)
settings().save()
return hashlib.sha512(password + salt).hexdigest()
def checkPassword(self, username, password):
user = self.findUser(username)
if not user:
return False
hash = UserManager.createPasswordHash(password)
if user.check_password(hash):
# new hash matches, correct password
return True
else:
# new hash doesn't match, but maybe the old one does, so check that!
oldHash = UserManager.createPasswordHash(password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW")
if user.check_password(oldHash):
# old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
self.changeUserPassword(username, password)
return True
else:
# old hash doesn't match either, wrong password
return False
def addUser(self, username, password, active, roles):
pass
@@ -37,9 +125,22 @@ class UserManager(object):
pass
def removeUser(self, username):
pass
if username in self._session_users_by_username:
users = self._session_users_by_username[username]
sessions = [user.get_session() for user in users if isinstance(user, SessionUser)]
for session in sessions:
if session in self._session_users_by_session:
del self._session_users_by_session[session]
del self._session_users_by_username[username]
def findUser(self, username=None, session=None):
if session is not None:
for session in self._session_users_by_session:
user = self._session_users_by_session[session]
if username is None or username == user.get_name():
return user
break
def findUser(self, username=None):
return None
def getAllUsers(self):
@@ -97,7 +198,10 @@ class FilebasedUserManager(UserManager):
self._dirty = False
self._load()
def addUser(self, username, password, active=False, roles=["user"], apikey=None):
def addUser(self, username, password, active=False, roles=None, apikey=None):
if not roles:
roles = ["user"]
if username in self._users.keys():
raise UserAlreadyExists(username)
@@ -179,6 +283,8 @@ class FilebasedUserManager(UserManager):
self._save()
def removeUser(self, username):
UserManager.removeUser(self, username)
if not username in self._users.keys():
raise UnknownUser(username)
@@ -186,17 +292,23 @@ class FilebasedUserManager(UserManager):
self._dirty = True
self._save()
def findUser(self, username=None, apikey=None):
def findUser(self, username=None, apikey=None, session=None):
user = UserManager.findUser(self, username=username, session=session)
if user is not None:
return user
if username is not None:
if username not in self._users.keys():
return None
return self._users[username]
elif apikey is not None:
for user in self._users.values():
if apikey == user._apikey:
return user
return None
else:
return None
@@ -257,6 +369,26 @@ class User(UserMixin):
def is_admin(self):
return "admin" in self._roles
def __repr__(self):
return "User(id=%s,name=%s,active=%r,user=%r,admin=%r)" % (self.get_id(), self.get_name(), self.is_active(), self.is_user(), self.is_admin())
class SessionUser(User):
def __init__(self, user):
User.__init__(self, user._username, user._passwordHash, user._active, user._roles, user._apikey)
import string
import random
import time
chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
self._session = "".join(random.choice(chars) for _ in xrange(10))
self._created = time.time()
def get_session(self):
return self._session
def __repr__(self):
return "SessionUser(id=%s,name=%s,active=%r,user=%r,admin=%r,session=%s,created=%s)" % (self.get_id(), self.get_name(), self.is_active(), self.is_user(), self.is_admin(), self._session, self._created)
##~~ DummyUser object to use when accessControl is disabled
class DummyUser(User):
@@ -274,9 +406,9 @@ def dummy_identity_loader():
return DummyIdentity()
##~~ Apiuser object to use when api key is used to access the API
##~~ Apiuser object to use when global api key is used to access the API
class ApiUser(User):
def __init__(self):
User.__init__(self, "api", "", True, UserManager.valid_roles)
User.__init__(self, "_api", "", True, UserManager.valid_roles)
+47 -1
View File
@@ -132,7 +132,7 @@ def getDosFilename(input, existingFilenames, extension=None):
def findCollisionfreeName(input, extension, existingFilenames):
filename = re.sub(r"\s+", "_", input.lower().translate(None, ".\"/\\[]:;=,"))
filename = re.sub(r"\s+", "_", input.lower().translate({ord(i):None for i in ".\"/\\[]:;=,"}))
counter = 1
power = 1
@@ -250,5 +250,51 @@ def dict_merge(a, b):
return result
def dict_clean(a, b):
from copy import deepcopy
if not isinstance(b, dict):
return a
result = deepcopy(a)
for k, v in a.iteritems():
if not k in b:
del result[k]
elif isinstance(v, dict):
result[k] = dict_clean(v, b[k])
else:
result[k] = deepcopy(v)
return result
class Object(object):
pass
def interface_addresses(family=None):
import netifaces
if not family:
family = netifaces.AF_INET
for interface in netifaces.interfaces():
try:
ifaddresses = netifaces.ifaddresses(interface)
except:
continue
if family in ifaddresses:
for ifaddress in ifaddresses[family]:
if not ifaddress["addr"].startswith("169.254."):
yield ifaddress["addr"]
def address_for_client(host, port):
import socket
for address in interface_addresses():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((address, 0))
sock.connect((host, port))
return address
except Exception as e:
pass
+23 -7
View File
@@ -1,5 +1,5 @@
from __future__ import absolute_import
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net> based on work by David Braam"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
@@ -13,6 +13,7 @@ import threading
import Queue as queue
import logging
import serial
import octoprint.plugin
from collections import deque
@@ -21,8 +22,8 @@ from octoprint.util.avr_isp import ispBase
from octoprint.settings import settings
from octoprint.events import eventManager, Events
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
from octoprint.gcodefiles import isGcodeFileName
from octoprint.util import getExceptionString, getNewTimeout, sanitizeAscii, filterNonAscii
from octoprint.util.virtual import VirtualPrinter
@@ -151,6 +152,10 @@ class MachineCom(object):
self._resendDelta = None
self._lastLines = deque([], 50)
# hooks
self._pluginManager = octoprint.plugin.plugin_manager()
self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.gcode")
# SD status data
self._sdAvailable = False
self._sdFileList = False
@@ -402,6 +407,7 @@ class MachineCom(object):
else:
self._sendNext()
except:
self._logger.exception("Error while trying to start printing")
self._errorValue = getExceptionString()
self._changeState(self.STATE_ERROR)
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
@@ -571,8 +577,8 @@ class MachineCom(object):
maxToolNum, parsedTemps = self._parseTemperatures(line)
# extruder temperatures
if not "T0" in parsedTemps.keys() and "T" in parsedTemps.keys():
# only single reporting, "T" is our one and only extruder temperature
if not "T0" in parsedTemps.keys() and not "T1" in parsedTemps.keys() and "T" in parsedTemps.keys():
# no T1 so only single reporting, "T" is our one and only extruder temperature
toolNum, actual, target = parsedTemps["T"]
if target is not None:
@@ -582,7 +588,13 @@ class MachineCom(object):
self._temp[0] = (actual, oldTarget)
else:
self._temp[0] = (actual, None)
elif "T0" in parsedTemps.keys():
elif not "T0" in parsedTemps.keys() and "T" in parsedTemps.keys():
# Smoothieware sends multi extruder temperature data this way: "T:<first extruder> T1:<second extruder> ..." and therefore needs some special treatment...
_, actual, target = parsedTemps["T"]
del parsedTemps["T"]
parsedTemps["T0"] = (0, actual, target)
if "T0" in parsedTemps.keys():
for n in range(maxToolNum + 1):
tool = "T%d" % n
if not tool in parsedTemps.keys():
@@ -663,7 +675,7 @@ class MachineCom(object):
filename = preprocessed_line
size = None
if isGcodeFileName(filename):
if valid_file_type(filename, "gcode"):
if filterNonAscii(filename):
self._logger.warn("Got a file from printer's SD that has a non-ascii filename (%s), that shouldn't happen according to the protocol" % filename)
else:
@@ -974,7 +986,7 @@ class MachineCom(object):
def _handleErrors(self, line):
# No matter the state, if we see an error, goto the error state and store the error for reference.
if line.startswith('Error:'):
if line.startswith('Error:') or line.startswith('!!'):
#Oh YEAH, consistency.
# Marlin reports an MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
# But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
@@ -1089,6 +1101,10 @@ class MachineCom(object):
return
if not self.isStreaming():
for hook in self._gcode_hooks:
hook_cmd = self._gcode_hooks[hook](self, cmd)
if hook_cmd and isinstance(hook_cmd, basestring):
cmd = hook_cmd
gcode = self._regex_command.search(cmd)
if gcode:
gcode = gcode.group(1)
+10 -10
View File
@@ -1,5 +1,5 @@
from __future__ import absolute_import
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net> based on work by David Braam"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2013 David Braam, Gina Häußge - Released under terms of the AGPLv3 License"
@@ -31,17 +31,17 @@ class gcode(object):
self._abort = False
self._filamentDiameter = 0
def load(self, filename):
def load(self, filename, printer_profile):
if os.path.isfile(filename):
self.filename = filename
self._fileSize = os.stat(filename).st_size
with open(filename, "r") as f:
self._load(f)
self._load(f, printer_profile)
def abort(self):
self._abort = True
def _load(self, gcodeFile):
def _load(self, gcodeFile, printer_profile):
filePos = 0
pos = [0.0, 0.0, 0.0]
posOffset = [0.0, 0.0, 0.0]
@@ -53,8 +53,8 @@ class gcode(object):
absoluteE = True
scale = 1.0
posAbs = True
feedRateXY = settings().getFloat(["printerParameters", "movementSpeed", "x"])
offsets = settings().get(["printerParameters", "extruderOffsets"])
feedRateXY = min(printer_profile["axes"]["x"], printer_profile["axes"]["y"])
offsets = printer_profile["extruder"]["offsets"]
for line in gcodeFile:
if self._abort:
@@ -198,13 +198,13 @@ class gcode(object):
if T > settings().getInt(["gcodeAnalysis", "maxExtruders"]):
self._logger.warn("GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis" % T)
else:
posOffset[0] -= offsets[currentExtruder]["x"] if currentExtruder < len(offsets) else 0
posOffset[1] -= offsets[currentExtruder]["y"] if currentExtruder < len(offsets) else 0
posOffset[0] -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
posOffset[1] -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
currentExtruder = T
posOffset[0] += offsets[currentExtruder]["x"] if currentExtruder < len(offsets) else 0
posOffset[1] += offsets[currentExtruder]["y"] if currentExtruder < len(offsets) else 0
posOffset[0] += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
posOffset[1] += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
if len(currentE) <= currentExtruder:
for i in range(len(currentE), currentExtruder + 1):
+4 -1
View File
@@ -1,5 +1,5 @@
from __future__ import absolute_import
# 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'
@@ -213,6 +213,9 @@ class VirtualPrinter():
allTemps.append((i, self.temp[i], self.targetTemp[i]))
allTempsString = " ".join(map(lambda x: "T%d:%.2f /%.2f" % x if includeTarget else "T%d:%.2f" % (x[0], x[1]), allTemps))
if settings().getBoolean(["devel", "virtualPrinter", "smoothieTemperatureReporting"]):
allTempsString = allTempsString.replace("T0:", "T:")
if settings().getBoolean(["devel", "virtualPrinter", "hasBed"]):
if includeTarget:
allTempsString = "B:%.2f /%.2f %s" % (self.bedTemp, self.bedTargetTemp, allTempsString)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more