Compare commits

..
Author SHA1 Message Date
Gina Häußge cf69c4500d Merge branch 'commRefactoring' into commRefactoring-commandTracking 2014-12-31 15:56:02 +01:00
Gina Häußge c7c6a08748 Merge branch 'devel' into commRefactoring 2014-12-31 15:55:37 +01:00
Gina Häußge c9c4066331 Fixed a bunch of doc issues, updated /api/printer/command to have more meaningful error messages 2014-12-31 15:47:12 +01:00
Gina Häußge 835b973bdc Merge branch 'patch-1' of https://github.com/bortek/OctoPrint into devel
Conflicts:
	docs/api/printer.rst
2014-12-31 15:19:18 +01:00
Gina Häußge bf6a32907c Ported possibility to set external host via headers from reverse proxy to the devel branch 2014-12-31 15:09:31 +01:00
bortek 2b7885c3f8 Update printer.rst 2014-12-30 12:18:39 +01:00
Gina Häußge 749af60796 Merge branch 'master' into devel
Conflicts:
	src/octoprint/server/util.py
	src/octoprint/settings.py
	src/octoprint/templates/index.jinja2
2014-12-30 10:49:03 +01:00
Gina Häußge 87ddcac2fc Don't user server.host but server.forwardedHost as fallback for generated external URLs
Closes #698
2014-12-30 10:20:50 +01:00
Gina Häußge e3383fe4c1 Generated URLs now take X-Forwarded-Host header sent by proxies into account for included host and port 2014-12-29 20:48:33 +01:00
Gina Häußge 292856e1bd Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url 2014-12-29 20:45:54 +01:00
Gina Häußge 3dacaaf03a Merge branch 'master' into devel 2014-12-28 00:20:11 +01:00
Gina Häußge 6307b765e3 Only decrement the image counter if it is set and larger than 0
Backported from devel
2014-12-28 00:19:55 +01:00
Gina Häußge eb2561175d Merge branch 'master' into devel
Conflicts:
	setup.py
	src/octoprint/timelapse.py
2014-12-28 00:18:49 +01:00
Gina Häußge a30e41f0b4 Timelapses: Do not try to use image counter if still set to None and synchronize decrementing of image counter via mutex as well
Possible fixes for #693, the latter maybe also for #690
2014-12-28 00:12:19 +01:00
Gina Häußge 51341f6722 Added removal of pyc files (and their parent folders if they are empty after that) to the python setup.py clean command
(cherry picked from commit 9e014eb)
2014-12-28 00:00:57 +01:00
Gina Häußge fb15751703 Decrease image counter if an image could not be captured from webcam
Should keep rendering of timelapse from breaking if only a couple of images couldn't be captured due to whatever reason. Suggested by @midopple in #344
(cherry picked from commit bf9d5ef)
2014-12-27 23:55:23 +01:00
Gina Häußge a0105bcb2f Better error handling for capture issues during timelapsing
Should help debugging issue #425 and any future problems in that area.
(cherry picked from commit 1a7a468)
2014-12-27 23:52:38 +01:00
Gina Häußge 103e0796b7 Request available slicers and slicing profiles from backend asynchronously when opening the slicing dialog
Should make sure that slicers and new profiles are detected correctly even without reload.

Could maybe help with #689
2014-12-21 15:57:23 +01:00
Gina Häußge 363b23d6e3 Better handling of errors while sending to (disconnected) clients on the websocket 2014-12-21 15:47:24 +01:00
Gina Häußge 52ad02a08a Updated the changelog with a lot of stuff that gone done the past weeks 2014-12-21 15:32:30 +01:00
Gina Häußge 977cf3c383 Added handler for uncaught exceptions to make sure those get logged 2014-12-21 15:32:07 +01:00
Gina Häußge 827ea36d72 Merge remote-tracking branch 'origin/devel' into devel 2014-12-21 15:16:34 +01:00
Gina Häußge 46b0367335 Log a message to octoprint.log if Cura is not fully configured and hence not available for slicing yet.
As suggested in #689
2014-12-21 15:15:59 +01:00
Gina Häußge 596afddfb6 Merge pull request #685 from Bevaz/bug_video_output_filename
Enframed output video filename with quotes.
2014-12-20 18:05:50 +01:00
Gina Häußge 68e4fca347 Merge branch 'devel' into commRefactoring 2014-12-20 10:15:06 +01:00
Gina Häußge 256c2dfdbe More error resilient handling of .metadata.yaml writes in local storage
Writes updated metadata to a backup file first and then copies it atomically (at least under anything that is not windows where the operation is a bit more complicated and hence not atomic)
2014-12-20 01:06:40 +01:00
Gina Häußge 0737ee65bd Support action: commands sent from printer, for now only pause, resume and disconnect are supported, plus a new hook "octoprint.comm.protocol.action" to add handlers of custom actions via plugins.
Added "!!DEBUG:" command to virtual printer to be able to trigger such commands to be sent by it.
2014-12-20 00:31:46 +01:00
Gina Häußge 05ac02770b WIP of command tracking and more intelligent pausing 2014-12-19 23:29:49 +01:00
Gina Häußge 25dc81a5d2 Couple more compatibility fixes to bring this up to par with devel 2014-12-19 23:20:50 +01:00
Gina Häußge 9e27744a05 Fixed some merge errors 2014-12-19 12:40:49 +01:00
Gina Häußge 77df620237 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/printer/__init__.py
	src/octoprint/server/__init__.py
	src/octoprint/server/api/connection.py
	src/octoprint/util/virtual.py
2014-12-19 12:33:57 +01:00
Gina Häußge 8998be66eb Don't accidentally include a newline from the mime headers in the parsed multipart data
Fixes #680
2014-12-19 12:28:02 +01:00
Gina Häußge 1180cac147 Fixed heated bed option not being properly displayed in printer profiles
Fixes #683
2014-12-19 10:01:00 +01:00
Gina Häußge 270231a004 Fixed extruder offsets not being properly editable in printer profiles
Closes #677
2014-12-19 09:54:11 +01:00
Gina Häußge c2f0f6c7c4 [i18n] Translation update 2014-12-18 15:15:23 +01:00
Gina Häußge c7afae38a8 Rolled back appearance settings
Associating them with the current printer profile is misleading as long as a printer profile represents both a physical printer and a type machine. In the future this association will have to be split, to allow for configuration of printers with respective machine profiles (name subject to be changed).
2014-12-18 13:48:19 +01:00
Gina Häußge 873a825e57 Commented out loggers used for debugging/evaluating print time estimation 2014-12-18 12:02:14 +01:00
Gina Häußge dc2318f404 Use the rolling average of the last n estimations instead of the current estimation for reporting print time left 2014-12-18 12:01:01 +01:00
Bevaz 699ed1da4d Enframed output filename with quotes. 2014-12-17 22:08:47 +03:00
Gina Häußge d8b95f845c If the G4 isn't returned, it won't be sent to the printer 2014-12-17 18:33:26 +01:00
Gina Häußge 014d39c11d Fetch estimated print time from cura slicing result, create print time statistics per printer profile, interpolate between stats and live estimation during printing for print time left 2014-12-17 17:31:30 +01:00
Gina Häußge a544a852f2 Some minor cleanup 2014-12-17 12:52:02 +01:00
Gina Häußge 3311a48e3a Merge branch 'issue_658' of https://github.com/vishnubob/OctoPrint into vishnubob-issue_658
Conflicts:
	src/octoprint/util/comm.py
2014-12-17 12:50:37 +01:00
Gina Häußge 5ac908afd4 Pauses in the print job are now cleaned from the basis for print time estimation, also switched to a rolling window approach for determining when estimation becomes stable 2014-12-16 13:27:31 +01:00
Gina Häußge 12a3e659b1 Added new plugin type ProgressPlugin
Plugins can implement that to get notified of progress in both print and slicing jobs in 1% increments.
2014-12-15 21:29:18 +01:00
Gina Häußge b0780af7fa Removed a possible race condition when slicing to the same gcode file in direct succession 2014-12-15 18:35:15 +01:00
Gina Häußge 2ec31c7521 Removed a left-over from print time estimation experiments that got overlooked 2014-12-15 11:38:17 +01:00
Gina Häußge f2562500a3 Print time estimation is now not displayed until it becomes somewhat stable 2014-12-12 23:38:57 +01:00
Gina Häußge 85a567bdab More error resilience when logging success/failure of prints 2014-12-11 18:32:17 +01:00
Gina Häußge 11c415fd17 Actually use caching when reading metadata (was a write-only cache previously, way to go...) 2014-12-11 18:31:48 +01:00
Gina Häußge d67ea41032 Fixed jog controls
Closes #664
2014-12-11 16:10:50 +01:00
Gina Häußge 66357ebe7e "autoconnect" parameter to "connect" command is not mandatory
Closes #675
2014-12-11 15:37:48 +01:00
Gina Häußge 8dbde90a93 Merge branch 'master' into devel 2014-12-09 22:25:19 +01:00
Gina Häußge d2910de121 Added entry to change log 2014-12-09 22:24:53 +01:00
Gina Häußge c5be9908c5 Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups 2014-12-09 22:20:55 +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
Giles Hall e844d42275 added G4 hook to increase the timeout for serial communication 2014-11-28 19:28:03 +00: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 a0a6f958d9 Improved cancelling by new lock, should make it even more snappier 2014-11-13 13:08:11 +01:00
Gina Häußge 16d156b530 This should hopefully get cancelling to react a bit snappier again
TODO: figure out why sometimes writetimeouts show up
2014-11-12 17:26:41 +01:00
Gina Häußge 420226b6c0 Added command processing phase "sending" which replaces former phase "sent", which in turn was moved _after_ the command has actually been sent
This solves a deadlock which can occur if a blocking command is denied sending due to buffer restrictions. It couldn't then ever be actually sent after denied once.
2014-11-12 12:38:15 +01:00
Gina Häußge da8e72b0d6 Use a bounded semaphore for properly limiting the max count of items in the queue, also track removed items upon send_queue.clear 2014-11-12 12:35:06 +01:00
Gina Häußge ef13cbecfd Do not delete lines from the send queue upon cancel that were already prepared (got a line number) 2014-11-12 11:50:58 +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 5910bba30e Define G28 and G29 as blocking commands, since apparently the firmware blocks writes (even buffered ones) while those are active 2014-11-10 19:48:02 +01:00
Gina Häußge 19ba3b1f99 command might be None after hook processors are through with it 2014-11-10 16:39:20 +01:00
Gina Häußge 23bc6b8df7 Added keywords arguments to pause_print to disable toggle and only resume or pause
If the printer is paused and the method is called with only_pause=True, nothing will happen.

If the printer is printing and the method is called with only_resume=True, nothing will happen.
2014-11-10 13:11:46 +01:00
Gina Häußge 69bea0f5b0 Hooks always get the value of with_line_number, no need for a keyword argument there 2014-11-10 13:00:18 +01:00
Gina Häußge 3c53394f4b Plugin manager returned wrong data types when no plugins/hooks where found 2014-11-10 12:58:15 +01:00
Gina Häußge 8741053dfc Merge branch 'dattas-commRefactoring-hook' into commRefactoring 2014-11-10 12:33:39 +01:00
Gina Häußge 8752f70ff3 Added multiple hooks for the individual processing phases, gcode hooks now have to process the parsed command (might be unknown) 2014-11-10 12:33:24 +01:00
Gina Häußge 2b66df39b6 Merge branch 'commRefactoring-hooks' of http://github.com/dattas/OctoPrint into dattas-commRefactoring-hook 2014-11-10 12:23:36 +01:00
Gina Häußge 17bb0e693d Version resource was defined twice 2014-11-10 12:13:42 +01:00
Gina Häußge 94e5b5fdaf Virtual printer did not send repetier-style target temperature messages while heating up 2014-11-10 12:13:18 +01:00
Gina Häußge 497ec5c6b2 RepetierTextualProtocol now makes use of overriding RepRapProtocol.MESSAGE_TEMPERATURE 2014-11-10 12:12:33 +01:00
Gina Häußge eaeae8d5ec Some small refactorings
- _nack_lines, _nack_lock, _nacks_before_resend => _sent_lines, _sent_lock, _sent_before_resend
- some reordering in the message processing
- referal to MESSAGE and COMMAND instances via self.__class__ instead of RepRapProtocol => allows sub classes to override MESSAGE and COMMAND definitions
2014-11-10 12:11:45 +01:00
Gina Häußge 3a05a2653b Fixed issue where peek and pop on send_queue could act on different
entries.

After sending the sent entry is now not removed from the queue by a
pop but an explicit remove instead. Removal maintains the queue's
heap invariant.
2014-11-10 12:07:49 +01:00
Gina Häußge 0ca63017c7 Merge remote-tracking branch 'origin/commRefactoring-rxcache' into commRefactoring-rxcache 2014-11-10 09:23:56 +01:00
Gina Häußge ea3416693c Merge branch 'devel' into commRefactoring-rxcache 2014-11-10 09:22:20 +01: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
Dattas Moonchaser 6dc56af3fa Add octoprint.comm.protocol.gcode hooks 2014-11-08 14:36:57 -07:00
Gina Häußge af297c2031 Merge pull request #643 from dattas/commRefactoring-unknowncmds
commRefactoring-Unknown commands
2014-11-08 19:47:36 +01:00
Dattas Moonchaser 024cf81238 Allow gcode commands to get farther into the processing, but ensure they don't get pushed to the printer 2014-11-08 11:36:31 -07: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 9d5a500b25 Cancelling print jobs should now work again 2014-11-07 22:56:49 +01:00
Gina Häußge 4bab1975c8 Funnily enough that clear_for_send was still decremented at the wrong location 2014-11-07 14:26:40 +01:00
Gina Häußge eae4153158 Some performance optimizations
- self._clear_for_send was decremented at wrong location
- added semaphore for use in fill queue processing (max entries 20, fill queue acquires, send queue releases upon send)
- added signal of state for use in fill queue processing, no more sleep-wake-check-loops there
- CommandQueue.peek also was not synchronized

Found a couple of issue to tackle next (see TODOs)
2014-11-07 13:29:11 +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
Gina Häußge a92aa96623 Proper clearing of send queue on cancel and proper signaling of print job done when last command gets acknowledged 2014-11-06 18:44:40 +01:00
Gina Häußge ccf0ab3b51 Let's set the default buffer size to something that should fit most configurations
These appear to be the used rx cache sizes:

  - Marlin on AT90USB boards (e.g. Printrboard) => 63 bytes
  - Marlin anywhere else, using MarlinSerial implementation => 127 bytes
  - Repetier by default => 127 bytes
  - Repetier if EXTERNALSERIAL is defined in Configuration => 63 bytes

63 bytes should be pretty much safe in any case, user can increase that if falling into the 127 bytes group.
2014-11-06 14:32:51 +01:00
Gina Häußge 7259c1c2ef Fixed a race condition that made print jobs stall, also fixed temperature reporting and a couple other things
See #568
2014-11-06 14:22:48 +01:00
Gina Häußge d66675c672 Actually forward the protocol and transport options to the protocol and transport instances upon connect...
Yeah, I don't know why that was missing either.
2014-11-06 08:54:05 +01:00
Gina Häußge 38483b0c67 Further work on the communication layer
Write blocks on the serial interface are now handled gracefully (also the write timeout has been set to a more sane value, maybe that can be lowered more?).

I'm still observing some weird "stops" when printing the valentine dragon thingy on a Printrbot Simple, still trying to find out what's happening there exactly.
2014-11-05 15:52:31 +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
Gina Häußge 19de4053fe WIP: More work on the communication layer
Split command processing into "queued", "sent" and "acknowledged" events, added command acknowledgement tracking via nack_line queue, using that too for resend implementation

Problem: Deadlock when using a real printer after receiving first "ok" response to "N0 M110 S0" right at the beginning of the print.
2014-11-03 21:37:04 +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 d0ff6d1579 Fix: it should not be possible to access/increment/decrement line numbers concurrently from different threads 2014-10-31 22:06:06 +01:00
Gina Häußge 105b68c807 Move the OK processing at the end of the message receiver for now to make temperature reporting outside of heatup work on Marlin again 2014-10-31 21:45:08 +01:00
Gina Häußge 97a6d8a15e Our transport timeout is a fairly normal thing and no reason for a warn in the log 2014-10-31 21:29:08 +01:00
Gina Häußge 26fa3df4aa Fixed line number generation outside of sending queue (and removed some left-overs) 2014-10-31 21:28:26 +01:00
Gina Häußge 9a336336d7 Removed unused method self._useChecksum 2014-10-31 19:04:12 +01:00
Gina Häußge 047d7f5046 self.disconnect had wrong signature 2014-10-31 19:02:48 +01:00
Gina Häußge 4fc561dab5 Always send checksum by default 2014-10-31 19:02:29 +01:00
Gina Häußge 785ac07de9 Removed self._ping_pong (can be done by setting self._rx_cache_size to 0) and self._rx_cache_fill (can be done by sum(self._nack_lines)), made self._rx_cache_size configurable 2014-10-31 18:51:54 +01:00
Gina Häußge 41c6978880 Changed some things refering to other things changed in devel 2014-10-31 17:59:05 +01:00
Gina Häußge f7ebc4ec11 Merge remote-tracking branch 'presslab-us/commRefactoring-rxcache' into commRefactoring-rxcache 2014-10-31 17:55:36 +01:00
Gina Häußge c06e8f47f0 Fixed queue processing of virtual printer 2014-10-31 17:54:01 +01:00
Gina Häußge dceb5dccd3 Made virtual printer a bit more "lifelike"
Added (configurable) queue for buffered G codes (G0, G1, G2, G3, G28, G29-G32), incoming queue and queue clearing upon resend

Needed for testing stuff for #568
2014-10-31 15:40:01 +01:00
Gina Häußge 7a50138ae3 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/settings.py
2014-10-31 14:50:59 +01: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 43cead8249 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/printer.py
	src/octoprint/server/api/files.py
2014-10-30 14:21:27 +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
Ryan Press 8492944fb5 Fix sign of 'nice' level. 2014-10-29 19:27:50 -07: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
Ryan Press f7433de2bf Fix temperature polling. 2014-10-26 12:51:27 -07:00
Ryan Press bbd46fd3a6 Reimplement missing events in commRefactoring. 2014-10-26 08:57:46 -07:00
Ryan Press 077486c838 Add support for rx cache to increase throughput to printer.
This can be disabled by ticking Ping-Pong in the settings.
2014-10-26 08:56:50 -07:00
Ryan Press baedab5931 Increase nice level in init script for higher priority. 2014-10-26 08:56:07 -07: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 36c8f25fd1 Honor paused state and don't eat the clear_for_send flag when not actually sending something 2014-09-17 18:15:10 +02:00
Gina Häußge b3050f1058 If command handler returns, _preprocess_command should return None not "None" 2014-09-17 17:33:58 +02:00
Gina Häußge a04a61f61b M0 command handler needs to return tuple, not just None 2014-09-17 17:23:51 +02:00
Gina Häußge 58204248bb Don't wait for "start" from printer if not configured like that 2014-09-17 17:08:35 +02:00
Gina Häußge a47740ae28 Merge branch 'devel' into commRefactoring 2014-09-15 21:55:35 +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 48d6a27fad Merge branch 'devel' into commRefactoring 2014-09-03 18:39:36 +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
Gina Häußge 5ffcd78f27 Merge remote-tracking branch 'origin/commRefactoring' into commRefactoring 2014-08-30 20:03:23 +02:00
Gina Häußge de9dd77b50 Merge branch 'devel' into commRefactoring 2014-08-30 20:02:36 +02:00
Gina Häußge 51c77be7a2 Don't overwrite query string of webcam URI
If there's a query already present, just append the timestamp to it with a & in between instead of creating a new query.
2014-08-11 22:25:09 +02:00
Gina Häußge f98563cbe9 Merge branch 'devel' into commRefactoring 2014-08-11 18:41:31 +02:00
Gina Häußge 8c8059db30 Protocol and Transport classes are now detected automatically and the one to use can be specified by config, also made standard control commands part of the protocol interface 2014-07-24 14:24:04 +02:00
Gina Häußge fa586426fa Connection handshake should now be more error resilient 2014-07-12 19:55:13 +02:00
Gina Häußge 60a1bf0d43 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/printer.py
2014-07-12 19:37:38 +02:00
Gina Häußge a48f194350 Repetier protocol specifics, better virtual printer, proper handling of finished print jobs 2014-06-02 00:32:29 +02:00
Gina Häußge 78f0ec94ea SD Upload appears to be working again 2014-06-01 18:43:13 +02:00
Gina Häußge 44f9e756da Merge branch 'devel' into commRefactoring 2014-06-01 11:54:14 +02:00
Gina Häußge 3d992d56cd And even more work, trying to get the SD stuff and the offsets working again, also refactored some things here and there 2014-06-01 11:52:06 +02:00
Gina Häußge 72f7b4627f Merge branch 'devel' into commRefactoring 2014-05-30 18:38:23 +02:00
Gina Häußge 5c1f165079 Connection options, sd initialization and releasing, refactoring ... more work, off I go then 2014-05-29 22:11:11 +02:00
Gina Häußge 95755ba515 Merge branch 'devel' into commRefactoring 2014-05-29 18:01:15 +02:00
Gina Häußge 791e4e26a9 More work, print jobs at least on the virtual printer are starting to work now 2014-05-29 17:40:49 +02:00
Gina Häußge 4d61963894 Merge branch 'devel' into commRefactoring 2014-05-29 13:17:31 +02:00
Gina Häußge 5622a9c565 more work on the comm refactoring, starting to resemble something working again 2014-05-29 13:02:25 +02:00
Gina Häußge 2e5069d5a1 Merge branch 'devel' into commRefactoring 2014-05-29 10:45:30 +02:00
Gina Häußge 4cd692e061 Merge branch 'commRefactoring' of https://github.com/foosel/OctoPrint into commRefactoring
Conflicts:
	src/octoprint/printer.py
2014-05-29 10:40:04 +02:00
Gina Häußge 216a88c00c WIP 2014-05-15 15:19:48 +02:00
Gina Häußge 10f1917589 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/settings.py
	src/octoprint/util/virtual.py
2014-03-15 20:39:33 +01:00
Gina Häußge 26f7d6e517 Added logging and filtering of non-ASCII filenames of files returned from SD card, still WIP 2014-02-23 11:07:09 +01:00
Gina Häußge b7b2e99ab1 Merge branch 'devel' into commRefactoring 2014-02-17 11:39:21 +01:00
Gina Häußge 0966b231e8 Some more WIP 2014-01-31 11:41:40 +01:00
Gina Häußge 00e1a1962b Started working on new modular comm layer, checking in just for the record, not yet usable 2014-01-27 13:15:15 +01:00
135 changed files with 163733 additions and 5282 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
+213
View File
@@ -0,0 +1,213 @@
# OctoPrint Changelog
## 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
* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A
connection to a printer will always have a printer profile associated.
* OctoPrint now supports `action:...` commands received via debug messages (`// action:...`) from the printer. Currently supported are
- `action:pause`: Pauses the current job in OctoPrint
- `action:resume`: Resumes the current job in OctoPrint
- `action:disconnect`: Disconnects OctoPrint from the printer
### 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).
* A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list
as well). This dialog also allows specifying which action to take after slicing has been completed (none, selecting the
sliced GCODE for printing or starting to print it directly)
* Slicers themselves are integrated into the system via ``SlicingPlugins``.
* The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the
[CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See
[the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to
accommodate the new integration.
* The "Slicing done" notification is now colored green ([#558](https://github.com/foosel/OctoPrint/issues/558)).
* The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI).
* File management now supports STL files as first class citizens (including UI adjustments to allow management of
uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI)
* 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"
* "Print time left" is now not displayed until it becomes somewhat stable. Display in web interface now also happens
in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one. Additionally
OctoPrint will use data from prior prints to enhance the initial print time estimation.
* Added handler for uncaught exceptions to make sure those get logged, should make the logs even more useful for analysing
bug reports
* The server now tracks the modification date of the configuration file and reloads it prior to saving the config if
it has been changed during runtime by external editing, hence no config settings added manually while the server
was running should be overwritten anymore.
* Automatically hard-reload the UI if upon reconnecting to the server a new version is detected.
* Better handling of errors on the websocket - no more logging of the full stack trace to the log, only a warning
message for now.
### Bug Fixes
* [#435](https://github.com/foosel/OctoPrint/issues/435) - Always interpret negative duration (e.g. for print time left)
as 0
* [#633](https://github.com/foosel/OctoPrint/issues/633) - Correctly interpret temperature lines from multi extruder
setups under Smoothieware
* [#556](https://github.com/foosel/OctoPrint/issues/556) - Allow login of the same user from multiple browsers without
side effects
* [#680](https://github.com/foosel/OctoPrint/issues/680) - Don't accidentally include a newline from the MIME headers
in the parsed multipart data from file uploads
* Various fixes of bugs in newly introduced features and improvements:
* [#625](https://github.com/foosel/OctoPrint/pull/625) - Newly added GCODE files were not being added to the analysis
queue
* [#664](https://github.com/foosel/OctoPrint/issues/664) - Fixed jog controls again
* [#677](https://github.com/foosel/OctoPrint/issues/677) - Fixed extruder offsets not being properly editable in
printer profiles
* [#683](https://github.com/foosel/OctoPrint/issues/683) - Fixed heated bed option not being properly displayed in
printer profiles
* Various fixes without tickets:
* GCODE viewer now doesn't stumble over completely extrusionless GCODE files
* Do not deliver the API key on settings API unless user has admin rights
* Don't hiccup on slic3r filament_diameter comments in GCODE generated for multi extruder setups
## 1.1.2 (Unreleased)
### Improvements
* Added deletion of `*.pyc` files to `python setup.py clean` command, should help tremendously when switching branches (backported
from [9e014eb](https://github.com/foosel/OctoPrint/commit/9e014eba1feffde11ed0601d9c911b8cac9f3fb0))
### Bug Fixes
* [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated
by versioneer
* [IRC] - Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups
* [ML] - Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url
* [unreported] & [#698](https://github.com/foosel/OctoPrint/issues/698) - Generated URLs now take X-Forwarded-Host header
sent by proxies into account for included host and port, also fixed [#698](https://github.com/foosel/OctoPrint/issues/698)
introduced by this
* Small fixes for timelapse creation:
- [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there
was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b)
and [bf9d5ef](https://github.com/foosel/OctoPrint/commit/bf9d5efe43a1e57aacd8512125082ddca06b4efc))
- [#693](https://github.com/foosel/OctoPrint/issues/693) - Try not to capture an image if image counter is still unset
- [unreported] Synchronize image counter decrementing as well as incrementing to prevent rare race conditions when generating the
image file names
## 1.1.1 (2014-10-27)
### Improvements
* The API is now enabled by default and the API key -- if not yet set -- will be automatically generated on first
server start and written back into ``config.yaml``
* Event subscriptions are now enabled by default (it was an accident that they weren't)
* Generate the key used for session hashing individually for each server instance
* Generate the salt used for hashing user passwords individually for each server instance
### Bug Fixes
* [#580](https://github.com/foosel/OctoPrint/issues/580) - Properly unset job data when instructed so by callers
* [#604](https://github.com/foosel/OctoPrint/issues/604) - Properly initialize settings basedir on server startup
* [IRC] Also allow downloading .g files via Tornado
([Commits](https://github.com/foosel/OctoPrint/compare/1.1.0...1.1.1))
## 1.1.0 (2014-09-03)
### New Features
* New REST API, including User API Keys additionally to the global API key. Please note that **this will break existing
API clients** as it replaces the old API (same endpoint). You can find the documentation of the new API at
[docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/api/index.html).
* New Event structure allows more flexibility regarding payload data, configuration files will be migrated automatically.
You can find the documentation of the new event format and its usage at [docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/events/index.html).
* Support for multi extruder setups. With this OctoPrint now in theory supports an unlimited amount of extruders, however
for now it's artificially limited to 9.
* Log files can be accessed from within the browser via the Settings dialog ([#361](https://github.com/foosel/OctoPrint/pull/361))
* Timelapses can now have a post-roll duration configured which will be rendered into the video too to not let it
end so abruptly ([#384](https://github.com/foosel/OctoPrint/issues/384))
* The terminal tab now has a command history ([#388](https://github.com/foosel/OctoPrint/pull/388))
### Improvements
* Stopping the application via Ctrl-C produces a less scary message ([#277](https://github.com/foosel/OctoPrint/pull/277))
* Webcam stream is disabled when control tab is not in focus, reduces bandwidth ([#316](https://github.com/foosel/OctoPrint/issues/316))
* M and G commands entered in Terminal tab are automatically converted to uppercase
* GCODE viewer now only loads automatically if GCODE file size is beneath certain threshold (different ones for desktop
and mobile devices), only actually loads file if user acknowledges that this might be too much for his browser
* Added time needed for printing file to PrintDone event's payload ([#333](https://github.com/foosel/OctoPrint/issues/333))
* Also provide the filename (basename without the path) in print events
* Support for circular beds in the GCODE viewer ([#407](https://github.com/foosel/OctoPrint/pull/407))
* The dimensions of the print bed can now be configured via the Settings ([#396](https://github.com/foosel/OctoPrint/pull/396))
* Target temperature reporting format of Repetier Firmware is now supported as well ([360](https://github.com/foosel/OctoPrint/issues/360))
* Version tracking now based on git tagging and [versioneer](https://github.com/warner/python-versioneer/). Version number,
git commit and branch get reported in the format `<version tag>-<commits since then>-g<commit hash> (<branch> branch)`,
e.g. `1.2.0-dev-172-ga48b5de (devel branch)`.
* Made "Center viewport on model" and "Zoom in on model" in the GCODE viewer automatically deselect and de-apply if
viewport gets manipulated by the user ([#398](https://github.com/foosel/OctoPrint/issues/398))
* GCODE viewer now interprets inverted axes for printer control and mirrors print bed accordingly ([#431](https://github.com/foosel/OctoPrint/issues/431))
* Added `clean` command to `setup.py`, removes old build artifacts (mostly interesting for developers)
* Added version resource on API which reports application and API version
* Made the navbar static instead of fixed to improve usability on mobile devices ([#257](https://github.com/foosel/OctoPrint/issues/257))
* Switch to password field upon enter in username field, submit login form upon enter in password field
* Changed default path to OctoPrint executable in included init-script to `/usr/local/bin/octoprint` (the default when
installing via `python setup.py install`)
### Bug Fixes
* Properly calculate time deltas (forgot to factor in days)
* [#35](https://github.com/foosel/OctoPrint/issues/35) - GCODE viewer has been modularized, options are now functional
* [#337](https://github.com/foosel/OctoPrint/issues/337) - Also recognize `--iknowwhatimdoing` when running as daemon
* [#357](https://github.com/foosel/OctoPrint/issues/357) - Do not run GCODE analyzer when a print is ongoing
* [#381](https://github.com/foosel/OctoPrint/issues/381) - Only list those SD files that have an ASCII filename
* Fixed a race condition that could occur when pressing "Print" (File not opened yet, but attempt to read from it)
* [#398](https://github.com/foosel/OctoPrint/issues/398) - Fixed interfering options in GCODE viewer
* [#399](https://github.com/foosel/OctoPrint/issues/399) & [360](https://github.com/foosel/OctoPrint/issues/360) - Leave
bed temperature unset when not detected (instead of dying a horrible death)
* [#492](https://github.com/foosel/OctoPrint/issues/492) - Fixed a race condition which could lead to an attempt to read
from an already closed serial port, causing an error to be displayed to the user
* [#257](https://github.com/foosel/OctoPrint/issues/257) - Logging in on mobile devices should now work
* [#476](https://github.com/foosel/OctoPrint/issues/476) - Also update the metadata correctly when an analysis finishes
* Various fixes of bugs in newly introduced features and improvements:
- [#314](https://github.com/foosel/OctoPrint/issues/314) - Use G28 for homing (G1 was copy and paste error)
- [#317](https://github.com/foosel/OctoPrint/issues/317) - Fixed "load and print" function
- [#326](https://github.com/foosel/OctoPrint/issues/326) - Fixed refresh of SD file list
- [#338](https://github.com/foosel/OctoPrint/issues/338) - Refetch file list when deleting a file
- [#339](https://github.com/foosel/OctoPrint/issues/339) - More error resilience when handling temperature offset data from the backend
- [#345](https://github.com/foosel/OctoPrint/issues/345) - Also recognize such temperature reports that do not contain a `T:` but a `T0:`
- [#377](https://github.com/foosel/OctoPrint/pull/377) - URLs in API examples fixed
- [#378](https://github.com/foosel/OctoPrint/pull/378) - Fixed crash of API call when `getStartTime()` returns None
- [#379](https://github.com/foosel/OctoPrint/pull/379) - Corrected response code for connection success
- [#414](https://github.com/foosel/OctoPrint/pull/414) - Fix style attribute for Actual column header
([Commits](https://github.com/foosel/OctoPrint/compare/1.0.0...1.1.0))
## 1.0.0 (2014-06-22)
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.
-73
View File
@@ -1,73 +0,0 @@
# OctoPrint Release Notes
## 1.1.0
### New Features
* New REST API, including User API Keys additionally to the global API key. Please note that **this will break existing
API clients** as it replaces the old API (same endpoint). You can find the documentation of the new API at
[docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/api/index.html).
* New Event structure allows more flexibility regarding payload data, configuration files will be migrated automatically.
You can find the documentation of the new event format and its usage at [docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/events/index.html).
* Support for multi extruder setups. With this OctoPrint now in theory supports an unlimited amount of extruders, however
for now it's artificially limited to 9.
* Log files can be accessed from within the browser via the Settings dialog ([#361](https://github.com/foosel/OctoPrint/pull/361))
* Timelapses can now have a post-roll duration configured which will be rendered into the video too to not let it
end so abruptly ([#384](https://github.com/foosel/OctoPrint/issues/384))
* The terminal tab now has a command history ([#388](https://github.com/foosel/OctoPrint/pull/388))
### Improvements
* Stopping the application via Ctrl-C produces a less scary message ([#277](https://github.com/foosel/OctoPrint/pull/277))
* Webcam stream is disabled when control tab is not in focus, reduces bandwidth ([#316](https://github.com/foosel/OctoPrint/issues/316))
* M and G commands entered in Terminal tab are automatically converted to uppercase
* GCODE viewer now only loads automatically if GCODE file size is beneath certain threshold (different ones for desktop
and mobile devices), only actually loads file if user acknowledges that this might be too much for his browser
* Added time needed for printing file to PrintDone event's payload ([#333](https://github.com/foosel/OctoPrint/issues/333))
* Also provide the filename (basename without the path) in print events
* Support for circular beds in the GCODE viewer ([#407](https://github.com/foosel/OctoPrint/pull/407))
* The dimensions of the print bed can now be configured via the Settings ([#396](https://github.com/foosel/OctoPrint/pull/396))
* Target temperature reporting format of Repetier Firmware is now supported as well ([360](https://github.com/foosel/OctoPrint/issues/360))
* Version tracking now based on git tagging and [versioneer](https://github.com/warner/python-versioneer/).
* Made "Center viewport on model" and "Zoom in on model" in the GCODE viewer automatically deselect and de-apply if
viewport gets manipulated by the user ([#398](https://github.com/foosel/OctoPrint/issues/398))
* GCODE viewer now interprets inverted axes for printer control and mirrors print bed accordingly ([#431](https://github.com/foosel/OctoPrint/issues/431))
* Added `clean` command to `setup.py`, removes old build artifacts (mostly interesting for developers)
* Added version resource on API which reports application and API version
* Made the navbar static instead of fixed to improve usability on mobile devices ([#257](https://github.com/foosel/OctoPrint/issues/257))
* Switch to password field upon enter in username field, submit login form upon enter in password field
* Changed default path to OctoPrint executable in included init-script to `/usr/local/bin/octoprint` (the default when
installing via `python setup.py install`)
### Bug Fixes
* Properly calculate time deltas (forgot to factor in days)
* [#35](https://github.com/foosel/OctoPrint/issues/35) - GCODE viewer has been modularized, options are now functional
* [#337](https://github.com/foosel/OctoPrint/issues/337) - Also recognize `--iknowwhatimdoing` when running as daemon
* [#357](https://github.com/foosel/OctoPrint/issues/357) - Do not run GCODE analyzer when a print is ongoing
* [#381](https://github.com/foosel/OctoPrint/issues/381) - Only list those SD files that have an ASCII filename
* Fixed a race condition that could occur when pressing "Print" (File not opened yet, but attempt to read from it)
* [#398](https://github.com/foosel/OctoPrint/issues/398) - Fixed interfering options in GCODE viewer
* [#399](https://github.com/foosel/OctoPrint/issues/399) & [360](https://github.com/foosel/OctoPrint/issues/360) - Leave
bed temperature unset when not detected (instead of dying a horrible death)
* [#492](https://github.com/foosel/OctoPrint/issues/492) - Fixed a race condition which could lead to an attempt to read
from an already closed serial port, causing an error to be displayed to the user
* [#257](https://github.com/foosel/OctoPrint/issues/257) - Logging in on mobile devices should now work
* [#476](https://github.com/foosel/OctoPrint/issues/476) - Also update the metadata correctly when an analysis finishes
* Various fixes of bugs in newly introduced features and improvements:
- [#314](https://github.com/foosel/OctoPrint/issues/314) - Use G28 for homing (G1 was copy and paste error)
- [#317](https://github.com/foosel/OctoPrint/issues/317) - Fixed "load and print" function
- [#326](https://github.com/foosel/OctoPrint/issues/326) - Fixed refresh of SD file list
- [#338](https://github.com/foosel/OctoPrint/issues/338) - Refetch file list when deleting a file
- [#339](https://github.com/foosel/OctoPrint/issues/339) - More error resilience when handling temperature offset data from the backend
- [#345](https://github.com/foosel/OctoPrint/issues/345) - Also recognize such temperature reports that do not contain a `T:` but a `T0:`
- [#377](https://github.com/foosel/OctoPrint/pull/377) - URLs in API examples fixed
- [#378](https://github.com/foosel/OctoPrint/pull/378) - Fixed crash of API call when `getStartTime()` returns None
- [#379](https://github.com/foosel/OctoPrint/pull/379) - Corrected response code for connection success
- [#414](https://github.com/foosel/OctoPrint/pull/414) - Fix style attribute for Actual column header
([Commits](https://github.com/foosel/OctoPrint/compare/1.0.0...1.1.0))
## 1.0.0
First release with new versioning scheme.
+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
+77 -1
View File
@@ -755,6 +755,61 @@ Retrieve the current SD state
:statuscode 200: No error
:statuscode 404: If SD support has been disabled in OctoPrint's config.
.. _sec-api-printer-arbcommand:
Send an arbitrary command to the printer
========================================
.. http:post:: /api/printer/command
Sends any command to the printer via the serial interface. Should be used with some care as some commands can interfere with
or even stop a running print job.
Expects a :ref:`Arbitrary Command Request <sec-api-printer-datamodel-arbcommand>` as the request's body.
If successful returns a :http:statuscode:`204` and an empty body.
**Example for sending a single command**
.. sourcecode:: http
POST /api/printer/command HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "M106"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example for sending multiple commands**
.. sourcecode:: http
POST /api/printer/command HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"commands": [
"M18",
"M106 S0"
]
}
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: Single command to send to the printer, mutually exclusive with ``commands``.
:json string commands: List of commands to send to the printer, mutually exclusive with ``command``.
:statuscode 204: No error
.. _sec-api-printer-datamodel:
Datamodel
@@ -783,7 +838,7 @@ Full State Response
- The printer's sd state data
* - ``state``
- 0..1
- :ref:`Printer State <sec-api-printer-datamodel-printerstate>`
- :ref:`Printer State <sec-api-datamodel-printer-state>`
- The printer's general state
.. _sec-api-printer-datamodel-temps:
@@ -831,3 +886,24 @@ SD State
- Boolean
- Whether the SD card has been initialized (``true``) or not (``false``).
.. _sec-api-printer-datamodel-arbcommand:
Arbitrary Command Request
-------------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``command``
- 0..1
- String
- Single command to send to the printer, mutually exclusive with ``commands``.
* - ``commands``
- 0..*
- Array of String
- Multiple commands to send to the printer (in the given order), mutually exclusive with ``command``.
+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.
+28 -1
View File
@@ -96,6 +96,10 @@ ClientOpened
ClientClosed
A client has disconnected from the webserver
Payload:
* ``remoteAddress``: the remote address (IP) of the client that disconnected
Printer communication
---------------------
@@ -132,7 +136,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 +332,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 +343,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 +360,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
+1
View File
@@ -3,3 +3,4 @@ nose>=1.3.0
sphinxcontrib-httpdomain
sphinx_rtd_theme
po2json
ddt
+3
View File
@@ -10,3 +10,6 @@ pyserial
netaddr
watchdog
sarge
netifaces
pylru
rsa
+2 -1
View File
@@ -19,6 +19,7 @@ PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="Octoprint Daemon"
NAME="Octoprint"
DAEMON=/usr/local/bin/octoprint
NICE=-10
PIDFILE=/var/run/$NAME.pid
PKGNAME=octoprint
SCRIPTNAME=/etc/init.d/$PKGNAME
@@ -72,7 +73,7 @@ do_start()
RETVAL="$?"
if [ $RETVAL != 0 ]; then
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile \
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile --nicelevel $NICE\
--exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK -- $DAEMON_ARGS
RETVAL="$?"
fi
+65 -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,57 @@ class CleanCommand(Command):
pass
def run(self):
# build folder
if os.path.exists('build'):
print "Deleting build directory"
shutil.rmtree('build')
# eggs
eggs = glob.glob('OctoPrint*.egg-info')
for egg in eggs:
print "Deleting %s directory" % egg
shutil.rmtree(egg)
# pyc files
def delete_folder_if_empty(path, applied_handler):
if not applied_handler:
return
if len(os.listdir(path)) == 0:
shutil.rmtree(path)
print "Deleted %s since it was empty" % path
def delete_file(path):
os.remove(path)
print "Deleted %s" % path
import fnmatch
_recursively_handle_files(
os.path.abspath("src"),
lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"),
folder_handler=delete_folder_if_empty,
file_handler=delete_file
)
# pyc files
def delete_folder_if_empty(path, applied_handler):
if not applied_handler:
return
if len(os.listdir(path)) == 0:
shutil.rmtree(path)
print "Deleted %s since it was empty" % path
def delete_file(path):
os.remove(path)
print "Deleted %s" % path
import fnmatch
_recursively_handle_files(
os.path.abspath("src"),
lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"),
folder_handler=delete_folder_if_empty,
file_handler=delete_file
)
class NewTranslation(Command):
description = "create a new translation"
@@ -219,7 +283,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)
+6
View File
@@ -0,0 +1,6 @@
# coding=utf-8
__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 Gina Häußge - Released under terms of the AGPLv3 License"
+589
View File
@@ -0,0 +1,589 @@
# coding=utf-8
__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 Gina Häußge - Released under terms of the AGPLv3 License"
import logging
import os
import time
from octoprint.events import eventManager, Events
from octoprint.comm.transport import MessageReceiver, StateReceiver, LogReceiver, State as TransportState
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings
class Protocol(MessageReceiver, StateReceiver, LogReceiver):
def __init__(self, transport_factory, protocol_listener=None):
self._logger = logging.getLogger(__name__)
self._transport = transport_factory(self, self, self)
self._transport_properties = self._transport.get_properties()
self._protocol_listener = protocol_listener
self._state = State.OFFLINE
self._heatup_start_time = None
self._heatup_time_lost = 0.0
self._pause_start_time = None
self._pause_time_lost = 0.0
self._current_file = None
self._current_z = 0.0
self._sd_available = False
self._sd_files = []
self._current_temperature = {}
self._temperature_offsets = {}
self._error = None
def _reset(self):
self._heatup_start_time = None
self._heatup_time_lost = 0.0
self._current_file = None
self._current_z = 0.0
self._sd_available = False
self._sd_files = []
self._current_temperature = {}
self._temperature_offsets = {}
self._error = None
##~~ public
def connect(self, protocol_options, transport_options):
self._transport.connect(transport_options)
def disconnect(self, on_error=False):
if self.is_printing():
payload = None
if self._current_file is not None:
payload = {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
}
eventManager().fire(Events.PRINT_FAILED, payload)
self._transport.disconnect(on_error)
def send_manually(self, command, high_priority=False):
pass
def select_file(self, filename, origin):
pass
def deselect_file(self):
pass
def start_print(self):
if self._current_file is None:
raise ValueError("No file selected for printing")
self._heatup_start_time = None
self._heatup_time_lost = 0.0
self._current_file.start()
self._changeState(State.PRINTING)
eventManager().fire(Events.PRINT_STARTED, {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
})
def pause_print(self, only_pause=None, only_resume=None):
payload = {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
}
if self._state == State.PRINTING and not only_resume:
self._pause_start_time = time.time()
self._changeState(State.PAUSED)
eventManager().fire(Events.PRINT_PAUSED, payload)
elif self._state == State.PAUSED and not only_pause:
if self._pause_start_time:
self._pause_time_lost += time.time() - self._pause_start_time
self._pause_start_time = None
self._changeState(State.PRINTING)
eventManager().fire(Events.PRINT_RESUMED, payload)
def cancel_print(self):
eventManager().fire(Events.PRINT_CANCELLED, {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
})
self._changeState(State.OPERATIONAL)
self._print_cancelled()
if self._protocol_listener is not None:
self._protocol_listener.onPrintjobCancelled(self)
def _print_cancelled(self):
pass
def init_sd(self):
pass
def release_sd(self):
pass
def refresh_sd_files(self):
pass
def add_sd_file(self, path, local, remote):
pass
def remove_sd_file(self, filename):
pass
def get_state(self):
return self._state
def get_current_temperatures(self):
return self._current_temperature
def get_temperature_offsets(self):
result = {}
result.update(self._temperature_offsets)
return result
def set_temperature_offsets(self, new_temperature_offsets):
offsets = {}
offsets.update(new_temperature_offsets)
self._temperature_offsets = offsets
def get_sd_files(self):
return self._sd_files
def get_print_time(self):
if self._current_file is None or self._current_file.getStartTime() is None:
return None
else:
return max(int(time.time() - self._current_file.getStartTime() - self._heatup_time_lost - self._pause_time_lost), 0)
def get_connection_options(self):
return self._transport.get_connection_options()
def get_current_connection(self):
return self._transport.get_current_connection()
##~~ granular state detection for implementations
def is_heating_up(self):
return self._heatup_start_time is not None
def is_printing(self):
return self._state == State.PRINTING or self._state == State.PAUSED
def is_sd_printing(self):
return isinstance(self._current_file, PrintingSdFileInformation) and self.is_busy()
def is_streaming(self):
return self._state == State.STREAMING
def is_busy(self):
return self.is_printing() or self.is_streaming()
def is_operational(self):
return self._state == State.OPERATIONAL
def is_sd_ready(self):
return self._sd_available
##~~ state tracking and reporting to protocol listener
def _changeState(self, newState):
oldState = self._state
self._state = newState
self._stateChanged(newState)
if self._protocol_listener is not None:
self._protocol_listener.onStateChange(self, oldState, newState)
def _stateChanged(self, newState):
pass
def _updateTemperature(self, temperatureData):
self._current_temperature = temperatureData
self._temperatureUpdated(temperatureData)
if self._protocol_listener is not None:
self._protocol_listener.onTemperatureUpdate(self, temperatureData)
def _temperatureUpdated(self, temperatureData):
pass
def _reportProgress(self, completion=None, filepos=None):
if completion is None:
completion = self._getPrintCompletion()
if filepos is None:
filepos = self._getPrintFilepos()
progress = {
"completion": completion,
"filepos": filepos,
"printTime": self.get_print_time()
}
self._progressReported(progress)
if self._protocol_listener is not None:
self._protocol_listener.onProgress(self, progress)
def _progressReported(self, progress):
pass
def _reportZChange(self, z):
old_z = self._current_z
self._current_z = z
self._zChangeReported(z)
if self._protocol_listener is not None:
self._protocol_listener.onZChange(self, old_z, z)
def _zChangeReported(self, newZ):
pass
def _changeSdState(self, sdAvailable):
self._sd_available = sdAvailable
self._sdStateChanged(sdAvailable)
if self._sd_available:
self.refresh_sd_files()
else:
self._sd_files = []
if self._protocol_listener is not None:
self._protocol_listener.onSdStateChange(self, sdAvailable)
def _sdStateChanged(self, sdAvailable):
pass
def _selectFile(self, currentFile):
self._current_file = currentFile
self._fileSelected(currentFile)
if self._protocol_listener is not None:
self._protocol_listener.onFileSelected(self, currentFile.getFilename(), currentFile.getFilesize(), currentFile.getFileLocation())
eventManager().fire(Events.FILE_SELECTED, {
"file": self._current_file.getFilename(),
"origin": self._current_file.getFileLocation()
})
def _fileSelected(self, currentFile):
pass
def _sendSdFiles(self):
self._sdFilesSent()
if self._protocol_listener is not None:
self._protocol_listener.onSdFiles(self, self._sd_files)
def _sdFilesSent(self):
pass
def _finishPrintjob(self):
self._reportProgress(completion=100, filepos=self._current_file.getFilesize())
self._changeState(State.OPERATIONAL)
if self._protocol_listener is not None:
self._protocol_listener.onPrintjobDone(self)
eventManager().fire(Events.PRINT_DONE, {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation(),
"time": time.time() - self._current_file.getStartTime() if self._current_file.getStartTime() is not None else None
})
self._printJobFinished()
def _printJobFinished(self):
pass
def _startFileTransfer(self, filename, filesize):
self._fileTransferStarted(filename, filesize)
if self._protocol_listener is not None:
self._protocol_listener.onFileTransferStarted(self, filename, filesize)
def _fileTransferStarted(self, filename, filesize):
pass
def _finishFileTransfer(self):
self._changeState(State.OPERATIONAL)
current_file = self._current_file
self._current_file = None
self._fileTransferFinished(current_file)
if self._protocol_listener is not None:
self._protocol_listener.onFileTransferDone(self)
def _fileTransferFinished(self, current_file):
pass
def _addSdFile(self, filename, filesize):
"""
Adds a file to the SD file list
:param filename: the filename to add to the list
:param filesize: the filesize to add to the list, may be None
"""
self._sd_files.append((filename, filesize))
self._sdFileAdded(filename, filesize)
def _sdFileAdded(self, filename, filesize):
"""
Called when a file has been added to the SD file list, can be used by the underyling protocol implementation
to react to that.
:param filename: the filename to add to the list
:param filesize: the filesize to add to the list, may be None
"""
pass
def _addSdFiles(self, files):
"""
Adds a list of files to the SD file list
:param files: the list of file tuples (name, size) to add to the list, size may be None
"""
for f in files:
self._sd_files.append(f)
self._sdFilesAdded(files)
def _sdFilesAdded(self, files):
"""
Called when a list of files has been added to the SD file list, can be used by the underlying protocol
implementation to react to that.
:param files: the file tuples (name, size) added to the list, size may be None
"""
pass
def _resetSdFiles(self):
"""
Resets the SD file list
"""
self._sd_files = []
self._sdFilesReset()
def _sdFilesReset(self):
"""
Called when the list of SD files has been reset, can be used in the underlying protocol implementation to
react to that
"""
pass
def _heatupDetected(self):
"""
Called when the underlying protocol detects the beginning of a heat-up interval.
"""
self._heatup_start_time = time.time()
def _heatupDone(self):
"""
Called when the underlying protocol detects the end of a heat-up interval.
"""
if self._heatup_start_time is not None:
self._heatup_time_lost += time.time() - self._heatup_start_time
self._heatup_start_time = None
def _log_error(self, error):
if self._protocol_listener is not None:
self._protocol_listener.onLogError(self, error)
##~~ StateReceiver
def onStateChangeReceived(self, source, oldState, newState):
if self._transport != source:
return
if newState == TransportState.DETECTING_CONNECTION or newState == TransportState.OPENING_CONNECTION:
self._changeState(State.CONNECTING)
elif newState == TransportState.CONNECTED:
self._changeState(State.CONNECTED)
elif newState == TransportState.DISCONNECTED:
self._changeState(State.OFFLINE)
elif newState == TransportState.DISCONNECTED_WITH_ERROR or newState == TransportState.ERROR:
self.onError(self._transport.getError())
try:
self._transport.disconnect()
except:
# TODO do we need to handle that?
pass
##~~ MessageReceiver
def onError(self, error):
self._changeState(State.ERROR)
self._error = error
eventManager().fire(Events.ERROR, {"error": error})
##~~ LogReceiver
def onLogRx(self, source, rx):
if self._transport != source:
return
if self._protocol_listener is not None:
self._protocol_listener.onLogRx(self, rx)
def onLogTx(self, source, tx):
if self._transport != source:
return
if self._protocol_listener is not None:
self._protocol_listener.onLogTx(self, tx)
def onLogError(self, source, error):
if self._transport != source:
return
self._log_error(error)
##~~ helpers
def _getPrintCompletion(self):
if self._current_file is None:
return None
return self._current_file.getProgress() * 100
def _getPrintFilepos(self):
if self._current_file is None:
return None
return self._current_file.getFilepos()
class ProtocolListener(object):
def onStateChange(self, source, oldState, newState):
pass
def onTemperatureUpdate(self, source, temperatureData):
pass
def onProgress(self, source, progress):
pass
def onZChange(self, source, oldZ, newZ):
pass
def onFileSelected(self, source, filename, filesize, origin):
pass
def onPrintjobStarted(self, source):
pass
def onPrintjobDone(self, source):
pass
def onPrintjobCancelled(self, source):
pass
def onFileTransferStarted(self, source, filename, filesize):
pass
def onFileTransferDone(self, source):
pass
def onSdStateChange(self, source, sdAvailable):
pass
def onSdFiles(self, source, files):
pass
def onLogTx(self, source, tx):
pass
def onLogRx(self, source, rx):
pass
def onLogError(self, source, error):
pass
class State(object):
OFFLINE = "Offline"
CONNECTING = "Connecting"
CONNECTED = "Connected"
OPERATIONAL = "Operational"
PRINTING = "Printing"
STREAMING = "Streaming"
PAUSED = "Paused"
ERROR = "Error"
### Printing file information classes ##################################################################################
class PrintingFileInformation(object):
"""
Encapsulates information regarding the current file being printed: file name, current position, total size and
time the print started.
Allows to reset the current file position to 0 and to calculate the current progress as a floating point
value between 0 and 1.
"""
def __init__(self, filename):
self._filename = filename
self._filepos = 0
self._filesize = None
self._startTime = None
def getStartTime(self):
return self._startTime
def getFilename(self):
return self._filename
def getFilesize(self):
return self._filesize
def getFilepos(self):
return self._filepos
def getFileLocation(self):
return FileDestinations.LOCAL
def getProgress(self):
"""
The current progress of the file, calculated as relation between file position and absolute size. Returns -1
if file size is None or < 1.
"""
if self._filesize is None or not self._filesize > 0:
return -1
return float(self._filepos) / float(self._filesize)
def reset(self):
"""
Resets the current file position to 0.
"""
self._filepos = 0
def start(self):
"""
Marks the print job as started and remembers the start time.
"""
self._startTime = time.time()
class PrintingSdFileInformation(PrintingFileInformation):
"""
Encapsulates information regarding an ongoing print from SD.
"""
def __init__(self, filename, filesize):
PrintingFileInformation.__init__(self, filename)
self._filesize = filesize
def setFilepos(self, filepos):
"""
Sets the current file position.
"""
self._filepos = filepos
def getFileLocation(self):
return FileDestinations.SDCARD
+59
View File
@@ -0,0 +1,59 @@
# coding=utf-8
__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 Gina Häußge - Released under terms of the AGPLv3 License"
import re
from octoprint.comm.protocol.reprap import RepRapProtocol
class RepetierTextualProtocol(RepRapProtocol):
__protocolinfo__ = ("repetier", "RepRap (Repetier Flavor)", False)
MESSAGE_TARGET_TEMPERATURE = staticmethod(lambda line: "TargetExtr" in line or "TargetBed" in line)
MESSAGE_TEMPERATURE = staticmethod(lambda line: RepRapProtocol.MESSAGE_TEMPERATURE(line) or RepetierTextualProtocol.MESSAGE_TARGET_TEMPERATURE(line))
REGEX_POSITIVE_FLOAT = "[+]?[0-9]*\.?[0-9]+"
REGEX_TARGET_EXTRUDER_TEMPERATURE = re.compile("TargetExtr([0-9]+):(%s)" % REGEX_POSITIVE_FLOAT)
REGEX_TARGET_BED_TEMPERATURE = re.compile("TargetBed:(%s)" % REGEX_POSITIVE_FLOAT)
def __init__(self, transport_factory, protocol_listener=None):
RepRapProtocol.__init__(self, transport_factory, protocol_listener)
self._sd_available = True
def _reset(self, from_start=False):
RepRapProtocol._reset(self, from_start=from_start)
self._sd_available = True
def _process_temperatures(self, line):
if RepetierTextualProtocol.MESSAGE_TARGET_TEMPERATURE(line):
match_extr = RepetierTextualProtocol.REGEX_TARGET_EXTRUDER_TEMPERATURE.match(line)
match_bed = RepetierTextualProtocol.REGEX_TARGET_BED_TEMPERATURE.match(line)
current_temperatures = self.get_current_temperatures()
key = None
target = None
try:
if match_extr is not None:
tool_num = int(match_extr.group(1))
key = "tool%d" % tool_num
target = float(match_extr.group(2))
elif match_bed is not None:
key = "bed"
target = float(match_bed.group(1))
except ValueError:
pass
if key is None:
return False
if key in current_temperatures and current_temperatures[key] is not None and isinstance(current_temperatures[key], tuple):
(actual, old_target) = current_temperatures[key]
current_temperatures[key] = (actual, target)
else:
current_temperatures[key] = (None, target)
self._updateTemperature(current_temperatures)
else:
RepRapProtocol._process_temperatures(self, line)
File diff suppressed because it is too large. Load diff
+377
View File
@@ -0,0 +1,377 @@
# coding=utf-8
__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 Gina Häußge - Released under terms of the AGPLv3 License"
import Queue
import re
import heapq
import os
import time
import itertools
from octoprint.comm.protocol import PrintingFileInformation
class GcodeCommand(object):
KNOWN_FLOAT_ATTRIBUTES = ("x", "y", "z", "e", "s", "p", "r")
KNOWN_INT_ATTRIBUTES = ("f", "t", "n")
KNOWN_ATTRIBUTES = KNOWN_FLOAT_ATTRIBUTES + KNOWN_INT_ATTRIBUTES
COMMAND_REGEX = re.compile("^([GMT])(\d+)")
ARGUMENT_REGEX = re.compile("\s+([%s][-+]?\d*\.?\d+|[%s][-+]?\d+)" % ("".join(map(lambda x: x.upper(), KNOWN_FLOAT_ATTRIBUTES)), "".join(map(lambda x: x.upper(), KNOWN_INT_ATTRIBUTES))))
PARAM_REGEX = re.compile("^[GMT]\d+\s+(.*?)$")
@staticmethod
def from_line(line):
line = line.strip()
command = ""
args = {"original": line}
match = GcodeCommand.COMMAND_REGEX.match(line)
if match is None:
args["unknown"] = True
else:
commandType = match.group(1)
commandNumber = int(match.group(2))
command = "%s%d" % (commandType, commandNumber)
if commandType == "T":
args["tool"] = commandNumber
else:
matchedArgs = GcodeCommand.ARGUMENT_REGEX.findall(line)
if len(matchedArgs) == 0:
paramMatch = GcodeCommand.PARAM_REGEX.match(line)
if paramMatch is not None:
args["param"] = paramMatch.group(1)
else:
for arg in matchedArgs:
key = arg[0].lower()
if key in GcodeCommand.KNOWN_INT_ATTRIBUTES:
value = int(arg[1:])
elif key in GcodeCommand.KNOWN_FLOAT_ATTRIBUTES:
value = float(arg[1:])
else:
value = str(arg[1:])
args[key] = value
return GcodeCommand(command, **args)
def __init__(self, command, **kwargs):
self.command = command
self.x = None
self.y = None
self.z = None
self.e = None
self.s = None
self.p = None
self.r = None
self.f = None
self.t = None
self.n = None
self.tool = None
self.original = None
self.param = None
self.progress = None
self.callback = None
self.unknown = False
for key, value in kwargs.iteritems():
if key in GcodeCommand.KNOWN_ATTRIBUTES + ("tool", "original", "param", "progress", "callback", "unknown"):
self.__setattr__(key, value)
def isGetTemperatureCommand(self):
return self.command == "M105"
def isSetTemperatureCommand(self):
return self.command in ("M104", "M140", "M109", "M190")
def isSelectToolCommand(self):
return self.command.startswith("T")
def __repr__(self):
return "GcodeCommand(\"{str}\",progress={progress})".format(str=str(self), progress=self.progress)
def __str__(self):
if self.original is not None:
return self.original
else:
attr = []
for key in GcodeCommand.KNOWN_ATTRIBUTES:
value = self.__getattribute__(key)
if value is not None:
if key in GcodeCommand.KNOWN_INT_ATTRIBUTES:
attr.append("%s%d" % (key.upper(), value))
elif key in GcodeCommand.KNOWN_FLOAT_ATTRIBUTES:
attr.append("%s%f" % (key.upper(), value))
else:
attr.append("%s%r" % (key.upper(), value))
attributeStr = " ".join(attr)
return "%s%s%s" % (self.command.upper(), " " + attributeStr if attributeStr else "", " " + self.param if self.param else "")
class CommandQueueEntry(object):
PRIORITY_RESEND = 1
PRIORITY_HIGH = 2
PRIORITY_NORMAL = 3
def __init__(self, priority, command, line_number=None, command_type=None, prepared=None):
self.priority = priority
self.command = command
self.line_number = line_number
self.command_type = command_type
self._prepared = prepared
self._size = 0
@property
def prepared(self):
return self._prepared
@prepared.setter
def prepared(self, prepared):
self._prepared = prepared
self._size = (len(prepared) + 1) if prepared is not None else 0
@property
def size(self):
return self._size
def __radd__(self, other):
return other + self._size
def __repr__(self):
return "CommandQueueEntry({command},prepared={prepared})".format(command=repr(self.command), prepared=self.prepared)
class SpecialCommandQueueEntry(CommandQueueEntry):
TYPE_JOBDONE = "JobDone"
TYPE_JOBCANCELLED = "JobCancelled"
def __init__(self, type):
CommandQueueEntry.__init__(self, CommandQueueEntry.PRIORITY_NORMAL, None)
self.type = type
def __repr__(self):
return "SpecialCommandQueueEntry(type={type})".format(type=self.type)
class CommandQueue(Queue.Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first, followed by addition order).
Entries need to be of the form (priority, command). An optional third argument commandType may be given:
(priority, command, commandType), the queue will ensure that only one command of a given commandType will ever
be in the queue.
'''
def _init(self, maxsize):
self.queue = []
self.lookup = {}
self.counter = itertools.count()
import threading
self.clearlock = threading.RLock()
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
if not isinstance(item, CommandQueueEntry):
raise ValueError("queue can only take CommandQueueEntries, can't accept %r" % item)
command_type = item.command_type
if command_type is not None:
if command_type not in self.lookup:
self.lookup[command_type] = item
else:
raise TypeAlreadyInQueue()
heappush(self.queue, (item.priority, next(self.counter), item))
def _get(self, heappop=heapq.heappop):
priority, counter, item = heappop(self.queue)
if item.command_type in self.lookup:
del self.lookup[item.command_type]
return item
def _entry_at(self, index):
try:
return self.queue[index]
except IndexError:
return None
def _del(self, entry, heapify=True):
item = entry[2]
try:
self.queue.remove(entry)
if heapify:
heapq.heapify(self.queue)
except ValueError:
# that's ok, the entry probably just got removed already e.g. by print cancelling
pass
if item.command_type in self.lookup:
del self.lookup[item.command_type]
def peek(self):
"""
Returns the left most entry, result is either a tuple (priority, counter, CommandQueueEntry) or None (if queue
was empty).
"""
with self.mutex:
entry = self._entry_at(0)
return entry[2] if entry is not None else None, entry
def remove(self, entry):
with self.mutex:
self._del(entry)
def clear(self, matcher=None):
if matcher is None:
matcher = lambda x: True
cleared = []
with self.clearlock:
for entry in self.queue[:]:
priority, counter, item = entry
if matcher(item):
self._del(entry, heapify=False)
cleared.append(entry)
heapq.heapify(self.queue)
return cleared
def __repr__(self):
return repr(self.queue)
class TypeAlreadyInQueue(Exception):
pass
class PrintingGcodeFileInformation(PrintingFileInformation):
"""
Encapsulates information regarding an ongoing direct print. Takes care of the needed file handle and ensures
that the file is closed in case of an error.
"""
def __init__(self, filename, offsetCallback):
PrintingFileInformation.__init__(self, filename)
self._lineCount = None
self._firstLine = None
self._currentTool = 0
self._offsetCallback = offsetCallback
self._fileHandle = None
if not os.path.exists(self._filename) or not os.path.isfile(self._filename):
raise IOError("File %s does not exist" % self._filename)
self._filesize = os.stat(self._filename).st_size
def start(self):
"""
Opens the file for reading and determines the file size. Start time won't be recorded until 100 lines in
"""
self._filehandle = open(self._filename, "r")
self._lineCount = None
self._startTime = None
def getNext(self):
"""
Retrieves the next line for printing.
"""
if self._filehandle is None:
raise ValueError("File %s is not open for reading" % self._filename)
if self._lineCount is None:
self._lineCount = 0
self._startTime = time.time()
return GcodeCommand.from_line("M110 N0")
try:
command = None
while command is None:
if self._filehandle is None:
# file got closed just now
return None
line = self._filehandle.readline()
if not line:
self._filehandle.close()
self._filehandle = None
command = self._process_command(line)
self._lineCount += 1
self._filepos = self._filehandle.tell()
return command
except Exception as (e):
if self._filehandle is not None:
self._filehandle.close()
self._filehandle = None
raise e
def _process_command(self, line):
# remove all comments and trim the line
if ";" in line:
line = line[0:line.find(";")]
line = line.strip()
if len(line) > 0:
# we still got something left => parse the command
command = GcodeCommand.from_line(line)
if command is None:
return None
if command.isSelectToolCommand():
# track tool changes
self._currentTool = command.tool
elif command.isSetTemperatureCommand() and self._offsetCallback is not None:
# if we have a temperature command and an offset callback, retrieve current offsets
offsets = self._offsetCallback()
# extruder temperature, determine which one and retrieve corresponding offset
if command.command == "M104" or command.command == "M109":
tool_num = self._currentTool
if command.t is not None:
tool_num = command.t
key = "tool%d" % tool_num
# bed temperature
elif command.command == "M140" or command.command == "M190":
key = "bed"
# unknown, should never happen
else:
key = None
if key is not None and key in offsets:
offset = offsets[key]
command.s = command.s + offset
if command.original is not None:
command.original = None
# finally return the processed command
return command
else:
# no command, return None
return None
class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
def __init__(self, path, localFilename, remoteFilename):
PrintingGcodeFileInformation.__init__(self, path, None)
self._localFilename = localFilename
self._remoteFilename = remoteFilename
def start(self):
PrintingGcodeFileInformation.start(self)
self._startTime = time.time()
def getLocalFilename(self):
return self._localFilename
def getRemoteFilename(self):
return self._remoteFilename
+121
View File
@@ -0,0 +1,121 @@
# coding=utf-8
__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 Gina Häußge - Released under terms of the AGPLv3 License"
import logging
from octoprint.events import eventManager, Events
class TransportError(Exception):
pass
class SendTimeout(Exception):
pass
class Transport(object):
def __init__(self, messageReceiver=None, stateReceiver=None, logReceiver=None):
self._transport_logger = logging.getLogger("TRANSPORT")
self._messageReceiver = messageReceiver
self._stateReceiver = stateReceiver
self._logReceiver = logReceiver
self._state = State.DISCONNECTED
self._error = None
self._opt = {}
def get_properties(self):
raise NotImplemented()
def get_connection_options(self):
return []
def get_current_connection(self):
return self._opt
def connect(self, opt):
self._opt = opt
def disconnect(self, onError=False):
if onError:
self.changeState(State.DISCONNECTED_WITH_ERROR)
else:
self.changeState(State.DISCONNECTED)
eventManager().fire(Events.DISCONNECTED)
def send(self, command):
pass
def receive(self):
pass
def changeState(self, newState):
oldState = self._state
self._state = newState
if self._stateReceiver is not None:
self._stateReceiver.onStateChangeReceived(self, oldState, newState)
def onError(self, error):
self.changeState(State.ERROR)
self._error = error
def onTimeout(self):
if self._messageReceiver is not None:
self._messageReceiver.onTimeoutReceived(self)
def getError(self):
return self._error
def logTx(self, tx):
if self._logReceiver is not None:
self._logReceiver.onLogTx(self, tx)
def logRx(self, rx):
if self._logReceiver is not None:
self._logReceiver.onLogRx(self, rx)
def logError(self, error):
if self._logReceiver is not None:
self._logReceiver.onLogError(self, error)
def onMessageReceived(self, message):
if self._messageReceiver is not None:
self._messageReceiver.onMessageReceived(self, message)
class TransportProperties(object):
FLOWCONTROL = "flowControl"
class State(object):
OPENING_CONNECTION = "Opening connection"
DETECTING_CONNECTION = "Detecting connection"
CONNECTED = "Connected"
DISCONNECTED = "Disconnected"
DISCONNECTED_WITH_ERROR = "Disconnected with error"
ERROR = "Error"
class MessageReceiver(object):
def onMessageReceived(self, source, message):
pass
def onTimeoutReceived(self, source):
pass
class StateReceiver(object):
def onStateChangeReceived(self, source, oldState, newState):
pass
class LogReceiver(object):
def onLogTx(self, source, tx):
pass
def onLogRx(self, source, rx):
pass
def onLogError(self, source, error):
pass
@@ -0,0 +1,192 @@
# coding=utf-8
__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 Gina Häußge - Released under terms of the AGPLv3 License"
import os
import glob
import threading
import serial
try:
import _winreg
except:
pass
from . import Transport, TransportProperties, State, SendTimeout, TransportError
from octoprint.util import getExceptionString
from octoprint.util.virtual import VirtualPrinter
from octoprint.settings import settings
from octoprint.events import eventManager, Events
class SerialTransport(Transport):
__transportinfo__ = ("serial", "Serial", False)
def __init__(self, messageReceiver, stateReceiver, logReceiver):
Transport.__init__(self, messageReceiver, stateReceiver, logReceiver)
self._serial = None
self._port = None
self._baudrate = None
self._connectionTimeout = None
self._writeTimeout = None
self._readTimeout = None
self._timeoutCounter = 0
self._maxTimeouts = 20
self._thread = None
def get_properties(self):
return {
TransportProperties.FLOWCONTROL: False
}
def get_connection_options(self):
return {
"port": self.__getSerialList(),
"baudrate": self.__getBaudrateList()
}
def connect(self, opt):
Transport.connect(self, opt)
self._port = opt["port"] if "port" in opt else None
self._baudrate = opt["baudrate"] if "baudrate" in opt else None
self._readTimeout = opt["timeout"]["read"] if "timeout" in opt and "read" in opt["timeout"] else 5.0
self._writeTimeout = opt["timeout"]["write"] if "timeout" in opt and "write" in opt["timeout"] else 0.5
if self._connect():
self._thread = threading.Thread(target=self._monitor, name="SerialTransportMonitor")
self._thread.daemon = True
self._thread.start()
def disconnect(self, onError=False):
try:
if self._serial is not None:
self._serial.close()
finally:
self._serial = None
self._thread = None
Transport.disconnect(self, onError)
def send(self, command):
commandToSend = command + "\n"
try:
self._serial.write(commandToSend)
self._transport_logger.info("Send: %s" % command)
self.logTx(command)
except serial.SerialTimeoutException:
self._transport_logger.warn("Timeout while sending: %s" % command)
self.logError("Serial timeout while writing to serial port, try again later.")
raise SendTimeout()
except:
exceptionString = getExceptionString()
self.logError("Unexpected error while writing serial port: %s" % exceptionString)
self.onError(exceptionString)
self.disconnect(True)
raise TransportError()
def receive(self):
return self._readline()
def _monitor(self):
error = None
while True:
line = self._readline()
if line is None:
error = "Serial connection closed unexpectedly"
break
if line == "":
self._timeoutCounter += 1
self.onTimeout()
if self._maxTimeouts and self._timeoutCounter > self._maxTimeouts:
error = "Printer did not respond at all over %d retries, considering it dead" % self._maxTimeouts
break
else:
self._timeoutCounter = 0
self.onMessageReceived(line.strip())
if error is not None:
self._transport_logger.error(error)
self.logError(error)
self.onError(error)
# TODO further error handling
def _connect(self):
self.changeState(State.OPENING_CONNECTION)
if self._port == "VIRTUAL":
self._serial = VirtualPrinter(read_timeout=self._readTimeout, write_timeout=self._writeTimeout)
self.changeState(State.CONNECTED)
self._transport_logger.debug("Connected to %s" % self._serial)
else:
try:
self._serial = serial.Serial(self._port, self._baudrate, timeout=self._readTimeout, writeTimeout=self._writeTimeout)
self.changeState(State.CONNECTED)
self._transport_logger.debug("Connected to %s" % self._serial)
except:
self.logError("Unexpected error while connecting to serial port: %s %s" % (self._port, getExceptionString()))
self.onError("Failed to open serial port, permissions correct?")
return False
eventManager().fire(Events.CONNECTED, {"port": self._port, "baudrate": self._baudrate})
return True
def _readline(self):
if self._serial is None:
return None
try:
line = self._serial.readline()
except:
exceptionString = getExceptionString()
self.logError("Unexpected error while reading serial port: %s" % exceptionString)
self.onError(exceptionString)
self.disconnect()
return None
if line != "":
loggable_line = unicode(line, "ascii", "replace").encode("ascii", "replace").rstrip()
self._transport_logger.debug("Recv: %s" % loggable_line)
self.logRx(loggable_line)
return line
def __getSerialList(self):
baselist=[]
if os.name == "nt":
try:
key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
i=0
while(1):
baselist+=[_winreg.EnumValue(key,i)[1]]
i+=1
except:
pass
baselist = baselist \
+ glob.glob("/dev/ttyUSB*") \
+ glob.glob("/dev/ttyACM*") \
+ glob.glob("/dev/ttyAMA*") \
+ glob.glob("/dev/tty.usb*") \
+ glob.glob("/dev/cu.*") \
+ glob.glob("/dev/rfcomm*")
additionalPorts = settings().get(["serial", "additionalPorts"])
for additional in additionalPorts:
baselist += glob.glob(additional)
prev = settings().get(["serial", "port"])
if prev in baselist:
baselist.remove(prev)
baselist.insert(0, prev)
if settings().getBoolean(["devel", "virtualPrinter", "enabled"]):
baselist.append("VIRTUAL")
return baselist
def __getBaudrateList(self):
ret = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
prev = settings().getInt(["serial", "baudrate"])
if prev in ret:
ret.remove(prev)
ret.insert(0, prev)
return ret
+30 -15
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"
@@ -35,6 +42,7 @@ class Events(object):
UPDATED_FILES = "UpdatedFiles"
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
# SD Upload
TRANSFER_STARTED = "TransferStarted"
@@ -55,6 +63,7 @@ class Events(object):
HOME = "Home"
Z_CHANGE = "ZChange"
WAITING = "Waiting"
DWELL = "Dwelling"
COOLING = "Cooling"
ALERT = "Alert"
CONVEYOR = "Conveyor"
@@ -72,6 +81,10 @@ class Events(object):
SLICING_STARTED = "SlicingStarted"
SLICING_DONE = "SlicingDone"
SLICING_FAILED = "SlicingFailed"
SLICING_CANCELLED = "SlicingCancelled"
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
def eventManager():
@@ -87,7 +100,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 +112,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 +122,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 +137,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 +165,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
+379 -1
View File
@@ -1,3 +1,381 @@
# 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 octoprint.plugin import plugin_manager, ProgressPlugin
from .destinations import FileDestinations
from .analysis import QueueEntry, AnalysisQueue
from .storage import LocalFileStorage
extensions = dict(
# extensions for 3d model files
model=dict(
stl=["stl"]
),
# extensions for printable machine code
machinecode=dict(
gcode=["gcode", "gco", "g"]
)
)
def get_extensions(type, subtree=None):
if not subtree:
subtree = extensions
for key, value in subtree.items():
if key == type:
return get_all_extensions(subtree=value)
elif isinstance(value, dict):
sub_extensions = get_extensions(type, subtree=value)
if sub_extensions:
return sub_extensions
return None
def get_all_extensions(subtree=None):
if not subtree:
subtree = extensions
result = []
if isinstance(subtree, dict):
for key, value in subtree.items():
if isinstance(value, dict):
result += get_all_extensions(value)
elif isinstance(value, (list, tuple)):
result += value
elif isinstance(subtree, (list, tuple)):
result = subtree
return result
def get_path_for_extension(extension, subtree=None):
if not subtree:
subtree = extensions
for key, value in subtree.items():
if isinstance(value, (list, tuple)) and extension in value:
return [key]
elif isinstance(value, dict):
path = get_path_for_extension(extension, subtree=value)
if path:
return [key] + path
return None
all_extensions = get_all_extensions()
def valid_extension(extension, type=None):
if not type:
return extension in all_extensions
else:
extensions = get_extensions(type)
if extensions:
return extension in extensions
def valid_file_type(filename, type=None):
_, extension = os.path.splitext(filename)
extension = extension[1:].lower()
return valid_extension(extension, type=type)
def get_file_type(filename):
_, extension = os.path.splitext(filename)
extension = extension[1:].lower()
return get_path_for_extension(extension)
class NoSuchStorage(Exception):
pass
class FileManager(object):
def __init__(self, analysis_queue, slicing_manager, printer_profile_manager, initial_storage_managers=None):
self._logger = logging.getLogger(__name__)
self._analysis_queue = analysis_queue
self._analysis_queue.register_finish_callback(self._on_analysis_finished)
self._storage_managers = dict()
if initial_storage_managers:
self._storage_managers.update(initial_storage_managers)
self._slicing_manager = slicing_manager
self._printer_profile_manager = printer_profile_manager
import threading
self._slicing_jobs = dict()
self._slicing_jobs_mutex = threading.Lock()
self._slicing_progress_callbacks = []
self._last_slicing_progress = None
self._progress_plugins = plugin_manager().get_implementations(ProgressPlugin)
for storage_type, storage_manager in self._storage_managers.items():
self._determine_analysis_backlog(storage_type, storage_manager)
def register_slicingprogress_callback(self, callback):
self._slicing_progress_callbacks.append(callback)
def unregister_slicingprogress_callback(self, callback):
self._slicing_progress_callbacks.remove(callback)
def _determine_analysis_backlog(self, storage_type, storage_manager):
self._logger.info("Adding backlog items from {storage_type} to analysis queue".format(**locals()))
for entry, path, printer_profile in storage_manager.analysis_backlog:
file_type = get_file_type(path)[-1]
# we'll use the default printer profile for the backlog since we don't know better
queue_entry = QueueEntry(entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
self._analysis_queue.enqueue(queue_entry, high_priority=False)
def add_storage(self, storage_type, storage_manager):
self._storage_managers[storage_type] = storage_manager
self._determine_analysis_backlog(storage_type, storage_manager)
def remove_storage(self, type):
if not type in self._storage_managers:
return
del self._storage_managers[type]
@property
def slicing_enabled(self):
return self._slicing_manager.slicing_enabled
@property
def registered_slicers(self):
return self._slicing_manager.registered_slicers
@property
def default_slicer(self):
return self._slicing_manager.default_slicer
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
absolute_source_path = self.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, _analysis=None):
try:
if _error:
eventManager().fire(Events.SLICING_FAILED, {"stl": source_path, "gcode": dest_path, "reason": _error})
elif _cancelled:
eventManager().fire(Events.SLICING_CANCELLED, {"stl": source_path, "gcode": dest_path})
else:
source_meta = self.get_metadata(source_location, source_path)
hash = source_meta["hash"]
class Wrapper(object):
def __init__(self, stl_name, temp_path, hash):
self.stl_name = stl_name
self.temp_path = temp_path
self.hash = hash
def save(self, absolute_dest_path):
with open(absolute_dest_path, "w") as d:
d.write(";Generated from {stl_name} {hash}\r".format(**vars(self)))
with open(tmp_path, "r") as s:
import shutil
shutil.copyfileobj(s, d)
links = [("model", dict(name=source_path))]
_, stl_name = self.split_path(source_location, source_path)
file_obj = Wrapper(stl_name, temp_path, hash)
printer_profile = self._printer_profile_manager.get(printer_profile_id)
self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis)
end_time = time.time()
eventManager().fire(Events.SLICING_DONE, {"stl": source_path, "gcode": dest_path, "time": end_time - start_time})
if callback is not None:
if callback_args is None:
callback_args = ()
callback(*callback_args)
finally:
os.remove(tmp_path)
source_job_key = (source_location, source_path)
dest_job_key = (dest_location, dest_path)
with self._slicing_jobs_mutex:
if source_job_key in self._slicing_jobs:
del self._slicing_jobs[source_job_key]
if dest_job_key in self._slicing_jobs:
del self._slicing_jobs[dest_job_key]
slicer = self._slicing_manager.get_slicer(slicer_name)
import time
start_time = time.time()
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path, "progressAvailable": slicer.get_slicer_properties()["progress_report"] if slicer else False})
import tempfile
f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False)
temp_path = f.name
f.close()
with self._slicing_jobs_mutex:
source_job_key = (source_location, source_path)
dest_job_key = (dest_location, dest_path)
if dest_job_key in self._slicing_jobs:
job_slicer_name, job_absolute_source_path, job_temp_path = self._slicing_jobs[dest_job_key]
self._slicing_manager.cancel_slicing(job_slicer_name, job_absolute_source_path, job_temp_path)
del self._slicing_jobs[dest_job_key]
self._slicing_jobs[dest_job_key] = self._slicing_jobs[source_job_key] = (slicer_name, absolute_source_path, temp_path)
args = (source_location, source_path, temp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args)
return self._slicing_manager.slice(
slicer_name,
absolute_source_path,
temp_path,
profile,
stlProcessed,
position=position,
callback_args=args,
overrides=overrides,
printer_profile_id=printer_profile_id,
on_progress=self.on_slicing_progress,
on_progress_args=(slicer_name, source_location, source_path, dest_location, dest_path))
def on_slicing_progress(self, slicer, source_location, source_path, dest_location, dest_path, _progress=None):
if not _progress:
return
progress_int = int(_progress * 100)
if self._last_slicing_progress != progress_int:
self._last_slicing_progress = progress_int
for callback in self._slicing_progress_callbacks:
try: callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
except: self._logger.exception("Exception while pushing slicing progress")
if progress_int:
def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress):
for name, plugin in self._progress_plugins.items():
try:
plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress)
except:
self._logger.exception("Exception while sending slicing progress to plugin %s" % name)
import threading
thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int))
thread.daemon = False
thread.start()
def get_busy_files(self):
return self._slicing_jobs.keys()
def file_exists(self, destination, path):
return self._storage(destination).file_exists(path)
def list_files(self, destinations=None, path=None, filter=None, recursive=None):
if not destinations:
destinations = self._storage_managers.keys()
if isinstance(destinations, (str, unicode, basestring)):
destinations = [destinations]
result = dict()
for dst in destinations:
result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive)
return result
def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None):
if printer_profile is None:
printer_profile = self._printer_profile_manager.get_current_or_default()
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
absolute_path = self._storage(destination).get_absolute_path(file_path)
if analysis is None:
file_type = get_file_type(absolute_path)
if file_type:
queue_entry = QueueEntry(file_path, file_type[-1], destination, absolute_path, printer_profile)
self._analysis_queue.enqueue(queue_entry, high_priority=True)
else:
self._add_analysis_result(destination, path, analysis)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
return file_path
def remove_file(self, destination, path):
self._storage(destination).remove_file(path)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def add_folder(self, destination, path, ignore_existing=True):
folder_path = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
return folder_path
def remove_folder(self, destination, path, recursive=True):
self._storage(destination).remove_folder(path, recursive=recursive)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def get_metadata(self, destination, path):
return self._storage(destination).get_metadata(path)
def add_link(self, destination, path, rel, data):
self._storage(destination).add_link(path, rel, data)
def remove_link(self, destination, path, rel, data):
self._storage(destination).remove_link(path, rel, data)
def log_print(self, destination, path, timestamp, print_time, success, printer_profile):
try:
if success:
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
else:
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
eventManager().fire(Events.METADATA_STATISTICS_UPDATED, dict(storage=destination, path=path))
except NoSuchStorage:
# if there's no storage configured where to log the print, we'll just not log it
pass
def set_additional_metadata(self, destination, path, key, data, overwrite=False, merge=False):
self._storage(destination).set_additional_metadata(path, key, data, overwrite=overwrite, merge=merge)
def remove_additional_metadata(self, destination, path, key):
self._storage(destination).remove_additional_metadata(path, key)
def 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 _add_analysis_result(self, destination, path, result):
if not destination in self._storage_managers:
return
storage_manager = self._storage_managers[destination]
storage_manager.set_additional_metadata(path, "analysis", result)
def _on_analysis_finished(self, entry, result):
self._add_analysis_result(entry.location, entry.path, result)
+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()
+885
View File
@@ -0,0 +1,885 @@
# 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 tempfile
import octoprint.filemanager
from octoprint.util import safeRename
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._calculate_stats_from_history(name, path, metadata=metadata, save=False)
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].update(data)
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
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._calculate_stats_from_history(name, path, metadata=metadata, save=False)
self._save_metadata(path, metadata)
except IndexError:
pass
def _calculate_stats_from_history(self, name, path, metadata=None, save=True):
if metadata is None:
metadata = self._get_metadata(path)
if not name in metadata or not "history" in metadata[name]:
return
# collect data from history
former_print_times = dict()
last_print = dict()
for history_entry in metadata[name]["history"]:
if not "printTime" in history_entry or not "success" in history_entry or not history_entry["success"] or not "printerProfile" in history_entry:
continue
printer_profile = history_entry["printerProfile"]
print_time = history_entry["printTime"]
if not printer_profile in former_print_times:
former_print_times[printer_profile] = []
former_print_times[printer_profile].append(print_time)
if not printer_profile in last_print or last_print[printer_profile] is None or ("timestamp" in history_entry and history_entry["timestamp"] > last_print[printer_profile]["timestamp"]):
last_print[printer_profile] = history_entry
# calculate stats
statistics = dict(averagePrintTime=dict(), lastPrintTime=dict())
for printer_profile in former_print_times:
if not former_print_times[printer_profile]:
continue
statistics["averagePrintTime"][printer_profile] = sum(former_print_times[printer_profile]) / float(len(former_print_times[printer_profile]))
for printer_profile in last_print:
if not last_print[printer_profile]:
continue
statistics["lastPrintTime"][printer_profile] = last_print[printer_profile]["printTime"]
metadata[name]["statistics"] = statistics
if save:
self._save_metadata(path, metadata)
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
metadata = yaml.safe_load(f)
except:
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
else:
self._metadata_cache[path] = metadata
return metadata
return dict()
def _save_metadata(self, path, metadata):
metadata_path = os.path.join(path, ".metadata.yaml")
fh, metadata_temporary_path = tempfile.mkstemp()
os.close(fh)
with self._metadata_lock:
try:
with open(metadata_temporary_path, "w") as f:
import yaml
yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
safeRename(metadata_temporary_path, metadata_path, throw_error=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
+152
View File
@@ -0,0 +1,152 @@
# 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,
ProgressPlugin]
if plugin_entry_points is None:
plugin_entry_points = "octoprint.plugin"
if plugin_disabled_list is None:
all_plugin_settings = settings().get(["plugins"])
plugin_disabled_list = []
for key in all_plugin_settings:
if "enabled" in all_plugin_settings[key] and not all_plugin_settings[key]:
plugin_disabled_list.append(key)
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points, 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
+264
View File
@@ -0,0 +1,264 @@
# 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 ProgressPlugin(Plugin):
"""
Via the ``ProgressPlugin`` mixing plugins can let themselves be called upon progress in print jobs or slicing jobs,
limited to minimally 1% steps.
"""
def on_print_progress(self, storage, path, progress):
"""
Called by OctoPrint on minimally 1% increments during a running print job.
:param location string: Location of the file
:param path string: Path of the file
:param progress int: Current progress as a value between 0 and 100
"""
pass
def on_slicing_progress(self, slicer, source_location, source_path, destination_location, destination_path, progress):
"""
Called by OctoPrint on minimally 1% increments during a running slicing job.
:param slicer string: Key of the slicer reporting the progress
:param source_location string: Location of the source file
:param source_path string: Path of the source file
:param destination_location string: Location the destination file
:param destination_path string: Path of the destination file
:param progress int: Current progress as a value between 0 and 100
"""
pass
class AppPlugin(Plugin):
def get_additional_apps(self):
return []
+448
View File
@@ -0,0 +1,448 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import logging.handlers
import os
import flask
import math
import octoprint.plugin
import octoprint.util
import octoprint.slicing
import octoprint.settings
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._cancelled_jobs = []
self._job_mutex = threading.Lock()
##~~ StartupPlugin API
def on_startup(self, host, port):
# setup our custom logger
cura_logging_handler = logging.handlers.RotatingFileHandler(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"])
if cura_engine is not None and os.path.exists(cura_engine):
return True
else:
self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine)
def get_slicer_properties(self):
return dict(
type="cura",
name="CuraEngine",
same_device=True,
progress_report=True
)
def get_slicer_default_profile(self):
path = 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):
try:
with self._job_mutex:
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))
p = sarge.run(command, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
self._slicing_commands[machinecode_path] = p.commands[0]
try:
layer_count = None
step_factor = dict(
inset=0,
skin=1,
export=2
)
analysis = None
while p.returncode is None:
line = p.stderr.readline(timeout=0.5)
if not line:
p.commands[0].poll()
continue
self._cura_logger.debug(line.strip())
if on_progress is not None:
# The Cura slicing process has three individual steps, each consisting of <layer_count> substeps:
#
# - inset
# - skin
# - export
#
# So each layer will be processed three times, once for each step, resulting in a total amount of
# substeps of 3 * <layer_count>.
#
# The CuraEngine reports the calculated layer count and the continuous progress on stderr.
# The layer count gets reported right at the beginning in a line of the format:
#
# Layer count: <layer_count>
#
# The individual progress per each of the three steps gets reported on stderr in a line of
# the format:
#
# Progress:<step>:<current_layer>:<layer_count>
#
# Thus, for determining the overall progress the following formula applies:
#
# progress = <step_factor> * <layer_count> + <current_layer> / <layer_count> * 3
#
# with <step_factor> being 0 for "inset", 1 for "skin" and 2 for "export".
if line.startswith("Layer count:") and layer_count is None:
try:
layer_count = float(line[len("Layer count:"):].strip())
except:
pass
elif line.startswith("Progress:"):
split_line = line[len("Progress:"):].strip().split(":")
if len(split_line) == 3:
step, current_layer, _ = split_line
try:
current_layer = float(current_layer)
except:
pass
else:
if not step in step_factor:
continue
on_progress_kwargs["_progress"] = (step_factor[step] * layer_count + current_layer) / (layer_count * 3)
on_progress(*on_progress_args, **on_progress_kwargs)
elif line.startswith("Print time:"):
try:
print_time = int(line[len("Print time:"):].strip())
if analysis is None:
analysis = dict()
analysis["estimatedPrintTime"] = print_time
except:
pass
elif line.startswith("Filament:") or line.startswith("Filament2:"):
if line.startswith("Filament:"):
filament_str = line[len("Filament:"):].strip()
tool_key = "tool0"
else:
filament_str = line[len("Filament2:"):].strip()
tool_key = "tool1"
try:
filament = int(filament_str)
if analysis is None:
analysis = dict()
if not "filament" in analysis:
analysis["filament"] = dict()
if not tool_key in analysis["filament"]:
analysis["filament"][tool_key] = dict()
analysis["filament"][tool_key]["length"] = filament
if "filamentDiameter" in engine_settings:
radius_in_cm = float(int(engine_settings["filamentDiameter"]) / 10000.0) / 2.0
filament_in_cm = filament / 10.0
analysis["filament"][tool_key]["volume"] = filament_in_cm * math.pi * radius_in_cm * radius_in_cm
except:
pass
finally:
p.close()
with self._job_mutex:
if machinecode_path in self._cancelled_jobs:
self._cura_logger.info("### Cancelled")
raise octoprint.slicing.SlicingCancelled()
self._cura_logger.info("### Finished, returncode %d" % p.returncode)
if p.returncode == 0:
return True, dict(analysis=analysis)
else:
self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode)
return False, "Got returncode %r" % p.returncode
except octoprint.slicing.SlicingCancelled as e:
raise e
except:
self._logger.exception("Could not slice via Cura, got an unknown error")
return False, "Unknown error, please consult the log file"
finally:
with self._job_mutex:
if machinecode_path in self._cancelled_jobs:
self._cancelled_jobs.remove(machinecode_path)
if machinecode_path in self._slicing_commands:
del self._slicing_commands[machinecode_path]
self._cura_logger.info("-" * 40)
def cancel_slicing(self, machinecode_path):
with self._job_mutex:
if machinecode_path in self._slicing_commands:
self._cancelled_jobs.append(machinecode_path)
command = self._slicing_commands[machinecode_path]
if command is not None:
command.terminate()
self._logger.info("Cancelled slicing of %s" % machinecode_path)
def _load_profile(self, path):
import yaml
profile_dict = dict()
with open(path, "r") as f:
try:
profile_dict = yaml.safe_load(f)
except:
raise IOError("Couldn't read profile from {path}".format(path=path))
return profile_dict
def _save_profile(self, path, profile, allow_overwrite=True):
if not allow_overwrite and os.path.exists(path):
raise IOError("Cannot overwrite {path}".format(path=path))
import yaml
with open(path, "wb") as f:
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
return profile.convert_to_engine()
def _sanitize_name(name):
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
sanitized_name = ''.join(c for c in name if c in valid_chars)
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name.lower()
__plugin_name__ = "CuraEngine"
__plugin_version__ = "0.1"
__plugin_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>
-761
View File
@@ -1,761 +0,0 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
import time
import datetime
import threading
import copy
import os
import logging
import octoprint.util.comm as comm
import octoprint.util as util
from octoprint.settings import settings
from octoprint.events import eventManager, Events
from octoprint.filemanager.destinations import FileDestinations
def getConnectionOptions():
"""
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
"""
return {
"ports": comm.serialList(),
"baudrates": comm.baudrateList(),
"portPreference": settings().get(["serial", "port"]),
"baudratePreference": settings().getInt(["serial", "baudrate"]),
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
}
class Printer():
def __init__(self, gcodeManager):
from collections import deque
self._gcodeManager = gcodeManager
self._gcodeManager.registerCallback(self)
# state
# TODO do we really need to hold the temperature here?
self._temp = None
self._bedTemp = None
self._targetTemp = None
self._targetBedTemp = None
self._temps = deque([], 300)
self._tempBacklog = []
self._latestMessage = None
self._messages = deque([], 300)
self._messageBacklog = []
self._latestLog = None
self._log = deque([], 300)
self._logBacklog = []
self._state = None
self._currentZ = None
self._progress = None
self._printTime = None
self._printTimeLeft = None
self._printAfterSelect = False
# sd handling
self._sdPrinting = False
self._sdStreaming = False
self._sdFilelistAvailable = threading.Event()
self._streamingFinishedCallback = None
self._selectedFile = None
# comm
self._comm = None
# callbacks
self._callbacks = []
self._lastProgressReport = None
self._stateMonitor = StateMonitor(
ratelimit=0.5,
updateCallback=self._sendCurrentDataCallbacks,
addTemperatureCallback=self._sendAddTemperatureCallbacks,
addLogCallback=self._sendAddLogCallbacks,
addMessageCallback=self._sendAddMessageCallbacks
)
self._stateMonitor.reset(
state={"text": self.getStateString(), "flags": self._getStateFlags()},
jobData={
"file": {
"name": None,
"size": None,
"origin": None,
"date": None
},
"estimatedPrintTime": None,
"lastPrintTime": None,
"filament": {
"length": None,
"volume": None
}
},
progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
currentZ=None
)
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished);
#~~ callback handling
def registerCallback(self, callback):
self._callbacks.append(callback)
self._sendInitialStateUpdate(callback)
def unregisterCallback(self, callback):
if callback in self._callbacks:
self._callbacks.remove(callback)
def _sendAddTemperatureCallbacks(self, data):
for callback in self._callbacks:
try: callback.addTemperature(data)
except: pass
def _sendAddLogCallbacks(self, data):
for callback in self._callbacks:
try: callback.addLog(data)
except: pass
def _sendAddMessageCallbacks(self, data):
for callback in self._callbacks:
try: callback.addMessage(data)
except: pass
def _sendCurrentDataCallbacks(self, data):
for callback in self._callbacks:
try: callback.sendCurrentData(copy.deepcopy(data))
except: pass
def _sendTriggerUpdateCallbacks(self, type):
for callback in self._callbacks:
try: callback.sendEvent(type)
except: pass
def _sendFeedbackCommandOutput(self, name, output):
for callback in self._callbacks:
try: callback.sendFeedbackCommandOutput(name, output)
except: pass
#~~ callback from gcodemanager
def sendUpdateTrigger(self, type):
if type == "gcodeFiles" and self._selectedFile:
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
#~~ callback from metadata analysis event
def onMetadataAnalysisFinished(self, event, data):
if self._selectedFile:
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
#~~ printer commands
def connect(self, port=None, baudrate=None):
"""
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
will be attempted.
"""
if self._comm is not None:
self._comm.close()
self._comm = comm.MachineCom(port, baudrate, callbackObject=self)
def disconnect(self):
"""
Closes the connection to the printer.
"""
if self._comm is not None:
self._comm.close()
self._comm = None
eventManager().fire(Events.DISCONNECTED)
def command(self, command):
"""
Sends a single gcode command to the printer.
"""
self.commands([command])
def commands(self, commands):
"""
Sends multiple gcode commands (provided as a list) to the printer.
"""
if self._comm is None:
return
for command in commands:
self._comm.sendCommand(command)
def jog(self, axis, amount):
movementSpeed = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z"]], asdict=True)
self.commands(["G91", "G1 %s%.4f F%d" % (axis.upper(), amount, movementSpeed[axis]), "G90"])
def home(self, axes):
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), axes)), "G90"])
def extrude(self, amount):
extrusionSpeed = settings().get(["printerParameters", "movementSpeed", "e"])
self.commands(["G91", "G1 E%s F%d" % (amount, extrusionSpeed), "G90"])
def changeTool(self, tool):
try:
toolNum = int(tool[len("tool"):])
self.command("T%d" % toolNum)
except ValueError:
pass
def setTemperature(self, type, value):
if type.startswith("tool"):
if settings().getInt(["printerParameters", "numExtruders"]) > 1:
try:
toolNum = int(type[len("tool"):])
self.command("M104 T%d S%f" % (toolNum, value))
except ValueError:
pass
else:
self.command("M104 S%f" % value)
elif type == "bed":
self.command("M140 S%f" % value)
def setTemperatureOffset(self, offsets={}):
if self._comm is None:
return
tool, bed = self._comm.getOffsets()
validatedOffsets = {}
for key in offsets:
value = offsets[key]
if key == "bed":
bed = value
validatedOffsets[key] = value
elif key.startswith("tool"):
try:
toolNum = int(key[len("tool"):])
tool[toolNum] = value
validatedOffsets[key] = value
except ValueError:
pass
self._comm.setTemperatureOffset(tool, bed)
self._stateMonitor.setTempOffsets(validatedOffsets)
def selectFile(self, filename, sd, printAfterSelect=False):
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
logging.info("Cannot load file: printer not connected or currently busy")
return
self._printAfterSelect = printAfterSelect
self._comm.selectFile(filename, sd)
self._setProgressData(0, None, None, None)
self._setCurrentZ(None)
def unselectFile(self):
if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()):
return
self._comm.unselectFile()
self._setProgressData(0, None, None, None)
self._setCurrentZ(None)
def startPrint(self):
"""
Starts the currently loaded print job.
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
"""
if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting():
return
if self._selectedFile is None:
return
self._setCurrentZ(None)
self._comm.startPrint()
def togglePausePrint(self):
"""
Pause the current printjob.
"""
if self._comm is None:
return
self._comm.setPause(not self._comm.isPaused())
def cancelPrint(self, disableMotorsAndHeater=True):
"""
Cancel the current printjob.
"""
if self._comm is None:
return
self._comm.cancelPrint()
if disableMotorsAndHeater:
# disable motors, switch off hotends, bed and fan
commands = ["M84"]
commands.extend(map(lambda x: "M104 T%d S0" % x, range(settings().getInt(["printerParameters", "numExtruders"]))))
commands.extend(["M140 S0", "M106 S0"])
self.commands(commands)
# reset progress, height, print time
self._setCurrentZ(None)
self._setProgressData(None, None, None, None)
# mark print as failure
if self._selectedFile is not None:
self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime())
payload = {
"file": self._selectedFile["filename"],
"origin": FileDestinations.LOCAL
}
if self._selectedFile["sd"]:
payload["origin"] = FileDestinations.SDCARD
eventManager().fire(Events.PRINT_FAILED, payload)
#~~ state monitoring
def _setCurrentZ(self, currentZ):
self._currentZ = currentZ
self._stateMonitor.setCurrentZ(self._currentZ)
def _setState(self, state):
self._state = state
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def _addLog(self, log):
self._log.append(log)
self._stateMonitor.addLog(log)
def _addMessage(self, message):
self._messages.append(message)
self._stateMonitor.addMessage(message)
def _setProgressData(self, progress, filepos, printTime, printTimeLeft):
self._progress = progress
self._printTime = printTime
self._printTimeLeft = printTimeLeft
self._stateMonitor.setProgress({
"completion": self._progress * 100 if self._progress is not None else None,
"filepos": filepos,
"printTime": int(self._printTime) if self._printTime is not None else None,
"printTimeLeft": int(self._printTimeLeft * 60) if self._printTimeLeft is not None else None
})
def _addTemperatureData(self, temp, bedTemp):
currentTimeUtc = int(time.time())
data = {
"time": currentTimeUtc
}
for tool in temp.keys():
data["tool%d" % tool] = {
"actual": temp[tool][0],
"target": temp[tool][1]
}
if bedTemp is not None and isinstance(bedTemp, tuple):
data["bed"] = {
"actual": bedTemp[0],
"target": bedTemp[1]
}
self._temps.append(data)
self._temp = temp
self._bedTemp = bedTemp
self._stateMonitor.addTemperature(data)
def _setJobData(self, filename, filesize, sd):
if filename is not None:
self._selectedFile = {
"filename": filename,
"filesize": filesize,
"sd": sd
}
else:
self._selectedFile = None
estimatedPrintTime = None
lastPrintTime = None
date = None
filament = None
if filename:
# Use a string for mtime because it could be float and the
# javascript needs to exact match
if not sd:
date = int(os.stat(filename).st_ctime)
fileData = self._gcodeManager.getFileData(filename)
if fileData is not None:
if "gcodeAnalysis" in fileData:
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["gcodeAnalysis"]:
estimatedPrintTime = fileData["gcodeAnalysis"]["estimatedPrintTime"]
if "filament" in fileData["gcodeAnalysis"].keys():
filament = fileData["gcodeAnalysis"]["filament"]
if "prints" in fileData and fileData["prints"] and "last" in fileData["prints"] and fileData["prints"]["last"] and "lastPrintTime" in fileData["prints"]["last"]:
lastPrintTime = fileData["prints"]["last"]["lastPrintTime"]
self._stateMonitor.setJobData({
"file": {
"name": os.path.basename(filename) if filename is not None else None,
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
"size": filesize,
"date": date
},
"estimatedPrintTime": estimatedPrintTime,
"lastPrintTime": lastPrintTime,
"filament": filament,
})
def _sendInitialStateUpdate(self, callback):
try:
data = self._stateMonitor.getCurrentData()
data.update({
"temps": list(self._temps),
"logs": list(self._log),
"messages": list(self._messages)
})
callback.sendHistoryData(data)
except Exception, err:
import sys
sys.stderr.write("ERROR: %s\n" % str(err))
pass
def _getStateFlags(self):
return {
"operational": self.isOperational(),
"printing": self.isPrinting(),
"closedOrError": self.isClosedOrError(),
"error": self.isError(),
"paused": self.isPaused(),
"ready": self.isReady(),
"sdReady": self.isSdReady()
}
#~~ callbacks triggered from self._comm
def mcLog(self, message):
"""
Callback method for the comm object, called upon log output.
"""
self._addLog(message)
def mcTempUpdate(self, temp, bedTemp):
self._addTemperatureData(temp, bedTemp)
def mcStateChange(self, state):
"""
Callback method for the comm object, called if the connection state changes.
"""
oldState = self._state
# forward relevant state changes to gcode manager
if self._comm is not None and oldState == self._comm.STATE_PRINTING:
if self._selectedFile is not None:
if state == self._comm.STATE_OPERATIONAL:
self._gcodeManager.printSucceeded(self._selectedFile["filename"], self._comm.getPrintTime())
elif state == self._comm.STATE_CLOSED or state == self._comm.STATE_ERROR or state == self._comm.STATE_CLOSED_WITH_ERROR:
self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime())
self._gcodeManager.resumeAnalysis() # printing done, put those cpu cycles to good use
elif self._comm is not None and state == self._comm.STATE_PRINTING:
self._gcodeManager.pauseAnalysis() # do not analyse gcode while printing
self._setState(state)
def mcMessage(self, message):
"""
Callback method for the comm object, called upon message exchanges via serial.
Stores the message in the message buffer, truncates buffer to the last 300 lines.
"""
self._addMessage(message)
def mcProgress(self):
"""
Callback method for the comm object, called upon any change in progress of the printjob.
Triggers storage of new values for printTime, printTimeLeft and the current progress.
"""
self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getPrintTimeRemainingEstimate())
def mcZChange(self, newZ):
"""
Callback method for the comm object, called upon change of the z-layer.
"""
oldZ = self._currentZ
if newZ != oldZ:
# we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or
# anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes
eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ})
self._setCurrentZ(newZ)
def mcSdStateChange(self, sdReady):
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def mcSdFiles(self, files):
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
self._sdFilelistAvailable.set()
def mcFileSelected(self, filename, filesize, sd):
self._setJobData(filename, filesize, sd)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
if self._printAfterSelect:
self.startPrint()
def mcPrintjobDone(self):
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def mcFileTransferStarted(self, filename, filesize):
self._sdStreaming = True
self._setJobData(filename, filesize, True)
self._setProgressData(0.0, 0, 0, None)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def mcFileTransferDone(self, filename):
self._sdStreaming = False
if self._streamingFinishedCallback is not None:
# in case of SD files, both filename and absolutePath are the same, so we set the (remote) filename for
# both parameters
self._streamingFinishedCallback(filename, filename, FileDestinations.SDCARD)
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._setProgressData(None, None, None, None)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def mcReceivedRegisteredMessage(self, command, output):
self._sendFeedbackCommandOutput(command, output)
#~~ sd file handling
def getSdFiles(self):
if self._comm is None or not self._comm.isSdReady():
return []
return self._comm.getSdFiles()
def addSdFile(self, filename, absolutePath, streamingFinishedCallback):
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
logging.error("No connection to printer or printer is busy")
return
self._streamingFinishedCallback = streamingFinishedCallback
self.refreshSdFiles(blocking=True)
existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles())
remoteName = util.getDosFilename(filename, existingSdFiles)
self._comm.startFileTransfer(absolutePath, filename, remoteName)
return remoteName
def deleteSdFile(self, filename):
if not self._comm or not self._comm.isSdReady():
return
self._comm.deleteSdFile(filename)
def initSdCard(self):
if not self._comm or self._comm.isSdReady():
return
self._comm.initSdCard()
def releaseSdCard(self):
if not self._comm or not self._comm.isSdReady():
return
self._comm.releaseSdCard()
def refreshSdFiles(self, blocking=False):
"""
Refreshs the list of file stored on the SD card attached to printer (if available and printer communication
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
received (and can be accessed via self._comm.getSdFiles()). Defaults to a asynchronous operation.
"""
if not self._comm or not self._comm.isSdReady():
return
self._sdFilelistAvailable.clear()
self._comm.refreshSdFiles()
if blocking:
self._sdFilelistAvailable.wait(10000)
#~~ state reports
def getStateString(self):
"""
Returns a human readable string corresponding to the current communication state.
"""
if self._comm is None:
return "Offline"
else:
return self._comm.getStateString()
def getCurrentData(self):
return self._stateMonitor.getCurrentData()
def getCurrentJob(self):
currentData = self._stateMonitor.getCurrentData()
return currentData["job"]
def getCurrentTemperatures(self):
if self._comm is not None:
tempOffset, bedTempOffset = self._comm.getOffsets()
else:
tempOffset = {}
bedTempOffset = None
result = {}
if self._temp is not None:
for tool in self._temp.keys():
result["tool%d" % tool] = {
"actual": self._temp[tool][0],
"target": self._temp[tool][1],
"offset": tempOffset[tool] if tool in tempOffset.keys() and tempOffset[tool] is not None else 0
}
if self._bedTemp is not None:
result["bed"] = {
"actual": self._bedTemp[0],
"target": self._bedTemp[1],
"offset": bedTempOffset
}
return result
def getTemperatureHistory(self):
return self._temps
def getCurrentConnection(self):
if self._comm is None:
return "Closed", None, None
port, baudrate = self._comm.getConnection()
return self._comm.getStateString(), port, baudrate
def isClosedOrError(self):
return self._comm is None or self._comm.isClosedOrError()
def isOperational(self):
return self._comm is not None and self._comm.isOperational()
def isPrinting(self):
return self._comm is not None and self._comm.isPrinting()
def isPaused(self):
return self._comm is not None and self._comm.isPaused()
def isError(self):
return self._comm is not None and self._comm.isError()
def isReady(self):
return self.isOperational() and not self._comm.isStreaming()
def isSdReady(self):
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
return False
else:
return self._comm.isSdReady()
class StateMonitor(object):
def __init__(self, ratelimit, updateCallback, addTemperatureCallback, addLogCallback, addMessageCallback):
self._ratelimit = ratelimit
self._updateCallback = updateCallback
self._addTemperatureCallback = addTemperatureCallback
self._addLogCallback = addLogCallback
self._addMessageCallback = addMessageCallback
self._state = None
self._jobData = None
self._gcodeData = None
self._sdUploadData = None
self._currentZ = None
self._progress = None
self._offsets = {}
self._changeEvent = threading.Event()
self._stateMutex = threading.Lock()
self._lastUpdate = time.time()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def reset(self, state=None, jobData=None, progress=None, currentZ=None):
self.setState(state)
self.setJobData(jobData)
self.setProgress(progress)
self.setCurrentZ(currentZ)
def addTemperature(self, temperature):
self._addTemperatureCallback(temperature)
self._changeEvent.set()
def addLog(self, log):
self._addLogCallback(log)
self._changeEvent.set()
def addMessage(self, message):
self._addMessageCallback(message)
self._changeEvent.set()
def setCurrentZ(self, currentZ):
self._currentZ = currentZ
self._changeEvent.set()
def setState(self, state):
with self._stateMutex:
self._state = state
self._changeEvent.set()
def setJobData(self, jobData):
self._jobData = jobData
self._changeEvent.set()
def setProgress(self, progress):
self._progress = progress
self._changeEvent.set()
def setTempOffsets(self, offsets):
self._offsets = offsets
self._changeEvent.set()
def _work(self):
while True:
self._changeEvent.wait()
with self._stateMutex:
now = time.time()
delta = now - self._lastUpdate
additionalWaitTime = self._ratelimit - delta
if additionalWaitTime > 0:
time.sleep(additionalWaitTime)
data = self.getCurrentData()
self._updateCallback(data)
self._lastUpdate = time.time()
self._changeEvent.clear()
def getCurrentData(self):
return {
"state": self._state,
"job": self._jobData,
"currentZ": self._currentZ,
"progress": self._progress,
"offsets": self._offsets
}
+963
View File
@@ -0,0 +1,963 @@
# coding=utf-8
from octoprint.comm.protocol.repetier import RepetierTextualProtocol
from octoprint.comm.transport import Transport
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
import time
import threading
import copy
import os
import re
import logging
import octoprint.util.comm as comm
import octoprint.util as util
from octoprint.settings import settings
from octoprint.events import eventManager, Events
from octoprint.filemanager.destinations import FileDestinations
from octoprint.comm.protocol import State as ProtocolState, Protocol
from octoprint.comm.protocol.reprap import RepRapProtocol
from octoprint.comm.transport.serialTransport import SerialTransport
from octoprint.plugin import plugin_manager, ProgressPlugin
def getConnectionOptions():
"""
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
"""
return {
"ports": comm.serialList(),
"baudrates": comm.baudrateList(),
"portPreference": settings().get(["serial", "port"]),
"baudratePreference": settings().getInt(["serial", "baudrate"]),
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
}
class Printer():
def __init__(self, fileManager, analysisQueue, printerProfileManager):
from collections import deque
self._logger = logging.getLogger(__name__)
#self._estimationLogger = logging.getLogger("ESTIMATIONS")
#self._printTimeLogger = logging.getLogger("PRINT_TIME")
self._analysisQueue = analysisQueue
self._fileManager = fileManager
self._printerProfileManager = printerProfileManager
# state
self._temps = deque([], 300)
self._tempBacklog = []
self._latestMessage = None
self._messages = deque([], 300)
self._messageBacklog = []
self._latestLog = None
self._log = deque([], 300)
self._logBacklog = []
self._state = None
self._currentZ = None
self._progress = None
self._printTime = None
self._printTimeLeft = None
self._printAfterSelect = False
# sd handling
self._sdPrinting = False
self._sdStreaming = False
self._sdFilelistAvailable = threading.Event()
self._streamingFinishedCallback = None
self._selectedFile = None
self._timeEstimationData = None
# comm
self._comm = None
self._protocol = self._createProtocol()
# callbacks
self._callbacks = []
# progress plugins
self._lastProgressReport = None
self._progressPlugins = plugin_manager().get_implementations(ProgressPlugin)
self._stateMonitor = StateMonitor(
ratelimit=0.5,
updateCallback=self._sendCurrentDataCallbacks,
addTemperatureCallback=self._sendAddTemperatureCallbacks,
addLogCallback=self._sendAddLogCallbacks,
addMessageCallback=self._sendAddMessageCallbacks
)
self._stateMonitor.reset(
state={"text": self.getStateString(), "flags": self._getStateFlags()},
jobData={
"file": {
"name": None,
"size": None,
"origin": None,
"date": None
},
"estimatedPrintTime": None,
"lastPrintTime": None,
"filament": {
"length": None,
"volume": None
}
},
progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
currentZ=None
)
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished)
eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self.onMetadataStatisticsUpdated)
def _getTransportFactory(self):
transports = self._getSubclassAttributes(Transport, "__transportinfo__", validator=lambda x: not x[2])
transportType = settings().get(["communication", "transport"])
for t in transports:
id, name, abstract, factory = t
if transportType == id:
return factory
return SerialTransport
def _createProtocol(self):
transport = self._getTransportFactory()
protocol_type = settings().get(["communication", "protocol"])
protocols = self._getSubclassAttributes(Protocol, "__protocolinfo__", validator=lambda x: not x[2])
protocol_factory = RepRapProtocol
for p in protocols:
id, name, abstract, factory = p
if protocol_type == id:
protocol_factory = factory
break
return protocol_factory(transport, protocol_listener=self)
def _getSubclassAttributes(self, origin, attribute, converter=lambda o, v: v, validator=lambda x: True):
result = []
if hasattr(origin, attribute):
value = getattr(origin, attribute)
if validator(value):
converted = list(converter(origin, value))
converted.append(origin)
result.append(converted)
subclasses = origin.__subclasses__()
if subclasses:
for s in subclasses:
result.extend(self._getSubclassAttributes(s, attribute, converter, validator))
return result
#~~ callback handling
def registerCallback(self, callback):
self._callbacks.append(callback)
self._sendInitialStateUpdate(callback)
def unregisterCallback(self, callback):
if callback in self._callbacks:
self._callbacks.remove(callback)
def _sendAddTemperatureCallbacks(self, data):
for callback in self._callbacks:
try: callback.addTemperature(data)
except: self._logger.exception("Exception while adding temperature data point")
def _sendAddLogCallbacks(self, data):
for callback in self._callbacks:
try: callback.addLog(data)
except: self._logger.exception("Exception while adding communication log entry")
def _sendAddMessageCallbacks(self, data):
for callback in self._callbacks:
try: callback.addMessage(data)
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: self._logger.exception("Exception while pushing current data")
def _sendTriggerUpdateCallbacks(self, type):
for callback in self._callbacks:
try: callback.sendEvent(type)
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: self._logger.exception("Exception while pushing feedback command output")
#~~ callbacks from protocol
def onStateChange(self, source, oldState, newState):
if not source == self._protocol:
return
# forward relevant state changes to gcode manager
if oldState == ProtocolState.PRINTING:
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
if self._selectedFile is not None and newState == ProtocolState.OFFLINE or newState == ProtocolState.ERROR:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), False)
elif newState == ProtocolState.PRINTING:
self._analysisQueue.pause() # do not analyse files while printing
self._setState(newState)
def onTemperatureUpdate(self, source, temperatureData):
if not source == self._protocol:
return
self._addTemperatureData(temperatureData)
def onProgress(self, source, progress):
if not source == self._protocol:
return
self._setProgressData(progress["completion"], progress["filepos"], progress["printTime"])
def onZChange(self, source, oldZ, newZ):
if not source == self._protocol:
return
if newZ != oldZ:
# we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or
# anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes
eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ})
self._setCurrentZ(newZ)
def onFileSelected(self, source, filename, filesize, origin):
if not source == self._protocol:
return
self._setJobData(filename, filesize, origin)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
if self._printAfterSelect:
self.startPrint()
pass
def onPrintjobDone(self, source):
if not source == self._protocol:
return
self._setProgressData(100.0, self._selectedFile["filesize"], self._protocol.get_print_time())
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
if self._selectedFile is not None:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), True, self._printerProfileManager.get_current_or_default()["id"])
def onPrintjobCancelled(self, source):
if not source == self._protocol:
return
if self._selectedFile is not None:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), False, self._printerProfileManager.get_current_or_default()["id"])
def onFileTransferStarted(self, source, filename, filesize):
if not source == self._protocol:
return
self._sdStreaming = True
self._setJobData(filename, filesize, FileDestinations.SDCARD)
self._setProgressData(0.0, 0, 0)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def onFileTransferDone(self, source):
if not source == self._protocol:
return
self._sdStreaming = False
if self._streamingFinishedCallback is not None:
self._streamingFinishedCallback(self._sdRemoteName, FileDestinations.SDCARD)
self._sdRemoteName = None
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._setProgressData(None, None, None)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def onSdStateChange(self, source, sdAvailable):
if not source == self._protocol:
return
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def onSdFiles(self, source, files):
if not source == self._protocol:
return
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
self._sdFilelistAvailable.set()
def onLogTx(self, source, tx):
if not source == self._protocol:
return
self._addLog("Send: %s" % tx)
def onLogRx(self, source, rx):
if not source == self._protocol:
return
self._addLog("Recv: %s" % rx)
def onLogError(self, source, error):
if not source == self._protocol:
return
self._addLog("ERROR: %s" % error)
#~~ callback from metadata analysis event
def onMetadataAnalysisFinished(self, event, data):
if self._selectedFile:
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
def onMetadataStatisticsUpdated(self, event, data):
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
#~~ progress plugin reporting
def _reportPrintProgressToPlugins(self, progress):
if not progress or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile:
return
storage = "sdcard" if self._selectedFile["sd"] else "local"
filename = self._selectedFile["filename"]
def call_plugins(storage, filename, progress):
for name, plugin in self._progressPlugins.items():
try:
plugin.on_print_progress(storage, filename, progress)
except:
self._logger.exception("Exception while sending print progress to plugin %s" % name)
thread = threading.Thread(target=call_plugins, args=(storage, filename, progress))
thread.daemon = False
thread.start()
#~~ printer commands
def connect(self, protocol_option_overrides=None, transport_option_overrides=None, profile=None):
"""
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
will be attempted.
"""
self._protocol.disconnect()
protocol_options = settings().get(["communication", "protocolOptions"], merged=True)
if protocol_option_overrides is not None and isinstance(protocol_option_overrides, dict):
protocol_options = util.dict_merge(protocol_options, protocol_option_overrides)
transport_options = settings().get(["communication", "transportOptions"], merged=True)
if transport_option_overrides is not None and isinstance(transport_option_overrides, dict):
transport_options = util.dict_merge(transport_options, transport_option_overrides)
self._protocol.connect(protocol_options, transport_options)
self._printerProfileManager.select(profile)
def disconnect(self):
"""
Closes the connection to the printer.
"""
self._protocol.disconnect()
self._printerProfileManager.deselect()
eventManager().fire(Events.DISCONNECTED)
def getConnectionOptions(self):
connection_options = self._protocol.get_connection_options()
return {
"ports": connection_options["port"],
"baudrates": connection_options["baudrate"],
"portPreference": settings().get(["serial", "port"]),
"baudratePreference": settings().getInt(["serial", "baudrate"]),
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
}
def command(self, command):
self._protocol.send_manually(command)
def commands(self, commands):
self.command(commands)
def jog(self, axis, amount):
if not axis or not amount:
return
printer_profile = self._printerProfileManager.get_current_or_default()
axis = axis.lower()
if axis in printer_profile["axes"]:
speed = printer_profile["axes"][axis]["speed"]
self._protocol.jog(axis, amount, speed)
def home(self, axes):
self._protocol.home(axes)
def extrude(self, amount):
if not amount:
return
printer_profile = self._printerProfileManager.get_current_or_default()
if "e" in printer_profile["axes"]:
speed = printer_profile["axes"]["e"]["speed"]
self._protocol.extrude(amount, speed)
def changeTool(self, tool):
self._protocol.change_tool(tool)
def setTemperature(self, type, value):
self._protocol.set_temperature(type, value)
def setTemperatureOffset(self, offsets):
current_offsets = self._protocol.get_temperature_offsets()
new_offsets = {}
new_offsets.update(current_offsets)
for key in offsets:
if key == "bed" or re.match("tool\d+", key):
new_offsets[key] = offsets[key]
self._protocol.set_temperature_offsets(new_offsets)
self._stateMonitor.setTempOffsets(new_offsets)
def selectFile(self, filename, origin, printAfterSelect=False):
self._printAfterSelect = printAfterSelect
self._protocol.select_file(filename, origin)
self._setProgressData(0, None, None)
self._setCurrentZ(None)
def unselectFile(self):
self._protocol.deselect_file()
self._setProgressData(0, None, None)
self._setCurrentZ(None)
def startPrint(self):
"""
Starts the currently loaded print job.
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
"""
if not self._protocol.is_operational() or self._protocol.is_busy():
return
if self._selectedFile is None:
return
self._timeEstimationData = TimeEstimationHelper()
self._lastProgressReport = None
self._setCurrentZ(None)
self._protocol.start_print()
def togglePausePrint(self):
"""
Pause the current printjob.
"""
self._protocol.pause_print()
def cancelPrint(self, disableMotorsAndHeater=True):
"""
Cancel the current printjob.
"""
self._protocol.cancel_print()
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(extruder_count)))
commands.extend(["M140 S0", "M106 S0"])
self.commands(commands)
# reset progress, height, print time
self._setCurrentZ(None)
self._setProgressData(None, None, None)
# mark print as failure
if self._selectedFile is not None:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), False, self._printerProfileManager.get_current_or_default()["id"])
payload = {
"file": self._selectedFile["filename"],
"origin": FileDestinations.LOCAL
}
if self._selectedFile["sd"]:
payload["origin"] = FileDestinations.SDCARD
eventManager().fire(Events.PRINT_FAILED, payload)
#~~ state monitoring
def _setCurrentZ(self, currentZ):
self._currentZ = currentZ
self._stateMonitor.setCurrentZ(self._currentZ)
def _setState(self, state):
self._state = state
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def _addLog(self, log):
self._log.append(log)
self._stateMonitor.addLog(log)
def _addMessage(self, message):
self._messages.append(message)
self._stateMonitor.addMessage(message)
def _estimateTotalPrintTime(self, progress, printTime):
if not progress or not printTime:
#self._estimationLogger.info("{progress};{printTime};;;;".format(**locals()))
return None
else:
newEstimate = printTime * 100 / progress
self._timeEstimationData.update(newEstimate)
result = None
if self._timeEstimationData.is_stable():
result = self._timeEstimationData.average_total_rolling
#averageTotal = self._timeEstimationData.average_total
#averageTotalRolling = self._timeEstimationData.average_total_rolling
#averageDistance = self._timeEstimationData.average_distance
#self._estimationLogger.info("{progress};{printTime};{newEstimate};{averageTotal};{averageTotalRolling};{averageDistance}".format(**locals()))
return result
def _setProgressData(self, progress, filepos, printTime):
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, printTime)
statisticalTotalPrintTime = None
totalPrintTime = estimatedTotalPrintTime
if self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"]:
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
if progress and printTime:
if estimatedTotalPrintTime is None:
totalPrintTime = statisticalTotalPrintTime
else:
if progress < 50:
sub_progress = progress * 2 / 100
else:
sub_progress = 1.0
totalPrintTime = (1 - sub_progress) * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime
#self._printTimeLogger.info("{progress};{printTime};{estimatedTotalPrintTime};{statisticalTotalPrintTime};{totalPrintTime}".format(**locals()))
self._progress = progress
self._printTime = printTime
self._printTimeLeft = totalPrintTime - printTime if (totalPrintTime is not None and printTime is not None) else None
self._stateMonitor.setProgress({
"completion": self._progress,
"filepos": filepos,
"printTime": int(self._printTime) if self._printTime is not None else None,
"printTimeLeft": int(self._printTimeLeft) if self._printTimeLeft is not None else None
})
if progress:
progress_int = int(progress)
if self._lastProgressReport != progress_int:
self._lastProgressReport = progress_int
self._reportPrintProgressToPlugins(progress_int)
def _addTemperatureData(self, temperatureData):
currentTimeUtc = int(time.time())
data = {
"time": currentTimeUtc
}
for tool in temperatureData.keys():
data[tool] = {
"actual": temperatureData[tool][0],
"target": temperatureData[tool][1]
}
self._temps.append(data)
self._stateMonitor.addTemperature(data)
def _setJobData(self, filename, filesize, origin):
sd = origin == FileDestinations.SDCARD
if filename is not None:
self._selectedFile = {
"filename": filename,
"filesize": filesize,
"sd": sd,
"estimatedPrintTime": None
}
else:
self._selectedFile = None
self._stateMonitor.setJobData({
"file": {
"name": None,
"origin": None,
"size": None,
"date": None
},
"estimatedPrintTime": None,
"averagePrintTime": None,
"lastPrintTime": None,
"filament": None,
})
return
estimatedPrintTime = None
lastPrintTime = None
averagePrintTime = None
date = None
filament = None
if filename:
# Use a string for mtime because it could be float and the
# javascript needs to exact match
if not sd:
date = int(os.stat(filename).st_ctime)
try:
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, filename)
except:
fileData = None
if fileData is not None:
if "analysis" in fileData:
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]:
estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"]
if "filament" in fileData["analysis"].keys():
filament = fileData["analysis"]["filament"]
if "statistics" in fileData:
printer_profile = self._printerProfileManager.get_current_or_default()["id"]
if "averagePrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["averagePrintTime"]:
averagePrintTime = fileData["statistics"]["averagePrintTime"][printer_profile]
if "lastPrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["lastPrintTime"]:
lastPrintTime = fileData["statistics"]["lastPrintTime"][printer_profile]
if averagePrintTime is not None:
self._selectedFile["estimatedPrintTime"] = averagePrintTime
elif estimatedPrintTime is not None:
# TODO apply factor which first needs to be tracked!
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
self._stateMonitor.setJobData({
"file": {
"name": os.path.basename(filename) if filename is not None else None,
"origin": origin,
"size": filesize,
"date": date
},
"estimatedPrintTime": estimatedPrintTime,
"averagePrintTime": averagePrintTime,
"lastPrintTime": lastPrintTime,
"filament": filament,
})
def _sendInitialStateUpdate(self, callback):
try:
data = self._stateMonitor.getCurrentData()
data.update({
"temps": list(self._temps),
"logs": list(self._log),
"messages": list(self._messages)
})
callback.sendHistoryData(data)
except Exception, err:
import sys
sys.stderr.write("ERROR: %s\n" % str(err))
pass
def _getStateFlags(self):
return {
"operational": self.isOperational(),
"printing": self.isPrinting(),
"closedOrError": self.isClosedOrError(),
"error": self.isError(),
"paused": self.isPaused(),
"ready": self.isReady(),
"sdReady": self.isSdReady()
}
#~~ callbacks triggered from self._comm
def mcReceivedRegisteredMessage(self, command, output):
self._sendFeedbackCommandOutput(command, output)
def mcForceDisconnect(self):
self.disconnect()
#~~ sd file handling
def getSdFiles(self):
if not self._protocol.is_sd_ready():
return []
return self._protocol.get_sd_files()
def addSdFile(self, filename, absolutePath, streamingFinishedCallback):
if self._protocol.is_busy() or not self._protocol.is_sd_ready():
logging.error("No connection to printer or printer is busy")
return
self._streamingFinishedCallback = streamingFinishedCallback
self.refreshSdFiles(blocking=True)
existingSdFiles = map(lambda x: x[0], self._protocol.get_sd_files())
self._sdRemoteName = util.getDosFilename(filename, existingSdFiles)
self._protocol.add_sd_file(absolutePath, filename, self._sdRemoteName)
return self._sdRemoteName
def deleteSdFile(self, filename):
if not self._protocol.is_sd_ready():
return
self._protocol.remove_sd_file(filename)
def initSdCard(self):
self._protocol.init_sd()
def releaseSdCard(self):
if not self._protocol.is_sd_ready() or self._protocol.is_busy():
return
self._protocol.release_sd()
def refreshSdFiles(self, blocking=False):
"""
Refreshs the list of file stored on the SD card attached to printer (if available and printer communication
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
received (and can be accessed via self._protocol.get_sd_files()). Defaults to a asynchronous operation.
"""
if not self._protocol.is_sd_ready():
return
self._sdFilelistAvailable.clear()
self._protocol.refresh_sd_files()
if blocking:
self._sdFilelistAvailable.wait(10000)
#~~ state reports
def getStateString(self):
"""
Returns a human readable string corresponding to the current communication state.
"""
return self._state
def getCurrentData(self):
return self._stateMonitor.getCurrentData()
def getCurrentJob(self):
currentData = self._stateMonitor.getCurrentData()
return currentData["job"]
def getCurrentTemperatures(self):
temperatures = self._protocol.get_current_temperatures()
offsets = self._protocol.get_temperature_offsets()
result = {}
result.update(temperatures)
for key, tool in result:
tool["offset"] = offsets[key] if key in offsets and offsets[key] is not None else 0
return result
def getTemperatureHistory(self):
return self._temps
def getCurrentConnection(self):
opt = self._protocol.get_current_connection()
if "port" in opt.keys() and "baudrate" in opt.keys():
return self._protocol.get_state(), opt["port"], opt["baudrate"], self._printerProfileManager.get_current_or_default()
return self._protocol.get_state(), None, None, None
def isClosedOrError(self):
return self._protocol.get_state() == ProtocolState.OFFLINE or self._protocol == ProtocolState.ERROR
def isOperational(self):
return not self.isClosedOrError()
def isPrinting(self):
return self._protocol.get_state() == ProtocolState.PRINTING
def isPaused(self):
return self._protocol.get_state() == ProtocolState.PAUSED
def isError(self):
return self._protocol.get_state() == ProtocolState.ERROR
def isReady(self):
return self.isOperational() and not self._protocol.is_streaming()
def isSdReady(self):
if not settings().getBoolean(["feature", "sdSupport"]):
return False
else:
return self._protocol.is_sd_ready()
class StateMonitor(object):
def __init__(self, ratelimit, updateCallback, addTemperatureCallback, addLogCallback, addMessageCallback):
self._ratelimit = ratelimit
self._updateCallback = updateCallback
self._addTemperatureCallback = addTemperatureCallback
self._addLogCallback = addLogCallback
self._addMessageCallback = addMessageCallback
self._state = None
self._jobData = None
self._gcodeData = None
self._sdUploadData = None
self._currentZ = None
self._progress = None
self._offsets = {}
self._changeEvent = threading.Event()
self._stateMutex = threading.Lock()
self._lastUpdate = time.time()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def reset(self, state=None, jobData=None, progress=None, currentZ=None):
self.setState(state)
self.setJobData(jobData)
self.setProgress(progress)
self.setCurrentZ(currentZ)
def addTemperature(self, temperature):
self._addTemperatureCallback(temperature)
self._changeEvent.set()
def addLog(self, log):
self._addLogCallback(log)
self._changeEvent.set()
def addMessage(self, message):
self._addMessageCallback(message)
self._changeEvent.set()
def setCurrentZ(self, currentZ):
self._currentZ = currentZ
self._changeEvent.set()
def setState(self, state):
with self._stateMutex:
self._state = state
self._changeEvent.set()
def setJobData(self, jobData):
self._jobData = jobData
self._changeEvent.set()
def setProgress(self, progress):
self._progress = progress
self._changeEvent.set()
def setTempOffsets(self, offsets):
self._offsets = offsets
self._changeEvent.set()
def _work(self):
while True:
self._changeEvent.wait()
with self._stateMutex:
now = time.time()
delta = now - self._lastUpdate
additionalWaitTime = self._ratelimit - delta
if additionalWaitTime > 0:
time.sleep(additionalWaitTime)
data = self.getCurrentData()
self._updateCallback(data)
self._lastUpdate = time.time()
self._changeEvent.clear()
def getCurrentData(self):
return {
"state": self._state,
"job": self._jobData,
"currentZ": self._currentZ,
"progress": self._progress,
"offsets": self._offsets
}
class TimeEstimationHelper(object):
STABLE_THRESHOLD = 0.1
STABLE_COUNTDOWN = 250
STABLE_ROLLING_WINDOW = 250
def __init__(self):
import collections
self._distances = collections.deque([], self.__class__.STABLE_ROLLING_WINDOW)
self._totals = collections.deque([], self.__class__.STABLE_ROLLING_WINDOW)
self._sum_total = 0
self._count = 0
self._stable_counter = None
def is_stable(self):
return self._stable_counter is not None and self._stable_counter >= self.__class__.STABLE_COUNTDOWN
def update(self, newEstimate):
old_average_total = self.average_total
self._sum_total += newEstimate
self._totals.append(newEstimate)
self._count += 1
if old_average_total:
self._distances.append(abs(self.average_total - old_average_total))
if -1.0 * self.__class__.STABLE_THRESHOLD < self.average_distance < self.__class__.STABLE_THRESHOLD:
if self._stable_counter is None:
self._stable_counter = 0
else:
self._stable_counter += 1
else:
self._stable_counter = None
@property
def average_total(self):
if not self._count:
return None
else:
return self._sum_total / self._count
@property
def average_total_rolling(self):
if not self._count or self._count < self.__class__.STABLE_ROLLING_WINDOW:
return None
else:
return sum(self._totals) / len(self._totals)
@property
def average_distance(self):
if not self._count or self._count < self.__class__.STABLE_ROLLING_WINDOW + 1:
return None
else:
return sum(self._distances) / len(self._distances)
+218
View File
@@ -0,0 +1,218 @@
# 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
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()
return False
else:
self._current = self.get(identifier)
return True
def deselect(self):
self._current = None
def get_all(self):
return self._load_all()
def get(self, identifier):
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)
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
+179 -30
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,15 +202,22 @@ class Server():
self._checkForRoot()
global printer
global gcodeManager
global printerProfileManager
global fileManager
global slicingManager
global analysisQueue
global userManager
global eventManager
global loginManager
global pluginManager
global appSessionManager
global debug
from tornado.ioloop import IOLoop
from tornado.web import Application
import sys
debug = self._debug
# first initialize the settings singleton and make sure it uses given configfile and basedir if available
@@ -162,14 +226,39 @@ class Server():
# then initialize logging
self._initLogging(self._debug, self._logConf)
logger = logging.getLogger(__name__)
def exception_logger(exc_type, exc_value, exc_tb):
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
sys.excepthook = exception_logger
logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)
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()
@@ -191,11 +280,21 @@ class Server():
app.wsgi_app,
settings().get(["server", "reverseProxy", "prefixHeader"]),
settings().get(["server", "reverseProxy", "schemeHeader"]),
settings().get(["server", "reverseProxy", "hostHeader"]),
settings().get(["server", "reverseProxy", "prefixFallback"]),
settings().get(["server", "reverseProxy", "prefixScheme"])
settings().get(["server", "reverseProxy", "schemeFallback"]),
settings().get(["server", "reverseProxy", "hostFallback"])
)
app.secret_key = "k3PuVYgtxNm8DXKKTw2nWmFQQun9qceV"
secret_key = settings().get(["server", "secretKey"])
if not secret_key:
import string
from random import choice
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
secret_key = "".join(choice(chars) for _ in xrange(32))
settings().set(["server", "secretKey"], secret_key)
settings().save()
app.secret_key = secret_key
loginManager = LoginManager()
loginManager.session_protection = "strong"
loginManager.user_callback = load_user
@@ -209,19 +308,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 +352,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(transport_option_overrides=dict(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:
@@ -299,10 +445,13 @@ class Server():
}
},
"loggers": {
"SERIAL": {
"TRANSPORT": {
"level": "CRITICAL",
"handlers": ["serialFile"],
"propagate": False
},
"tornado.application": {
"level": "ERROR"
}
},
"root": {
@@ -328,8 +477,8 @@ class Server():
if settings().getBoolean(["serial", "log"]):
# enable debug logging to serial.log
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
logging.getLogger("TRANSPORT").setLevel(logging.DEBUG)
logging.getLogger("TRANSPORT").debug("Enabling transport logging")
if __name__ == "__main__":
server = Server()
+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)
+31 -9
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,20 +17,22 @@ 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"])
@restricted_access
def connectionCommand():
valid_commands = {
"connect": ["autoconnect"],
"connect": [],
"disconnect": []
}
@@ -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(transport_option_overrides=dict(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
+185 -34
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,42 @@ def _getFileList(origin):
file.update({"size": sdSize})
files.append(file)
else:
files = gcodeManager.getAllFileData()
filter_func = None
if filter:
filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(entry, type=filter)
files = fileManager.list_files(origin, filter=filter_func, recursive=False)[origin].values()
for file in files:
file["origin"] = FileDestinations.LOCAL
if "analysis" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
file["gcodeAnalysis"] = file["analysis"]
del file["analysis"]
if "history" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
# convert print log
history = file["history"]
del file["history"]
success = 0
failure = 0
last = None
for entry in history:
success += 1 if "success" in entry and entry["success"] else 0
failure += 1 if "success" in entry and not entry["success"] else 0
if not last or ("timestamp" in entry and "timestamp" in last and entry["timestamp"] > last["timestamp"]):
last = entry
if last:
prints = dict(
success=success,
failure=failure,
last=dict(
success=last["success"],
date=last["timestamp"]
)
)
if "printTime" in last:
prints["last"]["printTime"] = last["printTime"]
file["prints"] = prints
file.update({
"refs": {
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file["name"], _external=True),
@@ -79,11 +117,9 @@ def _getFileList(origin):
def _verifyFileExists(origin, filename):
if origin == FileDestinations.SDCARD:
availableFiles = map(lambda x: x[0], printer.getSdFiles())
return filename in map(lambda x: x[0], printer.getSdFiles())
else:
availableFiles = gcodeManager.getAllFilenames()
return filename in availableFiles
return fileManager.file_exists(origin, filename)
@api.route("/files/<string:target>", methods=["POST"])
@@ -130,8 +166,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 +184,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 +200,18 @@ def uploadGcodeFile(target):
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
exact file is already selected, such reloading it.
"""
if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination):
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 +272,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,18 +283,120 @@ 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
sd = False
if target == FileDestinations.SDCARD:
filenameToSelect = filename
sd = True
else:
filenameToSelect = gcodeManager.getAbsolutePath(filename)
printer.selectFile(filenameToSelect, sd, printAfterLoading)
filenameToSelect = fileManager.get_absolute_path(target, filename)
printer.selectFile(filenameToSelect, target, 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 +410,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
+8 -7
View File
@@ -300,7 +300,6 @@ def printerSdState():
@api.route("/printer/command", methods=["POST"])
@restricted_access
def printerCommand():
# TODO: document me
if not printer.isOperational():
return make_response("Printer is not operational", 409)
@@ -309,15 +308,17 @@ def printerCommand():
data = request.json
parameters = {}
if "parameters" in data.keys():
parameters = data["parameters"]
parameters = dict()
if "parameters" in data.keys(): parameters = data["parameters"]
commands = []
if "command" in data.keys():
if "command" in data and "commands" in data:
return make_response("'command' and 'commands' are mutually exclusive", 400)
elif "command" in data:
commands = [data["command"]]
elif "commands" in data.keys():
elif "commands" in data and isinstance(data["commands"], (list, tuple)):
commands = data["commands"]
else:
return make_response("Need either single 'command' or list of 'commands'", 400)
commandsToSend = []
for command in commands:
@@ -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[1])))
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)))
+32 -27
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,15 +27,12 @@ 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": {
@@ -40,14 +40,6 @@ def getSettings():
"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 +94,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"])
@@ -123,14 +129,6 @@ def setSettings():
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():
@@ -166,12 +164,12 @@ def setSettings():
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
if oldLog and not s.getBoolean(["serial", "log"]):
# disable debug logging to serial.log
logging.getLogger("SERIAL").debug("Disabling serial logging")
logging.getLogger("SERIAL").setLevel(logging.CRITICAL)
logging.getLogger("TRANSPORT").debug("Disabling transport logging")
logging.getLogger("TRANSPORT").setLevel(logging.CRITICAL)
elif not oldLog and s.getBoolean(["serial", "log"]):
# enable debug logging to serial.log
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
logging.getLogger("TRANSPORT").setLevel(logging.DEBUG)
logging.getLogger("TRANSPORT").debug("Enabling transport logging")
if "folder" in data.keys():
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
@@ -204,7 +202,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
+97 -8
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):
@@ -72,20 +147,25 @@ class ReverseProxied(object):
:param app: the WSGI application
:param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix
:param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme
:param header_host: the HTTP header in the wsgi environment from which to determine the host for which to generate external URLs
:param base_url: the prefix to use as fallback if headers are not set
:param scheme: the scheme to use as fallback if headers are not set
:param host: the host to use as fallback if headers are not set
"""
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", base_url="", scheme=""):
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", header_host="x-forwarded-host", base_url="", scheme="", host=""):
self.app = app
# headers for prefix & scheme, converted to conform to WSGI format
# headers for prefix & scheme & host, converted to conform to WSGI format
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
self._header_prefix = to_wsgi_format(header_prefix)
self._header_scheme = to_wsgi_format(header_scheme)
self._header_host = to_wsgi_format(header_host)
# fallback prefix & scheme from config
# fallback prefix & scheme & host from config
self._fallback_prefix = base_url
self._fallback_scheme = scheme
self._fallback_host = host
def __call__(self, environ, start_response):
# determine prefix
@@ -109,6 +189,15 @@ class ReverseProxied(object):
if scheme:
environ["wsgi.url_scheme"] = scheme
# determine host
host = environ.get(self._header_host, "")
if not host:
host = self._fallback_host
# rewrite host header based on host
if host:
environ["HTTP_HOST"] = host
# call wrapped app with rewritten environment
return self.app(environ, start_response)
+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)
+41 -20
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,13 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
self._messageBacklogMutex = threading.Lock()
self._printer = printer
self._gcodeManager = gcodeManager
self._fileManager = fileManager
self._analysisQueue = analysisQueue
self._userManager = userManager
self._eventManager = eventManager
self._pluginManager = pluginManager
self._remoteAddress = None
def _getRemoteAddress(self, info):
forwardedFor = info.headers.get("X-Forwarded-For")
@@ -43,30 +43,32 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
return info.ip
def on_open(self, info):
remoteAddress = self._getRemoteAddress(info)
self._logger.info("New connection from client: %s" % remoteAddress)
self._remoteAddress = self._getRemoteAddress(info)
self._logger.info("New connection from client: %s" % self._remoteAddress)
# connected => update the API key, might be necessary if the client was left open while the server restarted
self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION})
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:
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
for event in octoprint.events.all_events():
self._eventManager.subscribe(event, self._onEvent)
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
def on_close(self):
self._logger.info("Client connection closed")
self._logger.info("Client connection closed: %s" % self._remoteAddress)
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:
self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
for event in octoprint.events.all_events():
self._eventManager.unsubscribe(event, self._onEvent)
def on_message(self, message):
@@ -86,10 +88,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 +115,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)
@@ -121,4 +139,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
self.sendEvent(event, payload)
def _emit(self, type, payload):
self.send({type: payload})
try:
self.send({type: payload})
except Exception as e:
self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, e.message))
+12 -64
View File
@@ -24,6 +24,7 @@ import tornado.httpclient
import tornado.http1connection
import tornado.iostream
import tornado.tcpserver
import tornado.util
import octoprint.util
@@ -193,7 +194,8 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
end_of_header = None
if delimiter_loc != -1:
# found the delimiter in the currently available data
data, self._buffer = data[0:delimiter_loc], data[delimiter_loc:]
delimiter_data_end = 0 if delimiter_loc == 0 else delimiter_loc - 2
data, self._buffer = data[0:delimiter_data_end], data[delimiter_loc:]
end_of_header = self._buffer.find("\r\n\r\n")
else:
# make sure any boundary (with single or double ==) contained at the end of chunk does not get
@@ -338,7 +340,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
if "content_type" in part and part["content_type"] is not None:
self._new_body += b"Content-Type: %s\r\n" % part["content_type"]
self._new_body += b"\r\n"
self._new_body += value
self._new_body += value + b"\r\n"
self._new_body += b"--%s--\r\n" % self._multipart_boundary
def _handle_method(self, *args, **kwargs):
@@ -707,80 +709,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)
+176 -57
View File
@@ -23,6 +23,30 @@ def settings(init=False, configfile=None, basedir=None):
return instance
default_settings = {
"communication": {
"protocol": "reprap",
"protocolOptions": {
"buffer": 63,
"temperature": 5,
"sdStatus": 1,
"waitForStart": False,
"forceChecksum": True,
"sdAlwaysAvailable": False
},
"transport": "serial",
"transportOptions": {
"port": None,
"baudrate": None,
"timeout": {
"read": 5,
"write": 0.5
},
"additionalPorts": []
},
"autoconnect": False,
"log": False
},
# TODO Remove, not used by the new communication layer but apparently still by the layers above it!
"serial": {
"port": None,
"baudrate": None,
@@ -41,16 +65,19 @@ default_settings = {
"host": "0.0.0.0",
"port": 5000,
"firstRun": True,
"secretKey": None,
"reverseProxy": {
"prefixHeader": "X-Script-Name",
"schemeHeader": "X-Scheme",
"hostHeader": "X-Forwarded-Host",
"prefixFallback": "",
"schemeFallback": ""
"schemeFallback": "",
"hostFallback": ""
},
"uploads": {
"maxSize": 1 * 1024 * 1024 * 1024, # 1GB
"nameSuffix": ".name",
"pathSuffix": ".path"
"nameSuffix": "name",
"pathSuffix": "path"
},
"maxSize": 100 * 1024, # 100 KB
},
@@ -78,12 +105,12 @@ default_settings = {
},
"feature": {
"temperatureGraph": True,
"waitForStartOnConnect": False,
"alwaysSendChecksum": False,
"sdSupport": True,
"sdAlwaysAvailable": False,
"swallowOkAfterResend": True,
"repetierTargetTemp": False
"waitForStartOnConnect": False, # TODO move to protocol options or reprap protocol
"alwaysSendChecksum": True, # TODO move to protocol options
"sdSupport": True, # TODO remove (can be always on)
"sdAlwaysAvailable": False, # TODO move to protocol options
"swallowOkAfterResend": True, # TODO remove (must always be done!)
"repetierTargetTemp": False # TODO remove (built into repetier protocol implementation)
},
"folder": {
"uploads": None,
@@ -91,31 +118,23 @@ 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": {
@@ -128,6 +147,7 @@ default_settings = {
},
"accessControl": {
"enabled": True,
"salt": None,
"userManager": "octoprint.users.FilebasedUserManager",
"userfile": None,
"autologinLocal": False,
@@ -139,19 +159,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": {
@@ -161,9 +188,21 @@ default_settings = {
"okWithLinenumber": False,
"numExtruders": 1,
"includeCurrentToolInTemps": True,
"movementSpeed": {
"x": 6000,
"y": 6000,
"z": 200,
"e": 300
},
"hasBed": True,
"repetierStyleTargetTemperature": False,
"extendedSdFileList": False
"smoothieTemperatureReporting": False,
"extendedSdFileList": False,
"throttle": 0.01,
"waitOnLongMoves": False,
"rxBuffer": 64,
"txBuffer": 40,
"commandBuffer": 4
}
}
}
@@ -179,6 +218,7 @@ class Settings(object):
self._config = None
self._dirty = False
self._mtime = None
self._init_settings_dir(basedir)
@@ -188,12 +228,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 +253,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 +262,72 @@ 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 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 +440,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 +488,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 +508,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 +519,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 +530,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 +605,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 +639,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 +652,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 +665,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)
+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 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))
elif result is not None and isinstance(result, dict) and "analysis" in result:
callback_kwargs.update(dict(_analysis=result["analysis"]))
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,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
+149 -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,38 @@ 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");
}
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);
}
})
}
}
}
};
+75 -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];
@@ -324,6 +342,21 @@ function formatDuration(seconds) {
return _.sprintf(gettext(/* L10N: duration format */ "%(hour)02d:%(minute)02d:%(second)02d"), {hour: h, minute: m, second: s});
}
function formatFuzzyEstimation(seconds, base) {
if (!seconds) return "-";
if (seconds < 0) return "-";
var m;
if (base != undefined) {
m = moment(base);
} else {
m = moment();
}
m.add(seconds, "s");
return m.fromNow(true);
}
function formatDate(unixTimestamp) {
if (!unixTimestamp) return "-";
return moment.unix(unixTimestamp).format(gettext(/* L10N: Date format */ "YYYY-MM-DD HH:mm"));
@@ -359,3 +392,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,4 +1,4 @@
function AppearanceViewModel(settingsViewModel) {
function AppearanceViewModel(settingsViewModel, printerStateViewModel) {
var self = this;
self.name = settingsViewModel.appearance_name;
@@ -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,15 @@ 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;
var printerProfiles = response.options.printerProfiles;
self.portOptions(ports);
self.baudrateOptions(baudrates);
@@ -52,17 +71,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 +106,7 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
connectionTab.collapse("show");
}
}
}
};
self.connect = function() {
if (self.isErrorOrClosed()) {
@@ -93,6 +114,7 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
"command": "connect",
"port": self.selectedPort(),
"baudrate": self.selectedBaudrate(),
"printerProfile": self.selectedPrinter(),
"autoconnect": self.settings.serial_autoconnect()
};
@@ -106,7 +128,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 +142,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);
@@ -110,7 +114,7 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
self.sendJogCommand = function(axis, multiplier, distance) {
if (typeof distance === "undefined")
distance = $('#jog_distance button.active').data('distance');
if (self.settings.getPrinterInvertAxis(axis)) {
if (self.settings.printerProfiles.currentProfileData() && self.settings.printerProfiles.currentProfileData()["axes"] && self.settings.printerProfiles.currentProfileData()["axes"][axis] && self.settings.printerProfiles.currentProfileData()["axes"][axis]["inverted"]()) {
multiplier *= -1;
}
@@ -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();
};
}
+112 -38
View File
@@ -95,42 +95,109 @@ 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;
GCODE.ui.updateOptions({
renderer: {
invertAxes: {
x: self.settings.printer_invertX(),
y: self.settings.printer_invertY()
var toolOffsets = self._retrieveToolOffsets(currentProfileData);
if (toolOffsets) {
GCODE.ui.updateOptions({
reader: {
toolOffsets: toolOffsets
}
}
});
});
}
var bedDimensions = self._retrieveBedDimensions(currentProfileData);
if (toolOffsets) {
GCODE.ui.updateOptions({
renderer: {
bed: bedDimensions
}
});
}
var axesConfiguration = self._retrieveAxesConfiguration(currentProfileData);
if (axesConfiguration) {
GCODE.ui.updateOptions({
renderer: {
invertAxes: axesConfiguration
}
});
}
});
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';
@@ -156,8 +223,9 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
onProgress: self._onProgress,
onModelLoaded: self._onModelLoaded,
onLayerSelected: self._onLayerSelected,
bed: self.settings.printer_bedDimensions(),
toolOffsets: self.settings.printer_extruderOffsets()
bed: self._retrieveBedDimensions(),
toolOffsets: self._retrieveToolOffsets(),
invertAxes: self._retrieveAxesConfiguration()
});
self.synchronizeOptions();
self.enabled = true;
@@ -332,7 +400,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 +422,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 +475,8 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]);
};
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,315 @@
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.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 = [parseFloat(self.editorExtruderOffsets()[i]["x"]()), parseFloat(self.editorExtruderOffsets()[i]["y"]())];
}
profile.extruder.offsets.push(offset);
}
}
return profile;
};
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());
@@ -52,9 +62,15 @@ function PrinterStateViewModel(loginStateViewModel) {
return formatDuration(self.printTime());
});
self.printTimeLeftString = ko.computed(function() {
if (!self.printTimeLeft())
return "-";
return formatDuration(self.printTimeLeft());
if (self.printTimeLeft() == undefined) {
if (!self.printTime() || !(self.isPrinting() || self.isPaused())) {
return "-";
} else {
return gettext("Calculating...");
}
} else {
return formatFuzzyEstimation(self.printTimeLeft());
}
});
self.progressString = ko.computed(function() {
if (!self.progress())
@@ -101,9 +117,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 +131,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 +186,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 +220,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,8 +1,9 @@
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);
@@ -19,8 +20,9 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
{key: "green", name: gettext("green")},
{key: "blue", name: gettext("blue")},
{key: "violet", name: gettext("violet")},
{key: "black", name: gettext("black")},
{key: "black", name: gettext("black")}
]);
self.appearance_colorName = function(color) {
switch (color) {
case "red":
@@ -44,83 +46,8 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
}
};
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);
@@ -133,6 +60,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
self.feature_temperatureGraph = ko.observable(undefined);
self.feature_waitForStart = ko.observable(undefined);
self.feature_alwaysSendChecksum = ko.observable(undefined);
self.feature_pingPong = ko.observable(undefined);
self.feature_sdSupport = ko.observable(undefined);
self.feature_sdAlwaysAvailable = ko.observable(undefined);
self.feature_swallowOkAfterResend = ko.observable(undefined);
@@ -166,6 +94,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 +112,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,6 +129,12 @@ 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);
@@ -227,14 +142,6 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
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,7 +191,9 @@ 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(),
@@ -295,14 +204,6 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
"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 +255,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
"config": self.cura_config()
},
"terminalFilters": self.terminalFilters()
};
});
$.ajax({
url: API_BASEURL + "settings",
@@ -367,6 +268,5 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
$("#settings_dialog").modal("hide");
}
});
}
};
}
@@ -0,0 +1,172 @@
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.requestData();
self.target = target;
self.file = file;
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file}));
self.gcodeFilename(self.file.substr(0, self.file.lastIndexOf(".")));
self.printerProfile(self.printerProfiles.currentProfile());
self.afterSlicing("none");
$("#slicing_configuration_dialog").modal("show");
};
self.slicer.subscribe(function(newValue) {
self.profilesForSlicer(newValue);
});
self.enableSliceButton = ko.computed(function() {
return self.gcodeFilename() != undefined
&& self.gcodeFilename().trim() != ""
&& self.slicer() != undefined
&& self.profile() != undefined;
});
self.requestData = function(callback) {
$.ajax({
url: API_BASEURL + "slicing",
type: "GET",
dataType: "json",
success: function(data) {
self.fromResponse(data);
if (callback !== undefined) {
callback();
}
}
});
};
self.fromResponse = function(data) {
self.data = data;
var selectedSlicer = undefined;
self.slicers.removeAll();
_.each(_.values(data), function(slicer) {
var name = slicer.displayName;
if (name == undefined) {
name = slicer.key;
}
if (slicer.default) {
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-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:11+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@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", "sec": "Sek", "Proceed": "Fortfahren", "Timelapse Temp Folder": "Tempor\u00e4res Zeitrafferverzeichnis", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "<code>TargetExtr%%n</code>/<code>TargetBed</code> Zieltemperaturformat unterst\u00fctzen", "Upload Folder": "Uploadverzeichnis", "Only show files stored locally": "Nur lokal abgelegte Dateien anzeigen", "Add Printer Profile": "Druckerprofil hinzuf\u00fcgen", "yellow": "Gelb", "Save": "Speichern", "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", "Color": "Farbe", "Temperature": "Temperatur", "Files": "Dateien", "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", "Form Factor": "Formfaktor", "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", "Select for printing": "Zum Drucken ausw\u00e4hlen", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "<a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a> erlauben", "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, mich erneut zu verbinden, aber Du kannst mittels des folgenden Buttons auch jederzeit einen manuellen Reconnect ansto\u00dfen.", "Rendering failed": "Rendering fehlgeschlagen", "Motors off": "Motoren aus", "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", "Nozzle Diameter": "D\u00fcsendurchmesser", "Sort by file size": "Nach Gr\u00f6\u00dfe sortieren", "Machine State": "Druckerstatus", "Slicing Profile": "Slicingprofil", "mm": "mm", "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\"", "Enable Temperature Graph": "Temperaturgraph aktivieren", "Delete user": "Nutzer l\u00f6schen", "Timelapse bitrate": "Zeitrafferbitrate", "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", "Delete Profile": "Profil entfernen", "Tool": "Werkzeug", "Settings": "Einstellungen", "Circular": "Rund", "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.", "Select a slicing profile...": "W\u00e4hle ein Slicingprofile...", "Wait for <code>start</code> on connect":Line truncated
+1 -1
View File
@@ -1 +1 @@
window.BABEL_TO_LOAD_fr = {"locale": "fr", "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 13:54+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: French (http://www.transifex.com/projects/p/octoprint/language/fr/)\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": "Temps d'impression restant", "Proceed": "Continuer", "Timelapse Temp Folder": "R\u00e9pertoire temporaire des timelapses", "Title": "Titre", "Only show files stored locally": "Ne montre que les fichiers enregistr\u00e9s localement", "yellow": "jaune", "Path to Cura": "Chemin vers Cura", "Action": "Action", "Passwords do not match": "Les mots de passes ne sont pas semblables", "Sort by name": "Trier par nom", "Save connection settings": "Sauvegarder les param\u00e8tres de connection", "Rendering timelapse": "Rendu du timelapse en cours", "Cura": "Cura", "Files": "Fichiers", "Bed Size": "Taille du lit", "Always assume SD card is present": "Toujours supposer que la carte SD est pr\u00e9sente", "Load and Print": "Charger et imprimer", "Sending file to SD": "Envoi du fichier vers la carte SD en cours", "Number of Extruders": "Nombre d'extrudeurs", "black": "noir", "Last Printed": "Impression pr\u00e9c\u00e9dente", "Sourcecode": "Code source", "Estimated layer height": "Hauteur de couche estim\u00e9e", "You are now logged out": "Vous \u00eates maintenant d\u00e9connect\u00e9", "Uploaded": "Charg\u00e9", "Opening serial port": "Ouverture du port s\u00e9rie en cours", "New timelapse %(movie_basename)s is done rendering.": "Le rendu du nouveau timelapse %(movie_basename)s est termin\u00e9.", "Invert control": "Inverser le contr\u00f4le", "Webcam": "Webcam", "Remember me": "Se souvenir de moi", "Enable GCode Visualizer": "Activer le visualisateur de GCode", "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.": "Le serveur semble \u00eatre hors ligne, du moins je ne re\u00e7ois aucunes r\u00e9ponses de celui-ci. Je vais tenter de me reconnecter automatiquement <strong>dans les minutes qui suivent</strong>. Quoiqu'il en soit vous pouvez tenter de vous reconnecter manuellement en utilisant le bouton ci-dessous.", "Rendering failed": "Echec du rendu", "Upload Folder": "R\u00e9pertoire des chargements", "descending": "descendant", "X": "X", "Add user": "Ajouter utilisateur", "GCODE commands in layer": "Commandes GCODE dans la couche", "Estimated print time": "Temps d'impression estim\u00e9", "Serial Connection": "Connection s\u00e9rie", "Control": "Contr\u00f4le", "Password": "Mot de passe", "Also show next layer": "Montrer \u00e9galement la couche suivante", "Print Time": "Temps d'impression", "Sort by file size": "Trier par taille des fichiers", "Machine State": "Etat de la machine", "default": "Par d\u00e9faut", "API": "API", "Printing from SD": "Impression depuis la carte SD en cours", "Terminal filters": "Filtres du terminal", "Change password for user \"%(user)s\"": "Changer le mot de passe pour l'utilisateur \"%(user)s\"", "Enable Temperature Graph": "Activer le graphique de temp\u00e9rature", "Delete user": "Supprimer utilisateur", "Confirm Password": "Confirmer le mot de passe", "Disconnect": "D\u00e9connecter", "Slicing done": "Tranchage termin\u00e9", "Initialize SD card": "Initialiser la carte SD", "System": "Syst\u00eame", "Send": "Envoyer", "State": "Etat", "Version": "Version", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Tentative de reconnection", "Streaming done": "Diffusion en direct termin\u00e9", "violet": "violet", "Print": "Imprimer", "Layer count": "Nombre de couches", "OctoPrint Settings": "Param\u00e8tres d'OctoPrint", "Are you sure?": "Etes-vous s\u00fbre?", "blue": "bleu", "Printer": "Imprimante", "Tool": "Outil", "Settings": "Param\u00e8tres", "Path to FFMPEG": "Chemin vers FFMPEG", "Upload to SD": "Chargement vers la carte SD", "The command \"%(command)s\" could not be executed.": "La commande \"%(command)s\" n'a pas pu \u00eatre ex\u00e9cut\u00e9e", "Printed": "Imprim\u00e9", "Layer number": "Couche num\u00e9ro", "Sync with job progress": "Synchroniser avec le progr\u00e8s du job", "Circular": "Circulaire", "Total filament used": "Quantit\u00e9 de filament utilis\u00e9", "red": "rouge", "Save as default": "Sauver en tant que d\u00e9faut", "Slicing ...": "Tranchage en cours...", "Last Print Time": "Temps d'impression pr\u00e9c\u00e9dent", "Target": "Cible", "Streaming ...": "Diffusion en direct en cours...", "Logout successful": "Fermeture de session r\u00e9ussie", "Now rendering timelapse %(movieLine truncated
window.BABEL_TO_LOAD_fr = {"locale": "fr", "domain": "messages", "plural_expr": "(n > 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: French (http://www.transifex.com/projects/p/octoprint/language/fr/)\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": "Temps d'impression restant", "sec": "sec", "Proceed": "Continuer", "Timelapse Temp Folder": "R\u00e9pertoire temporaire des timelapses", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> format de temp\u00e9rature de la cible", "Upload Folder": "R\u00e9pertoire des chargements", "Only show files stored locally": "Ne montre que les fichiers enregistr\u00e9s localement", "Add Printer Profile": "", "yellow": "jaune", "Save": "Sauver", "Action": "Action", "Passwords do not match": "Les mots de passes ne sont pas semblables", "Sort by name": "Trier par nom", "Save connection settings": "Sauvegarder les param\u00e8tres de connection", "Rendering timelapse": "Rendu du timelapse en cours", "Color": "Couleur", "Temperature": "Temp\u00e9rature", "Files": "Fichiers", "Resume": "", "Always assume SD card is present": "Toujours supposer que la carte SD est pr\u00e9sente", "Load and Print": "Charger et imprimer", "Sending file to SD": "Envoi du fichier vers la carte SD en cours", "Number of Extruders": "Nombre d'extrudeurs", "black": "noir", "Last Printed": "Impression pr\u00e9c\u00e9dente", "Sourcecode": "Code source", "Estimated layer height": "Hauteur de couche estim\u00e9e", "You are now logged out": "Vous \u00eates maintenant d\u00e9connect\u00e9", "Uploaded": "Charg\u00e9", "Form Factor": "", "Opening serial port": "Ouverture du port s\u00e9rie en cours", "New timelapse %(movie_basename)s is done rendering.": "Le rendu du nouveau timelapse %(movie_basename)s est termin\u00e9.", "Invert control": "Inverser le contr\u00f4le", "Webcam": "Webcam", "Select for printing": "", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "Permettre <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>", "Remember me": "Se souvenir de moi", "Enable GCode Visualizer": "Activer le visualisateur de GCode", "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.": "Le serveur semble \u00eatre hors ligne, du moins je ne re\u00e7ois aucunes r\u00e9ponses de celui-ci. Je vais tenter de me reconnecter automatiquement <strong>dans les minutes qui suivent</strong>. Quoiqu'il en soit vous pouvez tenter de vous reconnecter manuellement en utilisant le bouton ci-dessous.", "Rendering failed": "Echec du rendu", "Motors off": "Eteindre les moteurs", "descending": "descendant", "Only show files stored on SD": "Ne montrer que les fichier enregistr\u00e9s sur la carte SD", "X": "X", "Add user": "Ajouter utilisateur", "GCODE commands in layer": "Commandes GCODE dans la couche", "Estimated print time": "Temps d'impression estim\u00e9", "Serial Connection": "Connection s\u00e9rie", "Control": "Contr\u00f4le", "Password": "Mot de passe", "Also show next layer": "Montrer \u00e9galement la couche suivante", "Print Time": "Temps d'impression", "Slicer": "", "Nozzle Diameter": "", "Sort by file size": "Trier par taille des fichiers", "Machine State": "Etat de la machine", "Slicing Profile": "", "mm": "mm", "API": "API", "Printing from SD": "Impression depuis la carte SD en cours", "Stream URL": "URL de diffusion en direct", "Terminal filters": "Filtres du terminal", "Change password for user \"%(user)s\"": "Changer le mot de passe pour l'utilisateur \"%(user)s\"", "Enable Temperature Graph": "Activer le graphique de temp\u00e9rature", "Delete user": "Supprimer utilisateur", "Timelapse bitrate": "Bitrate du timelapse", "Confirm Password": "Confirmer le mot de passe", "Disconnect": "D\u00e9connecter", "Slicing done": "Tranchage termin\u00e9", "Initialize SD card": "Initialiser la carte SD", "System": "Syst\u00eame", "Send": "Envoyer", "State": "Etat", "Version": "Version", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Tentative de reconnection", "Streaming done": "Diffusion en direct termin\u00e9", "violet": "violet", "Print": "Imprimer", "Layer count": "Nombre de couches", "OctoPrint Settings": "Param\u00e8tres d'OctoPrint", "Are you sure?": "Etes-vous s\u00fbre?", "blue": "bleu", "Printer": "Imprimante", "Delete Profile": "", "Tool": "Outil", "Settings": "Param\u00e8tres", "Circular": "Circulaire", "Path to FFMPEG": "Chemin vers FFMPEG", "Upload to Line truncated
+1 -1
View File
@@ -1 +1 @@
window.BABEL_TO_LOAD_he = {"locale": "he", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint 1.2.0-dev-131-g854387b\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-31 12:52+0300\nPO-Revision-Date: 2014-08-31 18:44+0200\nLast-Translator: Guy Sheffer <guysoft@gmail.com>\nLanguage-Team: he <guysoft@gmail.com>\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": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05e0\u05d5\u05ea\u05e8", "Proceed": "\u05d4\u05de\u05e9\u05da", "Timelapse Temp Folder": "\u05ea\u05e7\u05d9\u05d9\u05d4 \u05d6\u05de\u05e0\u05d9\u05ea \u05dc-timelapse", "Title": "\u05db\u05d5\u05ea\u05e8\u05ea", "Only show files stored locally": "\u05d4\u05e6\u05d2 \u05e8\u05e7 \u05e7\u05d1\u05e6\u05d9\u05dd \u05d4\u05e9\u05de\u05d5\u05e8\u05d9\u05dd \u05de\u05e7\u05d5\u05de\u05d9\u05ea", "yellow": "\u05e6\u05d4\u05d5\u05d1", "Path to Cura": "\u05e0\u05ea\u05d9\u05d1 \u05dc-Cura", "Action": "\u05e4\u05e2\u05d5\u05dc\u05d4", "Passwords do not match": "\u05e1\u05d9\u05e1\u05de\u05d0\u05d5\u05ea \u05dc\u05d0 \u05ea\u05d5\u05d0\u05de\u05d5\u05ea", "Sort by name": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9 \u05e9\u05dd", "Save connection settings": "\u05e9\u05de\u05d5\u05e8 \u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05d7\u05d9\u05d1\u05d5\u05e8", "Rendering timelapse": "\u05de\u05e8\u05e0\u05d3\u05e8 timelapse", "Cura": "Cura", "Files": "\u05e7\u05d1\u05e6\u05d9\u05dd", "Bed Size": "\u05d2\u05d5\u05d3\u05dc \u05de\u05d9\u05d8\u05d4", "Always assume SD card is present": "\u05ea\u05de\u05d9\u05d3 \u05ea\u05e0\u05d9\u05d7 \u05e9\u05db\u05e8\u05d8\u05d9\u05e1 SD \u05e0\u05de\u05e6\u05d0", "Load and Print": "\u05d8\u05e2\u05df \u05d5\u05d4\u05d3\u05e4\u05e1", "Sending file to SD": "\u05e9\u05d5\u05dc\u05d7 \u05e7\u05d5\u05d1\u05e5 \u05d0\u05dc SD", "Number of Extruders": "\u05de\u05e1\u05e4\u05e8 \u05d0\u05e7\u05e1\u05d8\u05e8\u05d5\u05d3\u05e8\u05d9\u05dd", "black": "\u05e9\u05d7\u05d5\u05e8", "Last Printed": "\u05d4\u05d5\u05d3\u05e4\u05e1 \u05dc\u05d0\u05d7\u05e8\u05d5\u05e0\u05d4", "Sourcecode": "\u05e7\u05d5\u05d3 \u05de\u05e7\u05d5\u05e8", "Estimated layer height": "\u05d2\u05d5\u05d1\u05d4 \u05e9\u05db\u05d1\u05d5\u05ea \u05de\u05e9\u05d5\u05e2\u05e8", "You are now logged out": "\u05d4\u05ea\u05e0\u05ea\u05e7\u05ea \u05de\u05d4\u05de\u05e2\u05e8\u05db\u05ea", "Uploaded": "\u05d4\u05d5\u05e2\u05dc\u05d4", "Opening serial port": "\u05e4\u05d5\u05ea\u05d7 \u05d9\u05e6\u05d9\u05e8\u05d4 \u05d8\u05d5\u05e8\u05d9\u05ea", "New timelapse %(movie_basename)s is done rendering.": "\u05e1\u05d9\u05d9\u05dd \u05dc\u05e8\u05e0\u05d3\u05e8 \u05d0\u05ea \u05d4-timelapse %(movie_basename)s", "Invert control": "\u05d4\u05e4\u05d5\u05da \u05e9\u05dc\u05d9\u05d8\u05d4", "Webcam": "\u05de\u05e6\u05dc\u05de\u05ea \u05e8\u05e9\u05ea", "Remember me": "\u05d6\u05db\u05d5\u05e8 \u05d0\u05d5\u05ea\u05d9", "Enable GCode Visualizer": "\u05d4\u05e4\u05e2\u05dc \u05d5\u05d9\u05d6\u05d5\u05d0\u05dc\u05d9\u05d6\u05e6\u05d9\u05d4 \u05e9\u05dc GCode", "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.": "\u05e0\u05e8\u05d0\u05d4 \u05e9\u05d4\u05e9\u05e8\u05ea \u05dc\u05d0 \u05de\u05d7\u05d5\u05d1\u05e8, \u05d0\u05d5 \u05dc\u05e4\u05d7\u05d5\u05ea \u05d0\u05e0\u05d9 \u05dc\u05d0 \u05de\u05e6\u05dc\u05d9\u05d7 \u05dc\u05e7\u05d1\u05dc \u05db\u05dc \u05ea\u05d2\u05d5\u05d1\u05d4 \u05de\u05de\u05e0\u05d5. \u05d0\u05e0\u05e1\u05d4 \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05d0\u05d5\u05d8\u05d5\u05de\u05d8\u05d9\u05ea <strong>\u05d1\u05e2\u05d5\u05d3 \u05de\u05e1\u05e4\u05e8 \u05d3\u05e7\u05d5\u05ea</strong>, \u05d0\u05d1\u05dc \u05e0\u05d9\u05ea\u05df \u05d2\u05dd \u05dc\u05e0\u05e1\u05d5\u05ea \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05e2\u05dd \u05d4\u05db\u05e4\u05ea\u05d5\u05e8 \u05dc\u05d4\u05dc\u05df.", "Rendering failed": "\u05e8\u05d9\u05e0\u05d3\u05d5\u05e8 \u05e0\u05db\u05e9\u05dc", "Upload Folder": "\u05ea\u05e7\u05d9\u05d9\u05ea \u05d4\u05e2\u05dc\u05d0\u05d4", "descending": "\u05e1\u05d3\u05e8 \u05d9\u05d5\u05e8\u05d3", "X": "X", "Add user": "\u05d4\u05d5\u05e1\u05e3 \u05de\u05e9\u05ea\u05de\u05e9", "GCODE commands in layer": "\u05e4\u05e7\u05d5\u05d3\u05d5\u05ea GCODE \u05d1\u05e9\u05db\u05d1\u05d4", "Estimated print time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05de\u05e9\u05d5\u05e2\u05e8", "Serial Connection": "\u05d7\u05d9\u05d1\u05d5\u05e8 \u05d8\u05d5\u05e8\u05d9", "Control": "\u05e9\u05dc\u05d9\u05d8\u05d4", "Password": "\u05e1\u05d9\u05e1\u05de\u05d4", "Also show next layer": "\u05d0\u05e4\u05e9\u05e8 \u05d4\u05e6\u05d2\u05d4 \u05e9\u05dc \u05e9\u05db\u05d1\u05d4 \u05d4Line truncated
window.BABEL_TO_LOAD_he = {"locale": "he", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: Hebrew (http://www.transifex.com/projects/p/octoprint/language/he/)\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": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05e0\u05d5\u05ea\u05e8", "sec": "\u05e9\u05e0'", "Proceed": "\u05d4\u05de\u05e9\u05da", "Timelapse Temp Folder": "\u05ea\u05e7\u05d9\u05d9\u05d4 \u05d6\u05de\u05e0\u05d9\u05ea \u05dc-timelapse", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "\u05ea\u05de\u05d5\u05da \u05e2\u05d1\u05d5\u05e8 <code>TargetExtr%%n</code>/<code>TargetBed</code> \u05e4\u05d5\u05e8\u05de\u05d8 \u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05ea \u05d9\u05d9\u05e2\u05d3", "Upload Folder": "\u05ea\u05e7\u05d9\u05d9\u05ea \u05d4\u05e2\u05dc\u05d0\u05d4", "Only show files stored locally": "\u05d4\u05e6\u05d2 \u05e8\u05e7 \u05e7\u05d1\u05e6\u05d9\u05dd \u05d4\u05e9\u05de\u05d5\u05e8\u05d9\u05dd \u05de\u05e7\u05d5\u05de\u05d9\u05ea", "Add Printer Profile": "", "yellow": "\u05e6\u05d4\u05d5\u05d1", "Save": "\u05e9\u05de\u05d5\u05e8", "Action": "\u05e4\u05e2\u05d5\u05dc\u05d4", "Passwords do not match": "\u05e1\u05d9\u05e1\u05de\u05d0\u05d5\u05ea \u05dc\u05d0 \u05ea\u05d5\u05d0\u05de\u05d5\u05ea", "Sort by name": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9 \u05e9\u05dd", "Save connection settings": "\u05e9\u05de\u05d5\u05e8 \u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05d7\u05d9\u05d1\u05d5\u05e8", "Rendering timelapse": "\u05de\u05e8\u05e0\u05d3\u05e8 timelapse", "Color": "\u05e6\u05d1\u05e2", "Temperature": "\u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05d4", "Files": "\u05e7\u05d1\u05e6\u05d9\u05dd", "Resume": "", "Always assume SD card is present": "\u05ea\u05de\u05d9\u05d3 \u05ea\u05e0\u05d9\u05d7 \u05e9\u05db\u05e8\u05d8\u05d9\u05e1 SD \u05e0\u05de\u05e6\u05d0", "Load and Print": "\u05d8\u05e2\u05df \u05d5\u05d4\u05d3\u05e4\u05e1", "Sending file to SD": "\u05e9\u05d5\u05dc\u05d7 \u05e7\u05d5\u05d1\u05e5 \u05d0\u05dc SD", "Number of Extruders": "\u05de\u05e1\u05e4\u05e8 \u05d0\u05e7\u05e1\u05d8\u05e8\u05d5\u05d3\u05e8\u05d9\u05dd", "black": "\u05e9\u05d7\u05d5\u05e8", "Last Printed": "\u05d4\u05d5\u05d3\u05e4\u05e1 \u05dc\u05d0\u05d7\u05e8\u05d5\u05e0\u05d4", "Sourcecode": "\u05e7\u05d5\u05d3 \u05de\u05e7\u05d5\u05e8", "Estimated layer height": "\u05d2\u05d5\u05d1\u05d4 \u05e9\u05db\u05d1\u05d5\u05ea \u05de\u05e9\u05d5\u05e2\u05e8", "You are now logged out": "\u05d4\u05ea\u05e0\u05ea\u05e7\u05ea \u05de\u05d4\u05de\u05e2\u05e8\u05db\u05ea", "Uploaded": "\u05d4\u05d5\u05e2\u05dc\u05d4", "Form Factor": "", "Opening serial port": "\u05e4\u05d5\u05ea\u05d7 \u05d9\u05e6\u05d9\u05e8\u05d4 \u05d8\u05d5\u05e8\u05d9\u05ea", "New timelapse %(movie_basename)s is done rendering.": "\u05e1\u05d9\u05d9\u05dd \u05dc\u05e8\u05e0\u05d3\u05e8 \u05d0\u05ea \u05d4-timelapse %(movie_basename)s", "Invert control": "\u05d4\u05e4\u05d5\u05da \u05e9\u05dc\u05d9\u05d8\u05d4", "Webcam": "\u05de\u05e6\u05dc\u05de\u05ea \u05e8\u05e9\u05ea", "Select for printing": "", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "\u05d0\u05e4\u05e9\u05e8 <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>", "Remember me": "\u05d6\u05db\u05d5\u05e8 \u05d0\u05d5\u05ea\u05d9", "Enable GCode Visualizer": "\u05d4\u05e4\u05e2\u05dc \u05d5\u05d9\u05d6\u05d5\u05d0\u05dc\u05d9\u05d6\u05e6\u05d9\u05d4 \u05e9\u05dc GCode", "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.": "\u05e0\u05e8\u05d0\u05d4 \u05e9\u05d4\u05e9\u05e8\u05ea \u05dc\u05d0 \u05de\u05d7\u05d5\u05d1\u05e8, \u05d0\u05d5 \u05dc\u05e4\u05d7\u05d5\u05ea \u05d0\u05e0\u05d9 \u05dc\u05d0 \u05de\u05e6\u05dc\u05d9\u05d7 \u05dc\u05e7\u05d1\u05dc \u05db\u05dc \u05ea\u05d2\u05d5\u05d1\u05d4 \u05de\u05de\u05e0\u05d5. \u05d0\u05e0\u05e1\u05d4 \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05d0\u05d5\u05d8\u05d5\u05de\u05d8\u05d9\u05ea <strong>\u05d1\u05e2\u05d5\u05d3 \u05de\u05e1\u05e4\u05e8 \u05d3\u05e7\u05d5\u05ea</strong>, \u05d0\u05d1\u05dc \u05e0\u05d9\u05ea\u05df \u05d2\u05dd \u05dc\u05e0\u05e1\u05d5\u05ea \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05e2\u05dd \u05d4\u05db\u05e4\u05ea\u05d5\u05e8 \u05dc\u05d4\u05dc\u05df.", "Rendering failed": "\u05e8\u05d9\u05e0\u05d3\u05d5\u05e8 \u05e0\u05db\u05e9\u05dc", "Motors off": "\u05db\u05d1\u05d4 \u05de\u05e0\u05d5\u05e2\u05d9\u05dd", "descending": "\u05eLine 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-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\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", "sec": "sec", "Proceed": "Doorgaan", "Timelapse Temp Folder": "Tijdelijke timelapse map", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format", "Upload Folder": "Lokatie voor Uploads", "Only show files stored locally": "Laat alleen lokale bestanden zien", "Add Printer Profile": "", "yellow": "geel", "Save": "Opslaan", "Action": "Actie", "Passwords do not match": "De wachtwoorden komen niet overeen", "Sort by name": "Sorteer op naam", "Save connection settings": "Verbindings instellingen opslaan", "Rendering timelapse": "Renderen van timelapse", "Color": "Kleur", "Temperature": "Temperatuur", "Files": "Bestanden", "Resume": "Ga verder", "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 kaartje", "Number of Extruders": "Aantal Extruders", "black": "zwart", "Last Printed": "Vorige print-job", "Sourcecode": "Broncode", "Estimated layer height": "Geschatte laag hooge", "You are now logged out": "Je bent nu uitgelogd", "Uploaded": "Geupload", "Form Factor": "", "Opening serial port": "Openen van seri\u00eble poort", "New timelapse %(movie_basename)s is done rendering.": "Nieuwe timelapse %(movie_basename)s is gerenderd", "Invert control": "Bedieining spiegelen", "Webcam": "Webcam", "Select for printing": "", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "Sta <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a> toe", "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, althans er komt geen enkele reactie. Ik zal over <strong>een paar minuten</strong> opnieuw pogen te verbinden. Je kunt op elk moment met onderstaande knop 'handmatig' proberen te verbinden", "Rendering failed": "Renderen mislukt", "Motors off": "Motoren uit", "descending": "Aflopend", "Only show files stored on SD": "Laat alleen bestanden op SD-kaart zien", "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", "Slicer": "'Slicer' of fileersoftware", "Nozzle Diameter": "", "Sort by file size": "Sorteer op bestands grootte", "Machine State": "Machine status", "Slicing Profile": "Fileer profiel", "mm": "mm", "API": "API", "Printing from SD": "Printen vanaf SD kaartje", "Stream URL": "Stream URL", "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", "Timelapse bitrate": "Timelapse bitrate", "Confirm Password": "Bevestig wachtwoord", "Disconnect": "Verbreken", "Slicing done": "Fileren is 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": "Het Streamen is klaar", "violet": "violet", "Print": "Print", "Layer count": "Aantal lagen", "OctoPrint Settings": "OctoPrint instellingen", "Are you sure?": "Weet je het zeker?", "blue": "blauw", "Printer": "Printer", "Delete Profile": "", "Tool": "Gereedschap", "Settings": "Instellingen", "Circular": "Cirkelvormig", "Path to FFMPEG": "Lokatie van FFMPEG", "Upload to SD": "opslaan op SD-kaart ", "The command \"%(command)s\" could not be executed.": "Het commando \"%(command)s\" kon niet uitgevoerd worden.", "Select a slicing profile...": "", "Wait for <code>start</code> on connect": "Wacht voor <code>start</code> bij het verbinden", "Sync with job progress": "Synchroniseer met taak voortgang", "Calculating...": "", "Total filament used": "Totaal gebruikte filament", "red": "rood", "Save as default": 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-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\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", "sec": "sek", "Proceed": "Fortsett", "Timelapse Temp Folder": "Timelapse midlertidig mappe", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "St\u00f8tte <code>TargetExtr%%n</code>/<code>TargetBed</code> m\u00e5l temperatur format", "Upload Folder": "Opplastningsmappe", "Only show files stored locally": "Bare vis filer lagret lokalt", "Add Printer Profile": "", "yellow": "gul", "Save": "Lagre", "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", "Color": "Farge", "Temperature": "Temperatur", "Files": "Filer", "Resume": "Fortsett", "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", "Form Factor": "", "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", "Select for printing": "", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "Tillat <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>", "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", "Motors off": "Motorer av", "descending": "synkende", "Only show files stored on SD": "Bare vis filer lagret p\u00e5 minnekortet", "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", "Slicer": "Slicer", "Nozzle Diameter": "", "Sort by file size": "Sorter filer etter st\u00f8rrelse", "Machine State": "Maskintilstand", "Slicing Profile": "Slicer profil", "mm": "mm", "API": "API", "Printing from SD": "Utskrift fra minnekort", "Stream URL": "Str\u00f8m URL", "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", "Timelapse bitrate": "Timelapse bitrate", "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": "Str\u00f8mming ferdig", "violet": "fiolett", "Print": "Utskriv", "Layer count": "Antall lag", "OctoPrint Settings": "OctoPrint innstillinger", "Are you sure?": "Er du sikker?", "blue": "bl\u00e5", "Printer": "Printer", "Delete Profile": "", "Tool": "Verkt\u00f8y", "Settings": "Innstillinger", "Circular": "Sirkul\u00e6r", "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", "Select a slicing profile...": "", "Wait for <code>start</code> on connect": "Vent for <code>start</code> p\u00e5 tilkobling", "Sync with job progress": "Synkroniser med jobbprogresjon", "Calculating...": "", "Total filament used": "Totalt tr\u00e5dforbruk", "red": "r\u00f8d", "Save as default": "Lagre som standard", "SlicingLine truncated
+1 -1
View File
@@ -1 +1 @@
window.BABEL_TO_LOAD_ro = {"locale": "ro", "domain": "messages", "plural_expr": "(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2: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-31 16:21+0000\nLast-Translator: 3Dmaker4U <3dmaker4u@gmail.com>\nLanguage-Team: Romanian (http://www.transifex.com/projects/p/octoprint/language/ro/)\nPlural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2: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": "Timp de imprimare r\u0103mas", "Proceed": "Continuare", "Timelapse Temp Folder": "Director temporar pentru \u00eenregistrarea rapid\u0103", "Title": "Titlu", "Only show files stored locally": "Arat\u0103 doar fi\u0219ierele stocate local", "yellow": "galben", "Path to Cura": "Cale c\u0103tre Cura", "Action": "Ac\u021biune", "Passwords do not match": "Parolele nu se potrivesc", "Sort by name": "Sortare dup\u0103 nume", "Save connection settings": "Salvare configura\u021bie conexiune", "Rendering timelapse": "Redare \u00eenregistrare rapid\u0103", "Cura": "Cura", "Files": "Fi\u0219iere", "Bed Size": "M\u0103rime mas\u0103", "Always assume SD card is present": "Consider\u0103 \u00eentotdeauna cardul SD prezent", "Load and Print": "\u00cenc\u0103rcare \u0219i imprimare", "Sending file to SD": "Se transmite fi\u0219ierul c\u0103tre SD", "Number of Extruders": "Num\u0103r de extrudere", "black": "negru", "Last Printed": "Ultima dat\u0103 imprimat", "Sourcecode": "Cod surs\u0103", "Estimated layer height": "\u00cen\u0103l\u021bimea stratului estimat\u0103", "You are now logged out": "Acum e\u0219ti deconectat", "Uploaded": "\u00cenc\u0103rcat", "Opening serial port": "Se deschide portul serial", "New timelapse %(movie_basename)s is done rendering.": "Redarea noii \u00eenregistr\u0103ri rapide %(movie_basename)s s-a terminat.", "Invert control": "Inversare comand\u0103", "Webcam": "Webcam", "Remember me": "\u021aine-m\u0103 minte", "Enable GCode Visualizer": "Activeaz\u0103 vizualizarea GCode", "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.": "Se pare c\u0103 serverul nu este connectat sau, cel pu\u021bin, mie nu-mi r\u0103spunde. Voi \u00eencerca s\u0103 m\u0103 reconectez automat <strong>\u00een urm\u0103toarele dou\u0103 minute</strong>, dar po\u021bi \u00eencerca oric\u00e2nd s\u0103 te reconectezi manual utiliz\u00e2nd butonul de mai jos.", "Rendering failed": "Redarea a e\u0219uat", "Upload Folder": "\u00cencarc\u0103 director", "descending": "descresc\u0103tor", "X": "X", "Add user": "Ad\u0103ugare utilizator", "GCODE commands in layer": "comenzi GCODE \u00een strat", "Estimated print time": "Timp de imprimare estimat", "Serial Connection": "Conexiune serial\u0103", "Control": "Control", "Password": "Parol\u0103", "Also show next layer": "Vizualizare strat urm\u0103tor", "Print Time": "Timp de imprimare", "Sort by file size": "Sortare dup\u0103 m\u0103rimea fi\u0219ierului", "Machine State": "Starea ma\u0219inii", "default": "implicit", "API": "API", "Printing from SD": "Se imprim\u0103 de pe SD", "Terminal filters": "Filtre pentru terminal", "Change password for user \"%(user)s\"": "Modificare parol\u0103 pentru utilizatorul \"%(user)s\"", "Enable Temperature Graph": "Activeaz\u0103 graficul temperaturii", "Delete user": "\u0218tergere utilizator", "Confirm Password": "Confirmare parol\u0103", "Disconnect": "Deconectare", "Slicing done": "Feliere terminat\u0103", "Initialize SD card": "Ini\u021bializare card SD", "System": "Sistem", "Send": "Trimitere", "State": "Stare", "Version": "Versiune", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH.mm", "Attempt to reconnect": "\u00cencercare de reconectare", "Streaming done": "Transmiterea s-a terminat", "violet": "violet", "Print": "Imprimare", "Layer count": "Num\u0103r de straturi", "OctoPrint Settings": "Configurare OctoPrint", "Are you sure?": "E\u0219ti sigur?", "blue": "albastru", "Printer": "Imprimant\u0103", "Tool": "Unealt\u0103", "Settings": "Configura\u021bii", "Path to FFMPEG": "Cale c\u0103tre FFMPEG", "Upload to SD": "\u00cenc\u0103rcare pe SD", "The command \"%(command)s\" could not be executed.": "Comanda \"%(command)s\" nu a putut fi executat\u0103.", "Printed": "Imprimat", "Layer number": "Num\u0103rul stratului", "Sync with job progress": "Sincronizare cu stadiul lucr\u0103rii", "Circular": "Circular", "Total filament used": "Filament utilizat \u00een total", "red": "ro\u0219u", "Save as default": "Salvare ca valori implicite", "Slicing ...": "Se feliaz\u0103...", "Last Print Time": "Ultima imprimare a durat", "Target": "\u021aint\u0103", "Streaming ...": "Se transmite...", "Logout successful": "DecoLine truncated
window.BABEL_TO_LOAD_ro = {"locale": "ro", "domain": "messages", "plural_expr": "(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1))", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: Romanian (http://www.transifex.com/projects/p/octoprint/language/ro/)\nPlural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2: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": "Timp de imprimare r\u0103mas", "sec": "sec", "Proceed": "Continuare", "Timelapse Temp Folder": "Director temporar pentru \u00eenregistrarea rapid\u0103", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "Sus\u021bine formatul <code>TargetExtr%%n</code>/<code>TargetBed</code> pentru temperatura \u021bint\u0103", "Upload Folder": "\u00cencarc\u0103 director", "Only show files stored locally": "Arat\u0103 doar fi\u0219ierele stocate local", "Add Printer Profile": "", "yellow": "galben", "Save": "Salvare", "Action": "Ac\u021biune", "Passwords do not match": "Parolele nu se potrivesc", "Sort by name": "Sortare dup\u0103 nume", "Save connection settings": "Salvare configura\u021bie conexiune", "Rendering timelapse": "Redare \u00eenregistrare rapid\u0103", "Color": "Culoare", "Temperature": "Temperatur\u0103", "Files": "Fi\u0219iere", "Resume": "", "Always assume SD card is present": "Consider\u0103 \u00eentotdeauna cardul SD prezent", "Load and Print": "\u00cenc\u0103rcare \u0219i imprimare", "Sending file to SD": "Se transmite fi\u0219ierul c\u0103tre SD", "Number of Extruders": "Num\u0103r de extrudere", "black": "negru", "Last Printed": "Ultima dat\u0103 imprimat", "Sourcecode": "Cod surs\u0103", "Estimated layer height": "\u00cen\u0103l\u021bimea stratului estimat\u0103", "You are now logged out": "Acum e\u0219ti deconectat", "Uploaded": "\u00cenc\u0103rcat", "Form Factor": "", "Opening serial port": "Se deschide portul serial", "New timelapse %(movie_basename)s is done rendering.": "Redarea noii \u00eenregistr\u0103ri rapide %(movie_basename)s s-a terminat.", "Invert control": "Inversare comand\u0103", "Webcam": "Webcam", "Select for printing": "", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "Permite <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>", "Remember me": "\u021aine-m\u0103 minte", "Enable GCode Visualizer": "Activeaz\u0103 vizualizarea GCode", "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.": "Se pare c\u0103 serverul nu este connectat sau, cel pu\u021bin, mie nu-mi r\u0103spunde. Voi \u00eencerca s\u0103 m\u0103 reconectez automat <strong>\u00een urm\u0103toarele dou\u0103 minute</strong>, dar po\u021bi \u00eencerca oric\u00e2nd s\u0103 te reconectezi manual utiliz\u00e2nd butonul de mai jos.", "Rendering failed": "Redarea a e\u0219uat", "Motors off": "Oprire motoare", "descending": "descresc\u0103tor", "Only show files stored on SD": "Arat\u0103 doar fi\u0219ierele stocate pe SD", "X": "X", "Add user": "Ad\u0103ugare utilizator", "GCODE commands in layer": "comenzi GCODE \u00een strat", "Estimated print time": "Timp de imprimare estimat", "Serial Connection": "Conexiune serial\u0103", "Control": "Control", "Password": "Parol\u0103", "Also show next layer": "Vizualizare strat urm\u0103tor", "Print Time": "Timp de imprimare", "Slicer": "", "Nozzle Diameter": "", "Sort by file size": "Sortare dup\u0103 m\u0103rimea fi\u0219ierului", "Machine State": "Starea ma\u0219inii", "Slicing Profile": "", "mm": "mm", "API": "API", "Printing from SD": "Se imprim\u0103 de pe SD", "Stream URL": "URL flux video", "Terminal filters": "Filtre pentru terminal", "Change password for user \"%(user)s\"": "Modificare parol\u0103 pentru utilizatorul \"%(user)s\"", "Enable Temperature Graph": "Activeaz\u0103 graficul temperaturii", "Delete user": "\u0218tergere utilizator", "Timelapse bitrate": "Vitez\u0103 \u00eenregistrare rapid\u0103", "Confirm Password": "Confirmare parol\u0103", "Disconnect": "Deconectare", "Slicing done": "Feliere terminat\u0103", "Initialize SD card": "Ini\u021bializare card SD", "System": "Sistem", "Send": "Trimitere", "State": "Stare", "Version": "Versiune", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH.mm", "Attempt to reconnect": "\u00cencercare de reconectare", "Streaming done": "Transmiterea s-a terminat", "violet": "violet", "Print": "Imprimare", "Layer count": "Num\u0103r de straturi", "OctoPrint Settings": "Configurare OctoPrint", "Are you sure?": "E\u0219ti sigur?", "blue": "albastru", "Printer": "Imprimant\u0103", "Delete Profile": "", "Tool": "Unealt\u0103", Line 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>
+80 -12
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;
@@ -37,12 +59,15 @@
var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold }};
var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold }};
var SOCKJS_URI = window.location.protocol.slice(0, -1) + "://" + (window.document ? window.document.domain : window.location.hostname) + ":" + window.location.port + BASEURL + "sockjs";
var SOCKJS_URI = "{{ url_for('index') }}" + "sockjs";
var SOCKJS_DEBUG = {% if debug -%} true; {% else %} false; {%- endif %}
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">
@@ -100,7 +125,7 @@
<div class="accordion span4">
<div class="accordion-group" data-bind="visible: loginState.isUser" id="connection_accordion">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" href="#connection"><i class="icon-signal"></i> {{ _('Connection') }}</a>
<a class="accordion-toggle" data-toggle="collapse" data-target="#connection"><i class="icon-signal"></i> {{ _('Connection') }}</a>
</div>
<div class="accordion-body collapse in" id="connection">
<div class="accordion-inner">
@@ -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>
+203 -124
View File
@@ -8,19 +8,26 @@
<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 +106,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">
@@ -286,7 +367,7 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_alwaysSendChecksum" id="settings-featureAlwaysSendChecksum"> {{ _('Send a checksum with <strong>every</strong> command') }} <span class="label">{{ _('Repetier') }}</span>
<input type="checkbox" data-bind="checked: feature_alwaysSendChecksum" id="settings-featureAlwaysSendChecksum"> {{ _('Send a checksum with <strong>every</strong> command (reconnect after changing)') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
@@ -414,30 +495,8 @@
</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 +514,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 +667,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 +694,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>
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff. Show more