Compare commits

...
Author SHA1 Message Date
Gina Häußge 920d56b824 📝 Fix formatting 2022-11-03 12:02:31 +01:00
Gina Häußge fdafd098df 🐛 Remove debug output 2021-12-16 17:50:58 +01:00
Gina Häußge 0c1c6880c9 🐛 Fix disabling if no choices 2021-12-16 17:49:33 +01:00
Gina Häußge 1c05cd2304 🚧 Work on connection parameters vs. available ports 2021-12-16 17:44:04 +01:00
Gina Häußge fe1bd0131b 🐛 Fix connection refreshing 2021-12-15 16:42:07 +01:00
Gina Häußge 4135bb615c 🚧 ports are choice after all
Suggestion doesn't work, at least not in the
connect dialog.

Find another approach for offline preconfiguration.
2021-12-13 15:52:44 +01:00
Gina Häußge 116e6e7190 Merge branch 'devel' into dev/commRefactoringNG 2021-12-08 13:26:02 +01:00
Gina Häußge fdcf02c1ad Merge branch 'devel' into dev/commRefactoringNG 2021-12-06 17:14:27 +01:00
Gina Häußge cb47151646 Merge branch 'devel' into dev/commRefactoringNG 2021-12-06 16:54:48 +01:00
Gina Häußge 4699412f7b 🚧 Combo box experiments 2021-07-26 11:37:15 +02:00
Gina Häußge dcd1d4b749 🐛 Fix a refactoring issue 2021-07-26 11:36:41 +02:00
Gina Häußge 65324c6796 ♻️ Parameter templates are now generic 2021-07-20 12:17:28 +02:00
Gina Häußge d442d5a7bf 🐛 Fix styling of protocol/transport settings
Also update TODOs
2021-07-19 14:21:58 +02:00
Gina Häußge 6873cff462 ♻️ Move settings migrations into their own module 2021-07-16 16:05:12 +02:00
Gina Häußge e77f5b7385 ✨ Protocol & Transport settings dialog 2021-07-16 16:02:14 +02:00
Shawn Bruce bd443e2efc Use to_unicode instead of decode 2021-07-15 17:48:22 +02:00
Shawn Bruce 67c8ff4b66 Rename PTYVirtualPrinterWrapper to FileVirtualPrinterWrapper 2021-07-15 17:48:22 +02:00
Shawn Bruce 507bf89d73 Handle ImportError for unix specific imports. Only provide pty_command if import succeeds 2021-07-15 17:48:22 +02:00
Shawn Bruce 7e23356add Use with 2021-07-15 17:48:22 +02:00
Shawn Bruce e82f4551f3 Mutex not actually needed 2021-07-15 17:48:22 +02:00
Shawn Bruce 3c5c4ff385 - VirtualPrinterWrapper: Use mutex for read/write
- VirtualPrinterWrapper: Remove socket specific code
- VirtualPrinterWrapper: Decode received data when printing to console
- SocketVirtualPrinterWrapper: Return empty bytes instead of raising an exception
- all commands: Standardize options, add defaults
- uds_command: Fix UDS exception
- uds_command: Define default socket path
- uds_command: Remove addr from print statement. Not provided by socket
w/ Unix Sockets
- uds_command: Add basic checks before creating the socket
- Implement virtual printer over PTY
- Implement virtual printer over Serial
2021-07-15 17:48:22 +02:00
Gina Häußge 6942ddebc2 ♻️ Refactor connection API & view models
Big party here! 🥳
2021-07-14 17:38:16 +02:00
Gina Häußge d50c738a2d Merge branch 'devel' into dev/commRefactoringNG 2021-07-13 17:09:11 +02:00
Gina Häußge 334fb7453e Merge branch 'devel' into dev/commRefactoringNG 2021-07-13 15:55:29 +02:00
Gina Häußge 9f2a6cf6e0 🚧 Further progress on connection profile editing 2021-07-13 15:36:46 +02:00
Gina Häußge 5421c1bfe3 🐛 Fix connection profile editor save button 2021-07-09 18:51:13 +02:00
Gina Häußge b55a256419 🐛 Fix a buggy leftover from a refactoring 2021-07-09 18:48:19 +02:00
Gina Häußge 2fd886f413 🚧 Connection profile editor 2021-07-09 17:48:51 +02:00
Gina Häußge 030886e549 Merge branch 'devel' into dev/commRefactoringNG 2021-07-02 17:15:08 +02:00
Gina Häußge 20ca1018bd Merge branch 'devel' into dev/commRefactoringNG 2021-07-02 16:35:55 +02:00
Gina Häußge 8ff0eab24e 🚧 virtual: Better error handling & identifier 2021-07-02 16:16:49 +02:00
Gina Häußge 11047940bc 🐛 Further debugging
Disconnect handling, print time left calculation, and so on
2021-07-02 16:02:13 +02:00
Gina Häußge a707bfdee4 🚧 Timeouts & error handling on sockets
Also fix PushingTransportWrapper for SocketTransport
2021-07-01 19:45:58 +02:00
Gina Häußge c2d1e279ae 🐛 script.name => script 2021-07-01 19:43:19 +02:00
Gina Häußge 7f8cc5601b 🔥 Deactivating namedpipe stuff
This is not yet working and we'll concentrate on TCP and maybe
UDS for now.
2021-07-01 14:35:17 +02:00
Gina Häußge e0d874059d 🚧 virtual_printer: TCP, UDS, NamedPipe CLI
That way we can spawn the printer as a server and test the related
transports more easily.

TODO:
  * Test UDS
  * Fix NamedPipe stuff, currently connection doesn't work
2021-06-30 19:04:31 +02:00
Gina Häußge 34f94a043d ✨ UnixDomainSocket and Named Pipe transports 2021-06-30 19:01:16 +02:00
Gina Häußge 786203b7ac 🚧 WIP: Fixing/implementing things left and right 2021-06-10 16:51:54 +02:00
Gina Häußge c2cec4e11c ♻️ Some refactoring
And also some bug fixes
2021-06-09 16:08:27 +02:00
Gina Häußge b5a7586926 ✨ Implement serial port auto detection 2021-06-08 21:35:51 +02:00
Gina Häußge 7ffa3595db 🔊 Improved autoconnect logging 2021-06-01 22:35:10 +02:00
Gina Häußge 47e25d54cd 🐛 Implement auto connect on startup
If configured as such, OctoPrint will attempt to auto connect to the
default profile on startup.
2021-06-01 22:30:39 +02:00
Gina Häußge 3196f0b445 📝 Some TODOs are taken care of :) 2021-06-01 21:10:42 +02:00
Gina Häußge d478a0c4bb 🐛 More fixing of param processing 2021-06-01 21:04:26 +02:00
Gina Häußge d98f7a2dcb 🐛 Fix display of last connection params 2021-06-01 17:48:54 +02:00
Gina Häußge 56033f56a0 🐛 More wrangling with the frontend 2021-06-01 16:09:14 +02:00
Gina Häußge d62c97081c ✨ Add support for USB serialno & location matching 2021-05-31 19:49:03 +02:00
Gina Häußge ca6deb07d8 🐛 Fix class name of klipper flavor 2021-05-21 22:13:40 +02:00
Gina Häußge 92221b3996 🐛 Fix loading of connection profile w/ conditionalgroup 2021-05-21 22:12:56 +02:00
Gina Häußge 20ed3d10ab 🐛 Some cosmetic fixes 2021-05-21 14:48:31 +02:00
Gina Häußge 64ac824fb8 🐛 Only try to send script if already connected 2021-05-21 14:47:58 +02:00
Gina Häußge 995d3572fc 🐛 Fix conditionalgroup handling 2021-05-21 14:46:46 +02:00
Gina Häußge c78c2641dd 🔀 Reimplement maintenance changes 2021-05-21 14:31:53 +02:00
Gina Häußge 04391495e7 Merge branch 'devel' into dev/commRefactoringNG 2021-05-20 17:12:41 +02:00
Gina Häußge 77af2bd81f Merge branch 'devel' into dev/commRefactoringNG 2021-04-19 18:07:20 +02:00
Gina Häußge d197fabffc Merge branch 'devel' into dev/commRefactoringNG 2021-04-19 18:01:30 +02:00
Gina Häußge 35c3acf610 🚧 WIP: adding new conditionalgroup parameter type
Needs to be wired up to frontend. Supposed to be used to distinguish
between connect via port/usbid/url for SerialTransport. Should make
save&connect and autoconnect easier.
2021-03-17 17:59:33 +01:00
Gina Häußge 236cb56b49 🐛 Fix firmware info & caps propagation 2021-03-17 15:29:21 +01:00
Gina Häußge 875fb72fec 🐛 Fix virtual printer & settings 2021-03-17 15:28:42 +01:00
Gina Häußge 306d4f2942 🎨 pre-commit with new settings 2021-03-17 15:11:54 +01:00
Gina Häußge 741fac4396 Merge branch 'devel' into dev/commRefactoringNG 2021-03-16 15:26:42 +01:00
Gina Häußge 95201882e6 🎨 logger.warn => logger.warning 2021-02-26 13:34:57 +01:00
Gina Häußge bea7f34887 🎨 Get rid of py2 leftovers 2021-02-25 15:21:50 +01:00
Gina Häußge 11e30150b7 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/static/css/octoprint.css
2021-02-25 14:48:18 +01:00
Gina Häußge c0232c1551 🚧 Display vid/uid on USB ports 2021-02-19 17:41:26 +01:00
Gina Häußge 566e214ee4 🚧 ports/baudrates can now be overridden
Connection settings (exact port & baudrate to use) and overall serial
options (which ports and baudrates to offer) are now separated.
2021-02-19 14:02:53 +01:00
Gina Häußge ecd2bf81e3 🐛 Fix type conversion of connection options 2021-02-17 17:14:14 +01:00
Gina Häußge 2703cbc474 ✨ comm: configurable ok_buffer_size 2021-02-17 17:13:44 +01:00
Gina Häußge 777f6ed610 🎨 Reorder gcode handlers & add some dividers 2021-02-12 19:02:33 +01:00
Gina Häußge 8c25c88a20 🔥 Remove left-over part from an experiment 2021-02-12 18:53:28 +01:00
Gina Häußge 6a39f84f16 🔥 No more connection options on printers 2021-02-12 18:47:39 +01:00
Gina Häußge e60c8db43b 🚧 Refactoring and implementation continues...
* gcode handlers moved into flavor
  * StandardFlavor instead of GenericFlavor
  * InternalState class instead of _internal_flags dict
2021-02-12 18:39:39 +01:00
Gina Häußge 14ed49a5dd ♻️ Refactor to use flavor instances 2021-02-12 13:50:07 +01:00
Gina Häußge 37c439ca8c 🚧 Further work on various things 2021-02-11 16:46:37 +01:00
Gina Häußge 98860ece7f ♻️ Remove some Py2 stuff 2021-02-10 17:52:35 +01:00
Gina Häußge 6a9415b39f 🐛 Fix merge & migration errors
At least the virtual printer is working again \o/
2021-02-10 17:39:27 +01:00
Gina Häußge 65706d4171 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	THIRDPARTYLICENSES.md
#	src/octoprint/__init__.py
#	src/octoprint/filemanager/__init__.py
#	src/octoprint/filemanager/storage/local.py
#	src/octoprint/logging/handlers.py
#	src/octoprint/plugin/__init__.py
#	src/octoprint/plugins/virtual_printer/__init__.py
#	src/octoprint/plugins/virtual_printer/virtual.py
#	src/octoprint/printer/__init__.py
#	src/octoprint/printer/estimation.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/__init__.py
#	src/octoprint/server/api/connection.py
#	src/octoprint/server/api/files.py
#	src/octoprint/server/api/settings.py
#	src/octoprint/server/util/flask.py
#	src/octoprint/server/views.py
#	src/octoprint/settings.py
#	src/octoprint/static/css/octoprint.css
#	src/octoprint/static/js/app/viewmodels/connection.js
#	src/octoprint/static/js/app/viewmodels/settings.js
#	src/octoprint/static/less/octoprint.less
#	src/octoprint/templates/dialogs/settings/serialconnection.jinja2
#	src/octoprint/templates/index.jinja2
#	src/octoprint/templates/sidebar/connection.jinja2
#	src/octoprint/timelapse.py
#	src/octoprint/util/__init__.py
#	tests/filemanager/test_filemanager.py
#	tests/plugin/test_settings.py
2021-02-10 16:59:45 +01:00
Gina Häußge 369c643ed8 🚧 WIP of serial settings migration, part 2 2019-09-23 10:12:13 +02:00
Gina Häußge 6c75ff6c98 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css
#	src/octoprint/printer/standard.py
#	src/octoprint/templates/dialogs/settings/serialconnection.jinja2
#	translations/de/LC_MESSAGES/messages.po
#	translations/messages.pot
2019-09-20 16:13:07 +02:00
Gina Häußge 788a1f0a13 🚧 WIP of serial settings migration 2019-09-20 16:11:07 +02:00
Gina Häußge 8302253f84 🚧 port over feedback controls 2019-09-20 13:10:23 +02:00
Gina Häußge 932ede865b 🚧 connection.log toggling 2019-09-19 21:47:54 +02:00
Gina Häußge e1d6a14df6 🚧 Disable defaults button when connection active 2019-09-19 13:14:07 +02:00
Gina Häußge d796d34a8a 🐛 Fix a key error 2019-09-19 13:08:56 +02:00
Gina Häußge dc519e0aff 🚧 Fix another bug 2019-08-02 16:15:49 +02:00
Gina Häußge c4978db302 🚧 Implement temperature offset feature 2019-08-02 16:05:32 +02:00
Gina Häußge 70540ff51b 🚧 Fix a bug, more tests 2019-08-01 14:16:58 +02:00
Gina Häußge 3eb572ede5 🚧 First unit tests 2019-08-01 13:12:59 +02:00
Gina Häußge f5e56b4d4a 🚧 Capability support flags 2019-08-01 13:12:32 +02:00
Gina Häußge 0612fe4e36 🚧 Wait for disconnect until all's been processed 2019-08-01 13:12:15 +02:00
Gina Häußge 16cff1a098 🚧 Error handling works now 2019-07-30 15:57:36 +02:00
Gina Häußge dd6ca9d351 🚧 WIP: Start on testing infrastructure 2019-07-26 17:22:28 +02:00
Gina Häußge 732c510b98 🚧 Various hook implementations 2019-07-26 17:22:15 +02:00
Gina Häußge 9aea8ed218 🚧 Fix job estimator handling 2019-07-25 15:12:07 +02:00
Gina Häußge 4c66ece044 🚧 script hook & fix multiple job commands 2019-07-25 14:50:06 +02:00
Gina Häußge 62298c55b8 🚧 Remove redundancy for trigger_ok_after_resend 2019-07-24 17:04:12 +02:00
Gina Häußge 7c51fbda1b 🚧 Fix consecutive timeout tracking 2019-07-24 16:09:37 +02:00
Gina Häußge e4afae66a3 🚧 Fix trigger_ok_after_resend flag 2019-07-24 15:41:09 +02:00
Gina Häußge 8d10eff9df 🚧 More work towards feature completion 2019-07-22 13:06:55 +02:00
Gina Häußge 4b028562d8 🚧 Expert parameters 2019-07-18 15:16:01 +02:00
Gina Häußge 395dce457d 🚧 Apply overrides from connection profiles 2019-07-17 15:47:49 +02:00
Gina Häußge 2bf7eceb8e 🚧 Flavor override dialog finally works 2019-07-16 16:17:23 +02:00
Gina Häußge 67047c006c 🚨 Start to flesh out connection parameters 2019-06-06 16:43:06 +02:00
Gina Häußge 2d872baaec 🚧 connection profiles now load properly 2019-06-06 15:50:48 +02:00
Gina Häußge a412ff42cb 🚧 WIP: More work on the connection profiles 2019-05-31 17:53:45 +02:00
Gina Häußge 06cd4ead8d 🚧 Support adding & updating connection profiles 2019-05-24 17:18:35 +02:00
Gina Häußge 13995e30b7 🚧 Introduce connection profiles 2019-05-24 16:30:22 +02:00
Gina Häußge 0d6d0f7256 🐛 Fix protocol/transport selection 2019-05-22 16:12:23 +02:00
Gina Häußge 1e8cb55be9 🐛 Fix script processing 2019-05-17 12:04:45 +02:00
Gina Häußge e63161ae17 ✨ Reset line numbers before all jobs 2019-05-16 17:40:12 +02:00
Gina Häußge f41dc58d97 ✨ Port part_of_job tracking & fix some bugs 2019-05-16 17:04:01 +02:00
Gina Häußge 522abbddbe ✨ Port various bits from old comm layer 2019-05-16 15:24:53 +02:00
Gina Häußge fecc162b5d ✨ Add "starting" state 2019-05-16 11:31:00 +02:00
Gina Häußge accb222a92 ✨ Support autodetection of klipper 2019-05-16 11:30:32 +02:00
Gina Häußge 0768e3e72b Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/plugins/virtual_printer/virtual.py
#	src/octoprint/printer/standard.py
2019-05-16 11:30:11 +02:00
Gina Häußge 961b41f0fe 🐛 Fix action commands & various other things 2019-03-08 20:02:51 +01:00
Gina Häußge 4f59e0fd48 🐛 Fix resumed script 2019-03-08 16:32:21 +01:00
Gina Häußge e441976682 🐛 Fix sending of cancel, pause, resume scripts 2019-03-08 14:32:20 +01:00
Gina Häußge 864ac12097 🐛 Fix time reporting & user logging 2019-03-08 10:59:58 +01:00
Gina Häußge ee854f44cc ♻ Make some protocol flags dynamic
Less risk of forgetting to adjust them on some randomg state change.

Fixes issues with pausing/resuming/finishing.
2019-03-07 12:48:06 +01:00
Gina Häußge cc5c19dde9 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/filemanager/storage/local.py
2019-03-06 15:12:27 +01:00
Gina Häußge f36a6a0409 🐛 Fix missing error field on protocol 2019-03-01 18:09:28 +01:00
Gina Häußge de8be65be7 🚧 WIP: user action logging, continued 2019-03-01 18:09:13 +01:00
Gina Häußge 780948fe7d 🐛 Fix ok_timeout detection under Py2 as well
d291734 only fixed it for Py3 🤦‍♀️
2019-03-01 16:24:32 +01:00
Gina Häußge c27936a9db 🐛 Fix print logging 2019-03-01 15:31:36 +01:00
Gina Häußge caad7a3f60 🐛 tracking: Use correct payload roperty for elapsed time 2019-03-01 13:16:11 +01:00
Gina Häußge 7c75c882d3 ♻ Put time into job event payload 2019-03-01 13:15:45 +01:00
Gina Häußge 9594b75b78 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/plugins/tracking/__init__.py
2019-03-01 11:29:14 +01:00
Gina Häußge 9eafe9979a 🚧 WIP: user action logging 2019-02-22 19:25:02 +01:00
Gina Häußge 086a2c9f82 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/plugins/virtual_printer/virtual.py
2019-02-22 18:48:10 +01:00
Gina Häußge 0c58566789 🐛 Fix on_protocol_job_resumed call 2019-02-22 17:51:34 +01:00
Gina Häußge d2917346f5 🐛 Fix ok_timeout detection 2019-02-22 17:50:43 +01:00
Gina Häußge e7f1302f3c 🐛 Fix pausing -> paused
Was not waiting for scripts and such to complete before the state
change.
2019-02-22 15:23:28 +01:00
Gina Häußge eca74233eb 🐛 Fix resume 2019-02-22 14:47:31 +01:00
Gina Häußge 36fb7805e5 🐛 Fix type error in case of a resend 2019-02-22 11:33:45 +01:00
Gina Häußge c7afd7951c 💚 Fix tests (final pass) 2019-02-21 16:58:44 +01:00
Gina Häußge f489f4ffd1 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	.travis.yml
#	src/octoprint/util/__init__.py
2019-02-21 15:44:27 +01:00
Gina Häußge ba96ba8fe8 🚧 WIP: Fixing tests, part 3 2019-02-21 15:29:41 +01:00
Gina Häußge 02566ae9d0 👷 ALLOW_UNICODE and custom pretty printer in doctests
We could also have set ALLOW_UNICODE globally, but this way we might
catch situations where we definitely do not expect mixed results between
py2 and py3.
2019-02-21 15:29:20 +01:00
Gina Häußge 8080e65366 Merge branch 'devel' into dev/commRefactoringNG 2019-02-21 11:52:11 +01:00
Gina Häußge 4c76225c41 🚧 WIP: Fixing tests, part 2 2019-02-15 18:54:07 +01:00
Gina Häußge 1f4bfa854b 👷 Switching from nose to pytest 2019-02-15 18:52:44 +01:00
Gina Häußge 4be18c2668 🚧 WIP: Fixing tests 2019-02-15 12:56:57 +01:00
Gina Häußge 225cca34e1 🔥 Remove old test code 2019-02-14 17:29:42 +01:00
Gina Häußge 9a4149164b ♻ Some porting from maintenance/devel 2019-02-14 17:29:02 +01:00
Gina Häußge cf9243c2e7 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/filemanager/storage/local.py
#	src/octoprint/logging/handlers.py
#	src/octoprint/plugin/__init__.py
#	src/octoprint/plugins/virtual_printer/virtual.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/connection.py
#	src/octoprint/server/api/files.py
#	src/octoprint/settings.py
#	src/octoprint/static/js/app/viewmodels/connection.js
#	src/octoprint/util/__init__.py
#	tests/plugin/test_settings.py
2019-02-14 17:27:00 +01:00
Gina Häußge 8eba3fef0a Add disconnect handling
Had to refactor quite some bits to be able to implement this.
2018-07-05 17:36:43 +02:00
Gina Häußge e93d2104fd Add last temperature to script context & event on M112 2018-07-05 12:22:53 +02:00
Gina Häußge a7aa58e524 Add printer profile, use where needed 2018-07-05 12:17:10 +02:00
Gina Häußge c442906379 Resolve a dwelling TODO 2018-07-05 11:25:38 +02:00
Gina Häußge bb0b01aa01 Add resend_ok_timer to work around broken resends 2018-07-04 17:52:25 +02:00
Gina Häußge 3173783620 Join connection dialog with new comm layer 2018-06-29 20:55:54 +02:00
Gina Häußge 5d0cb14f71 Fix Print Time/Printed tracking for successfully completed jobs
We want this data to stick around after the print job ended, just like
it does now
2018-06-28 15:31:04 +02:00
Gina Häußge 60d84b7d06 Make SD prints work again
#mswa
2018-06-27 17:37:56 +02:00
Gina Häußge 93d77e6b25 Fix missing event field 2018-06-26 16:30:48 +02:00
Gina Häußge fd13b18ef7 Remove parsing limitation on sd file streaming 2018-06-26 13:28:05 +02:00
Gina Häußge acd05cdcc5 Limit parsing to comm when streaming to SD 2018-06-14 19:16:25 +02:00
Gina Häußge 1a67b5b3fc Upload to SD is now working 2018-06-14 18:54:40 +02:00
Gina Häußge 473d4a752a Fix message parsing again 2018-06-14 12:58:10 +02:00
Gina Häußge 33a5e389fd Fix line pushing 2018-06-13 17:35:16 +02:00
Gina Häußge 287a13b944 Reset handling 2018-06-12 16:28:22 +02:00
Gina Häußge 5282db6871 Implement job_on_hold functionality 2018-06-12 15:57:46 +02:00
Gina Häußge b79618d752 Disable heatup detection when auto reporting 2018-06-12 13:54:35 +02:00
Gina Häußge 391930e2cb Fix reported state id 2018-06-12 13:48:12 +02:00
Gina Häußge 4630cc8ee0 Fix restart button 2018-06-12 13:47:52 +02:00
Gina Häußge 4e83466af3 Fix temperature polling 2018-06-12 13:29:29 +02:00
Gina Häußge b7e08c7ddc Fix pausing 2018-06-12 13:29:19 +02:00
Gina Häußge 701208484a WIP first throw at scripts
Currently broken:
  * temperature and position logging in context
  * pausing and cancelling
2018-06-07 17:49:35 +02:00
Gina Häußge 02252d1254 finishing state 2018-06-07 14:29:42 +02:00
Gina Häußge 8347f182ef queue markers, pausing, cancelling 2018-06-07 14:16:47 +02:00
Gina Häußge 7e4faa20b7 Fix temperature access 2018-06-06 15:12:27 +02:00
Gina Häußge 717eef25da Fix wrong (1%) progress on print finish 2018-06-06 13:06:39 +02:00
Gina Häußge 31fbebdbb9 Basic action commands are working 2018-06-05 17:39:04 +02:00
Gina Häußge afe224ae08 Fix resend request handling
Resends didn't use up oks due to a missing to_command during enqueuing.
2018-06-05 16:54:52 +02:00
Gina Häußge d09f75a815 Add commdebug logger
To help with debugging ping pong communication
2018-06-05 16:54:01 +02:00
Gina Häußge 812ce40e35 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/logging/handlers.py
#	src/octoprint/printer/standard.py
2018-06-05 13:22:15 +02:00
Gina Häußge 66cad78c41 WIP: busy proto, dwelling, ok timeout 2018-05-31 17:42:52 +02:00
Gina Häußge 4e91f47e8b Add protocol state to handler calls 2018-05-31 15:15:32 +02:00
Gina Häußge 4b753d03dc internal_state => internal_flags 2018-05-31 10:59:17 +02:00
Gina Häußge 6f18749df1 time.time => monotonic_time 2018-05-31 10:44:30 +02:00
Gina Häußge eab0ce8aee Add firmware & capability reporting, temp autoreports
Also refactored flavors to make adding additional ones (e.g. from
plugins) even easier.
2018-05-31 10:19:15 +02:00
Gina Häußge ba00b4d675 Fix bug in GcodeCommand constructor 2018-05-30 19:12:30 +02:00
Gina Häußge 9bc8638d80 Fix resend handling 2018-05-30 14:32:46 +02:00
Gina Häußge d9c8351025 WIP: tags, print time estimation, gcode parsing 2018-05-24 18:52:19 +02:00
Gina Häußge 73a16f6075 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/printer/standard.py
2018-05-24 10:53:56 +02:00
Gina Häußge 4967d19b6a WIP: Add tags & atcommands 2018-05-23 18:45:00 +02:00
Gina Häußge 4b64fb7f47 Corrected some merge issues 2018-05-09 14:05:25 +02:00
Gina Häußge 7e11104b9c Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	src/octoprint/__init__.py
#	src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css
#	src/octoprint/printer/__init__.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/files.py
#	src/octoprint/util/__init__.py
2018-05-08 15:57:05 +02:00
Gina Häußge 81efd3251c Merge branch 'devel' into dev/commRefactoringNG 2017-06-14 11:27:22 +02:00
Gina Häußge f21a1093f3 Eval message integrity for checksumming 2017-05-02 09:21:53 +02:00
Gina Häußge 72318fa696 Fix comment stripping 2017-05-02 09:21:19 +02:00
Gina Häußge babc581c5d More migrations from stable comm layer to new layer
Also fixed:
  * comment stripping
  * resends (? maybe ?)
  * transport error detection
2017-04-21 23:05:58 +02:00
Gina Häußge c28fb4164b Transport registry, events and various fixes
Broken:

  * print time estimation
  * comment stripping (not stripping totally empty lines)
  * resend handling (837, 838, 833 - boom)
  * job pause/resume events?
  * possibly more
2017-04-20 17:18:36 +02:00
Gina Häußge a6db08992f Fixed some merge errors & temperature reporting 2017-04-20 15:17:07 +02:00
Gina Häußge 2dea5e0ffc Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	setup.py
#	src/octoprint/filemanager/__init__.py
#	src/octoprint/filemanager/storage.py
#	src/octoprint/printer/__init__.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/__init__.py
2017-04-20 12:25:08 +02:00
Gina Häußge a2323a7bb2 Merge branch 'devel' into dev/commRefactoringNG
# Conflicts:
#	setup.py
#	src/octoprint/plugins/virtual_printer/virtual.py
#	src/octoprint/printer/__init__.py
#	src/octoprint/printer/standard.py
#	src/octoprint/util/__init__.py
2016-12-08 14:37:12 +01:00
Gina Häußge cfe8b1a764 Experimenting with a real printer 2016-02-15 09:43:50 +01:00
Gina Häußge aee1dff718 Trying to get disconnecting to work reliably 2016-02-12 08:51:14 +01:00
Gina Häußge 54bd41903b Merge branch 'devel' into dev/commRefactoringNG 2016-02-11 13:46:58 +01:00
Gina Häußge c813df9afe Do not hiccup if listener to remove isn't registered 2016-02-11 08:46:47 +01:00
Gina Häußge e312f66823 We depend on pyserial 3 in this branch... 2016-02-11 08:34:55 +01:00
Gina Häußge 648c10c91f Merge branch 'devel' into dev/commRefactoringNG
Conflicts:
	src/octoprint/printer/__init__.py
	src/octoprint/printer/standard.py
2016-02-10 16:54:15 +01:00
Gina Häußge 2cf902c6c3 Stupid typos are stupid 2016-02-08 11:28:20 +01:00
Gina Häußge 26934fae02 Printing more or less works against the virtual printer 2016-02-05 16:19:36 +01:00
Gina Häußge 74ba9364f4 First attempt at connecting with existing architecture 2016-02-04 18:39:50 +01:00
Gina Häußge 18222420ee Merge branch 'devel' into dev/commRefactoringNG 2016-02-04 14:11:35 +01:00
Gina Häußge 89a37766df Minimal job queue in test code, first local file print 2016-01-30 12:08:31 +01:00
Gina Häußge cf02471db7 More work on getting to the point where printing might work
Status reporting, timeout handling, parsing etc... lots of work
2016-01-29 21:16:13 +01:00
Gina Häußge ff9b7de615 Introduced jobs, more work on protocols and transports 2016-01-29 09:02:35 +01:00
Gina Häußge b7ad8faaee WIP 2016-01-27 14:34:00 +01:00
Gina Häußge 34facfe764 WIP 2016-01-22 12:05:17 +01:00
Gina Häußge c83b6288aa Started implementation of Protocol type hierarchy 2016-01-20 13:03:34 +01:00
Gina Häußge b66f86de71 Renamed url_scheme property to key 2016-01-19 11:59:29 +01:00
Gina Häußge 581cd19446 Starting work on a better version of the comm refactoring 2016-01-16 16:35:31 +01:00
87 changed files with 15655 additions and 2512 deletions

No files matched your search

+2
View File
@@ -23,9 +23,11 @@
* [JQuery Slimscroll](http://rocha.la/jQuery-slimScroll): MIT, GPL (dual licensed)
* [JQuery UI Core, Mouse, Slider and Widget](http://jqueryui.com): MIT
* [Knockout](http://knockoutjs.com/): MIT
* [Knockout.Markdown](https://github.com/grofit/knockout.markdown): MIT
* [LESS](http://lesscss.org): Apache License 2.0
* [lodash](https://lodash.com): MIT
* [Loglevel](https://github.com/pimterry/loglevel): MIT
* [Markdown-it](https://markdown-it.github.io/): MIT
* [md5.js](https://blueimp.github.io/JavaScript-MD5/): MIT
* [Modernizr](http://modernizr.com): MIT
* [Moment.js](http://momentjs.com/): MIT
+8 -7
View File
@@ -68,11 +68,6 @@ INSTALL_REQUIRES = [
"unidecode", # dependency of awesome-slugify, leave w/o range to not cause dependency hell w/ Octolapse deps
]
# OSX specific requirements
INSTALL_REQUIRES_OSX = [
"appdirs>=1.4.4,<2",
]
# Additional requirements for optional install options
EXTRA_REQUIRES = {
"develop": [
@@ -96,13 +91,19 @@ EXTRA_REQUIRES = {
"sphinx_rtd_theme",
"readthedocs-sphinx-ext",
],
# Windows dependencies
":sys_platform == 'win32'": [
"pywin32>=301",
],
# Mac dependencies
":sys_platform == 'darwin'": [
"appdirs>=1.4.4",
],
}
# Dependency links for any of the aforementioned dependencies
DEPENDENCY_LINKS = []
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
# -----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
+23 -6
View File
@@ -280,6 +280,8 @@ def init_logging(
"serial": {"format": "%(asctime)s - %(message)s"},
"timings": {"format": "%(asctime)s - %(message)s"},
"timingscsv": {"format": "%(asctime)s;%(func)s;%(timing)f"},
"communication": {"format": "%(asctime)s - %(name)s - %(message)s"},
"commdebug": {"format": "%(asctime)s - %(threadName)s - %(message)s"},
},
"handlers": {
"console": {
@@ -298,13 +300,23 @@ def init_logging(
settings.getBaseFolder("logs"), "octoprint.log"
),
},
"serialFile": {
"class": "octoprint.logging.handlers.SerialLogHandler",
"connectionFile": {
"class": "octoprint.logging.handlers.CommunicationLogHandler",
"level": "DEBUG",
"formatter": "serial",
"formatter": "communication",
"backupCount": 3,
"filename": os.path.join(
settings.getBaseFolder("logs"), "serial.log"
settings.getBaseFolder("logs"), "connection.log"
),
"delay": True,
},
"commDebugFile": {
"class": "octoprint.logging.handlers.CommunicationLogHandler",
"level": "DEBUG",
"formatter": "commdebug",
"backupCount": 3,
"filename": os.path.join(
settings.getBaseFolder("logs"), "commdebug.log"
),
"delay": True,
},
@@ -330,9 +342,14 @@ def init_logging(
},
},
"loggers": {
"SERIAL": {
"CONNECTION": {
"level": "INFO",
"handlers": ["serialFile"],
"handlers": ["connectionFile"],
"propagate": False,
},
"COMMDEBUG": {
"level": "INFO",
"handlers": ["commDebugFile"],
"propagate": False,
},
"PLUGIN_TIMINGS": {
+1 -1
View File
@@ -41,7 +41,7 @@ def run_server(
from octoprint.logging.handlers import PluginTimingsLogHandler
logger = logging.getLogger("octoprint.startup")
PluginTimingsLogHandler.arm_rollover()
PluginTimingsLogHandler.arm_rollover(logger)
logger.info(get_divider_line("*"))
logger.info(f"Starting OctoPrint {__display_version__}")
+49
View File
@@ -0,0 +1,49 @@
# General TODOs
* Protocols
* Firmware detection vs connection sequence, warnings trigger too late/not at all
* Transports
* "no serial ports" warning
* Anything missing from settings migration to profile?
* Disconnect after incomplete connect/reset states
* Failing tests
---
On disconnect from (virtual) printer:
```
2021-12-16 17:45:05,197 - tornado.application - ERROR - Uncaught exception POST /api/connection (127.0.0.1)
HTTPServerRequest(protocol='http', host='localhost:5000', method='POST', uri='/api/connection', version='HTTP/1.1', remote_ip='127.0.0.1')
Traceback (most recent call last):
File "d:\Code\OctoPrint\devenv37\lib\site-packages\tornado\web.py", line 1702, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "d:\code\octoprint\octoprint\src\octoprint\server\util\tornado.py", line 591, in _handle_method
self._fallback(self.request, body)
File "d:\code\octoprint\octoprint\src\octoprint\server\util\tornado.py", line 702, in __call__
WsgiInputContainer.environ(request, body), start_response
File "d:\Code\OctoPrint\devenv37\lib\site-packages\flask\app.py", line 2076, in wsgi_app
response = self.handle_exception(e)
File "d:\Code\OctoPrint\devenv37\lib\site-packages\flask\app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "d:\Code\OctoPrint\devenv37\lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
rv = self.handle_user_exception(e)
File "d:\Code\OctoPrint\devenv37\lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
rv = self.dispatch_request()
File "d:\Code\OctoPrint\devenv37\lib\site-packages\flask\app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "d:\code\octoprint\octoprint\src\octoprint\server\util\flask.py", line 1560, in decorated_view
return func(*args, **kwargs)
File "d:\code\octoprint\octoprint\src\octoprint\vendor\flask_principal.py", line 196, in _decorated
rv = f(*args, **kw)
File "d:\code\octoprint\octoprint\src\octoprint\server\api\connection.py", line 102, in connectionCommand
printer.disconnect()
File "d:\code\octoprint\octoprint\src\octoprint\printer\standard.py", line 614, in disconnect
self._protocol.unregister_listener(self)
AttributeError: 'NoneType' object has no attribute 'unregister_listener'
2021-12-16 17:45:05,198 - octoprint.events.fire - DEBUG - Firing event: Disconnecting (Payload: None)
```
---
TBC
+2
View File
@@ -0,0 +1,2 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
+232
View File
@@ -0,0 +1,232 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
from os import scandir
from octoprint.settings import settings
from octoprint.util import is_hidden_path
class ConnectionProfile:
def __init__(
self,
id,
name=None,
printer_profile=None,
protocol=None,
protocol_parameters=None,
transport=None,
transport_parameters=None,
**kwargs,
):
self.id = id
self.name = name if name is not None else id
self.printer_profile = printer_profile
self.protocol = protocol
self.protocol_parameters = protocol_parameters
self.transport = transport
self.transport_parameters = transport_parameters
@classmethod
def from_dict(cls, data):
identifier = data.pop("id")
return ConnectionProfile(identifier, **data)
def as_dict(self):
return {
"id": self.id,
"name": self.name,
"printer_profile": self.printer_profile,
"protocol": self.protocol,
"protocol_parameters": self.protocol_parameters,
"transport": self.transport,
"transport_parameters": self.transport_parameters,
}
class ConnectionProfileManager:
@classmethod
def to_profile(cls, data):
return ConnectionProfile.from_dict(data)
def __init__(self):
self._current = None
self._folder = settings().getBaseFolder("connectionProfiles")
self._logger = logging.getLogger(__name__)
def select(self, identifier):
self._current = self.get(identifier)
if self._current is None:
self._logger.error(f"Profile {identifier} is invalid, cannot select")
return False
return True
def deselect(self):
self._current = None
@property
def current(self):
return self._current
def get_all(self):
return self._load_all()
def get(self, identifier):
try:
if self.exists(identifier):
return self._load_from_path(self._get_profile_path(identifier))
else:
return None
except InvalidProfileError:
return None
def remove(self, identifier):
return self._remove_from_path(self._get_profile_path(identifier))
def save(self, profile, allow_overwrite=False, make_default=False):
self._save_to_path(
self._get_profile_path(profile.id), profile, allow_overwrite=allow_overwrite
)
if make_default:
self.set_default(profile.id)
return self.get(profile.id)
@property
def profile_count(self):
return len(self._load_all_identifiers())
@property
def last_modified(self):
dates = [os.stat(self._folder).st_mtime]
dates += [
entry.stat().st_mtime
for entry in scandir(self._folder)
if entry.name.endswith(".profile")
]
return max(dates)
def get_default(self):
default = settings().get(["connection", "profiles", "default"])
if default is not None and self.exists(default):
profile = self.get(default)
if profile is not None:
return profile
else:
self._logger.warning(f"Default profile {default} is invalid")
return None
def set_default(self, identifier):
all_identifiers = self._load_all_identifiers()
if identifier is not None and identifier not in all_identifiers:
return
settings().set(["connection", "profiles", "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
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 = {}
for identifier, path in all_identifiers.items():
try:
profile = self._load_from_path(path)
except InvalidProfileError:
self._logger.warning(f"Profile {identifier} is invalid, skipping")
continue
if profile is None:
continue
results[identifier] = profile
return results
def _load_all_identifiers(self):
results = {}
for entry in scandir(self._folder):
if is_hidden_path(entry.name) or not entry.name.endswith(".profile"):
continue
if not entry.is_file():
continue
identifier = entry.name[: -len(".profile")]
results[identifier] = entry.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, encoding="utf-8") as f:
data = yaml.safe_load(f)
if data is None or not isinstance(data, dict):
raise InvalidProfileError("Profile is None or not a dict")
return ConnectionProfile.from_dict(data)
def _save_to_path(self, path, profile, allow_overwrite=False):
if os.path.exists(path) and not allow_overwrite:
raise SaveError(
"Profile {} already exists and overwriting is not allowed".format(
profile.id
)
)
import yaml
from octoprint.util import atomic_write
try:
with atomic_write(path, mode="wt", max_permissions=0o666) as f:
yaml.safe_dump(
profile.as_dict(),
f,
default_flow_style=False,
indent=2,
allow_unicode=True,
)
except Exception as e:
self._logger.exception(f"Error while trying to save profile {profile.id}")
raise SaveError(f"Cannot save profile {profile.id}: {e}")
def _remove_from_path(self, path):
try:
os.remove(path)
return True
except Exception:
return False
def _get_profile_path(self, identifier):
return os.path.join(self._folder, f"{identifier}.profile")
class InvalidProfileError(Exception):
pass
class SaveError(Exception):
pass
+388
View File
@@ -0,0 +1,388 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
import logging
import os
import time
from abc import ABCMeta
from octoprint.comm.protocol import ProtocolListener, ProtocolState
from octoprint.util.listener import ListenerAware
class LastResult:
def __init__(self):
self.elapsed = None
self.clean_elapsed = None
self.progress = None
self.pos = None
self.success = None
self.available = False
class Printjob(ProtocolListener, ListenerAware, metaclass=ABCMeta):
parallel = False
"""Job runs parallel to regular communication."""
exclusive = False
"""Job has exclusive claim to communication channel."""
def __init__(self, name=None, user=None, event_data=None):
if event_data is None:
event_data = {}
super().__init__()
self._logger = logging.getLogger(__name__)
self._start = None
self._protocol = None
self._printer_profile = None
self._name = name
self._user = user
self._event_data = event_data
self._lost_time = 0
self._last_result = LastResult()
@property
def name(self):
return self._name
@property
def user(self):
return self._user
@property
def size(self):
return None
@property
def pos(self):
return None
@property
def elapsed(self):
return time.monotonic() - self._start if self._start is not None else None
@property
def clean_elapsed(self):
elapsed = self.elapsed
if elapsed is None:
return None
return elapsed - self._lost_time
@property
def last_result(self):
return self._last_result
@property
def progress(self):
size = self.size
pos = self.pos
if pos is None or size is None or size == 0:
return None
return float(pos) / float(size)
@property
def active(self):
return self._start is not None
def add_to_lost_time(self, value):
self._lost_time += value
def can_process(self, protocol):
return False
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
self._last_result = LastResult()
self._start = time.monotonic()
self._user = user
self._protocol = protocol
self._protocol.register_listener(self)
def pause(self, user=None, tags=None, **kwargs):
self.process_job_paused(user=user, tags=tags, **kwargs)
def resume(self, user=None, tags=None, **kwargs):
self.process_job_resumed(user=user, tags=tags, **kwargs)
def cancel(self, error=None, user=None, tags=None, **kwargs):
if error:
self.process_job_failed(**kwargs)
else:
self.process_job_cancelled(user=user, tags=tags, **kwargs)
self._protocol.unregister_listener(self)
self._protocol = None
def get_next(self):
return None
def can_get_content(self):
return False
def get_content_generator(self):
return None
def event_payload(self, incl_last=False):
payload = copy.deepcopy(self._event_data)
payload["owner"] = self._user
elapsed = self.elapsed
if elapsed is None and incl_last and self.last_result.available:
elapsed = self.last_result.elapsed
if elapsed is not None:
payload["time"] = elapsed
return payload
def process_job_started(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_started", self, user=user, tags=tags, **kwargs)
def process_job_done(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_done", self, user=user, tags=tags, **kwargs)
self.report_stats()
self.reset_job()
def process_job_failed(self, **kwargs):
self.notify_listeners("on_job_failed", self, **kwargs)
self.report_stats()
self.reset_job(success=False)
def process_job_cancelled(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_cancelled", self, user=user, tags=tags, **kwargs)
self.report_stats()
self.reset_job(success=False)
def process_job_paused(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_paused", self, user=user, tags=tags, **kwargs)
def process_job_resumed(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_resumed", self, user=user, tags=tags, **kwargs)
def process_job_progress(self):
self.notify_listeners("on_job_progress", self)
def report_stats(self):
elapsed = self.elapsed
if elapsed:
self._logger.info(f"Job processed in {elapsed}s")
def reset_job(self, success=True):
self._last_result.progress = 1.0 if success else self.progress
self._last_result.pos = self.size if success else self.pos
self._last_result.elapsed = self.elapsed
self._last_result.clean_elapsed = self.clean_elapsed
self._last_result.success = success
self._last_result.available = True
self._start = None
self._lost_time = 0
def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs):
if (
new_state
in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR)
and self.active
):
self.cancel(error=True)
class StoragePrintjob(Printjob):
def __init__(self, storage, path_in_storage, *args, **kwargs):
Printjob.__init__(self, *args, **kwargs)
self._storage = storage
self._path_in_storage = path_in_storage
@property
def storage(self):
return self._storage
@property
def path_in_storage(self):
return self._path_in_storage
def event_payload(self, incl_last=False):
payload = Printjob.event_payload(self, incl_last=incl_last)
payload["name"] = self.name
payload["path"] = self.path_in_storage
payload["origin"] = self.storage
return payload
class LocalFilePrintjob(StoragePrintjob):
def __init__(self, path, *args, **kwargs):
encoding = kwargs.pop("encoding", "utf-8")
StoragePrintjob.__init__(self, *args, **kwargs)
if path is None or not os.path.exists(path):
raise ValueError("path must be set to a local file path")
self._path = path
self._encoding = encoding
self._size = os.stat(path).st_size
self._pos = 0
self._read_lines = 0
self._actual_lines = 0
self._cancel_pos = None
self._handle = None
@property
def size(self):
return self._size
@property
def pos(self):
return self._pos
@property
def actual_lines(self):
return self._actual_lines
@property
def read_lines(self):
return self._read_lines
@property
def cancel_pos(self):
return self._cancel_pos
@property
def active(self):
return self._start is not None and self._handle is not None
@property
def path(self):
return self._path
def event_payload(self, incl_last=False):
event_data = StoragePrintjob.event_payload(self, incl_last=incl_last)
event_data["size"] = self.size
return event_data
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
Printjob.process(
self, protocol, position=position, user=user, tags=tags, **kwargs
)
from octoprint.util import bom_aware_open
self._handle = bom_aware_open(
self._path, encoding=self._encoding, errors="replace"
)
if position > 0:
self._handle.seek(position)
self._pos = position
self.process_job_started(user=user, tags=tags)
def cancel(self, error=False, user=None, tags=None, **kwargs):
self._cancel_pos = self.pos
super().cancel(error=error, user=user, tags=tags, **kwargs)
def get_next(self):
from octoprint.util import to_unicode
if self._handle is None:
raise ValueError("File {} is not open for reading" % self._path)
try:
processed = None
while processed is None:
if self._handle is None:
# file got closed just now
self.process_job_done()
return None
line = to_unicode(self._handle.readline())
# we need to manually keep track of our pos here since
# codecs' readline will make our handle's tell not
# return the actual number of bytes read, but also the
# already buffered bytes (for detecting the newlines)
self._pos += len(line)
self._actual_lines += 1
if not line:
self.process_job_done()
return None
processed = self.process_line(line)
self._read_lines += 1
self.process_job_progress()
return processed
except Exception as e:
self.cancel(error=True)
self._logger.exception("Exception while processing line")
raise e
def process_line(self, line):
return line
def close(self):
if self._handle is not None:
try:
self._handle.close()
except Exception:
pass
self._handle = None
def can_get_content(self):
return True
def get_content_generator(self):
from octoprint.util import bom_aware_open
with bom_aware_open(self._path, encoding=self._encoding, error="replace") as f:
yield from f.readline()
def reset_job(self, success=True):
super().reset_job(success=success)
self.close()
self._pos = self._read_lines = 0
def report_stats(self):
elapsed = self.elapsed
lines = self._read_lines
if elapsed and lines:
self._logger.info(f"Job processed in {elapsed:.3f}s ({lines} lines)")
class CopyJobMixin:
pass
class PrintjobListener:
def on_job_started(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_done(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_failed(self, job, *args, **kwargs):
pass
def on_job_cancelling(self, job, firmware_error=None, *args, **kwargs):
pass
def on_job_cancelled(
self, job, cancel_position=None, suppress_script=False, *args, **kwargs
):
pass
def on_job_paused(
self, job, pause_position=None, suppress_script=False, *args, **kwargs
):
pass
def on_job_resumed(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_progress(self, job, *args, **kwargs):
pass
+105
View File
@@ -0,0 +1,105 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import CopyJobMixin, LocalFilePrintjob
class LocalGcodeFilePrintjob(LocalFilePrintjob):
def can_process(self, protocol):
return LocalGcodeFilePrintjob in protocol.supported_jobs
def process_line(self, line):
from octoprint.comm.protocol.reprap.util import strip_comment
# strip line
processed = line.strip()
# strip comments
processed = strip_comment(processed)
if not len(processed):
return None
# TODO apply offsets
# return result
return processed
class LocalGcodeStreamjob(LocalGcodeFilePrintjob, CopyJobMixin):
exclusive = True
@classmethod
def from_job(cls, job, remote):
if not isinstance(job, LocalGcodeFilePrintjob):
raise ValueError("job must be a LocalGcodeFilePrintjob")
path = job._path
storage = job._storage
path_in_storage = job._path_in_storage
name = job._name
user = job._user
encoding = job._encoding
event_data = job._event_data
return cls(
remote,
path,
storage,
path_in_storage,
name=name,
user=user,
encoding=encoding,
event_data=event_data,
)
def __init__(self, remote, *args, **kwargs):
super().__init__(*args, **kwargs)
self._remote = remote
@property
def remote(self):
return self._remote
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
super().process(protocol, position=position, user=user, tags=tags, **kwargs)
self._protocol.record_file(self._remote)
def process_job_done(self, user=None, tags=None, **kwargs):
self._protocol.stop_recording_file()
super().process_job_done(user=user, tags=tags, **kwargs)
def process_job_failed(self, **kwargs):
self._protocol.stop_recording_file()
super().process_job_failed(**kwargs)
def process_job_cancelled(self, user=None, tags=None, **kwargs):
self._protocol.stop_recording_file()
self._protocol.delete_file(self.remote)
super().process_job_cancelled(user=user, tags=tags, **kwargs)
def can_process(self, protocol):
from octoprint.comm.protocol import (
FileManagementProtocolMixin,
FileStreamingProtocolMixin,
)
return (
LocalGcodeStreamjob in protocol.supported_jobs
and isinstance(protocol, FileStreamingProtocolMixin)
and isinstance(protocol, FileManagementProtocolMixin)
)
def report_stats(self):
elapsed = self.elapsed
lines = self._read_lines
if elapsed and lines:
self._logger.info(
"Job processed in {:.3f}s ({} lines). Approx. {:.3f} lines/s, {:.3f} ms/line".format(
elapsed,
lines,
float(lines) / float(elapsed),
float(elapsed) * 1000.0 / float(lines),
)
)
+114
View File
@@ -0,0 +1,114 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol import FileAwareProtocolListener
from . import Printjob, StoragePrintjob
class SDFilePrintjob(StoragePrintjob, FileAwareProtocolListener):
parallel = True
def __init__(self, path, status_interval=2.0, *args, **kwargs):
name = path
if name.startswith("/"):
name = name[1:]
StoragePrintjob.__init__(
self,
"sdcard",
name,
name=name,
event_data={"name": name, "path": path, "origin": "sdcard"},
)
self._filename = path
self._status_interval = status_interval
self._status_timer = None
self._active = False
self._size = None
self._last_pos = None
@property
def size(self):
return self._size
@property
def pos(self):
return self._last_pos
@property
def active(self):
return self._start is not None and self._active
@property
def status_interval(self):
return self._status_interval
def can_process(self, protocol):
from octoprint.comm.protocol import FileAwareProtocolMixin
return SDFilePrintjob in protocol.supported_jobs and isinstance(
protocol, FileAwareProtocolMixin
)
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
Printjob.process(
self, protocol, position=position, user=user, tags=tags, **kwargs
)
self._protocol.register_listener(self)
self._active = True
self._last_pos = position
self._protocol.start_file_print(
self._filename,
position=position,
user=user,
tags=tags,
part_of_job=True,
**kwargs
)
self._protocol.start_file_print_status_monitor()
def pause(self, user=None, tags=None, **kwargs):
super().pause(user=user, tags=tags, **kwargs)
self._protocol.pause_file_print(user=user, tags=tags, part_of_job=True, **kwargs)
def resume(self, user=None, tags=None, **kwargs):
super().resume(user=user, tags=tags, **kwargs)
self._protocol.resume_file_print(user=user, tags=tags, part_of_job=True, **kwargs)
def on_protocol_sd_status(self, protocol, pos, total):
self._last_pos = pos
self._size = total
self.process_job_progress()
def on_protocol_file_print_started(
self, protocol, name, long_name, size, *args, **kwargs
):
self._size = size
self.process_job_started(**kwargs)
def on_protocol_file_print_done(self, protocol, *args, **kwargs):
self._protocol.stop_file_print_status_monitor(**kwargs)
self.process_job_done(**kwargs)
def on_protocol_file_print_paused(self, protocol, *args, **kwargs):
self._protocol.pause_file_print(**kwargs)
def on_protocol_file_print_resumed(self, protocol, *args, **kwargs):
self._protocol.resume_file_print(**kwargs)
def reset_job(self, success=True):
super().reset_job(success=success)
self._active = False
self._last_pos = None
self._size = None
def event_payload(self, incl_last=False):
payload = Printjob.event_payload(self, incl_last=incl_last)
payload["size"] = self.size
return payload
+877
View File
@@ -0,0 +1,877 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import contextlib
import copy
import logging
from typing import Union
import frozendict
from octoprint.comm.transport import (
TransportListener,
TransportOutOfAutodetectionCandidates,
TransportRequiresAutodetection,
TransportState,
)
from octoprint.plugin import plugin_manager
from octoprint.settings import SubSettings
from octoprint.settings.parameters import register_settings_overlay
from octoprint.util import CountedEvent, to_unicode
from octoprint.util.listener import ListenerAware
SETTINGS_PATH = ["connection", "protocols"]
_registry = {}
def register_protocols(settings):
from .reprap import ReprapGcodeProtocol
# stock protocols
register_protocol(ReprapGcodeProtocol, settings, SETTINGS_PATH)
# more protocols provided by plugins
logger = logging.getLogger(__name__)
hooks = plugin_manager().get_hooks("octoprint.comm.protocol.register")
for name, hook in hooks.items():
try:
protocols = hook()
for protocol in protocols:
try:
register_protocol(protocol, settings, SETTINGS_PATH)
except Exception:
logger.exception(
"Error while registering protocol class {} for plugin {}".format(
protocol, name
)
)
except Exception:
logger.exception(
"Error executing octoprint.comm.protocol.register hook for plugin {}".format(
name
)
)
def register_protocol(protocol_class, settings, path):
logger = logging.getLogger(__name__)
if not hasattr(protocol_class, "key"):
raise ValueError(f"Protocol class {protocol_class} is missing key")
if not hasattr(protocol_class, "settings"):
raise ValueError(f"Protocol class {protocol_class} is missing settings")
# register settings overlay
overlay = register_settings_overlay(settings, path, protocol_class.settings)
logger.debug(
"Registered settings overlay for protocol {} under key {}".format(
protocol_class, overlay
)
)
# register protocol
key = protocol_class.key
overrides = settings.get(path, merged=True)
_registry[key] = (
protocol_class,
protocol_class.with_settings(**overrides.get(key, {})),
)
def refresh_protocols(settings, path):
for key in _registry:
refresh_protocol(key, settings, path)
def refresh_protocol(key, settings, path):
protocol_class, _ = _registry[key]
overrides = settings.get(path, merged=True)
_registry[key] = (
protocol_class,
protocol_class.with_settings(**overrides.get(key, {})),
)
def lookup_protocol(key):
return _registry.get(key, (None, None))[1]
def all_protocols():
return map(lambda x: x[1], _registry.values())
class ProtocolErrorStats(ListenerAware):
def __init__(self, **kwargs):
super().__init__()
self._rx = 0
self._rx_errors = 0
self._rx_error_rate = 0
self._rx_arm = -1
self._rx_threshold = 0
self._rx_triggered = False
self._tx = 0
self._tx_errors = 0
self._tx_error_rate = 0
self._tx_arm = -1
self._tx_threshold = 0
self._tx_triggered = False
self.reset(**kwargs)
def reset(
self, rx_arm=None, rx_threshold=None, tx_arm=None, tx_threshold=None, **kwargs
):
self._rx = self._rx_errors = self._rx_error_rate = 0
self._rx_triggered = False
if rx_arm is not None:
self._rx_arm = rx_arm
if rx_threshold is not None:
self._rx_threshold = rx_threshold
self._tx = self._tx_errors = self._tx_error_rate = 0
self._tx_triggered = False
if tx_arm is not None:
self._tx_arm = tx_arm
if tx_threshold is not None:
self._tx_threshold = tx_threshold
@property
def rx(self):
return self._rx
@property
def rx_errors(self):
return self._rx_errors
@property
def rx_error_rate(self):
return self._rx_error_rate
@property
def rx_error_threshold(self):
return self._rx_threshold
@property
def tx(self):
return self._tx
@property
def tx_errors(self):
return self._tx_errors
@property
def tx_error_rate(self):
return self._tx_error_rate
@property
def tx_error_threshold(self):
return self._tx_threshold
def inc_rx(self):
self._rx += 1
if self._rx > self._rx_arm:
self.notify_listeners("on_protocol_stats_rx_armed", self)
def inc_rx_errors(self):
self._rx_errors += 1
self._rx_error_rate = (self._rx_errors / self._rx) if self._rx > 0 else 0
if (
self._rx > self._rx_arm
and self._rx_error_rate > self._rx_threshold
and not self._rx_triggered
):
self._rx_triggered = True
self.notify_listeners("on_protocol_stats_rx_triggered", self)
def inc_tx(self):
self._tx += 1
if self._tx > self._tx_arm:
self.notify_listeners("on_protocol_stats_tx_armed", self)
def inc_tx_errors(self):
self._tx_errors += 1
self._tx_error_rate = (self._tx_errors / self._tx) if self._tx > 0 else 0
if (
self._tx > self._tx_arm
and self._tx_error_rate > self._tx_threshold
and not self._tx_triggered
):
self._tx_triggered = True
self.notify_listeners("on_protocol_stats_tx_triggered", self)
class ProtocolErrorStatsListener:
def on_protocol_stats_tx_armed(self, stats):
pass
def on_protocol_stats_tx_triggered(self, stats):
pass
def on_protocol_stats_rx_armed(self, stats):
pass
def on_protocol_stats_rx_triggered(self, stats):
pass
class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener):
name = None
key = None
supported_jobs = []
settings = []
LOG_PREFIX_TX = ">>> "
LOG_PREFIX_RX = "<<< "
LOG_PREFIX_MSG = "--- "
LOG_PREFIX_WARN = "!!! "
LOG_PREFIX_NONE = ""
@classmethod
def with_settings(cls, **settings):
return type(
cls.__name__ + "WithSettings",
(cls,),
settings,
)
@classmethod
def get_connection_options(cls):
return []
def __init__(self, *args, **kwargs):
super().__init__()
self._logger = logging.getLogger(__name__)
self._connection_logger = logging.getLogger("CONNECTION")
self._state = ProtocolState.DISCONNECTED
self._error = None
self._stats = ProtocolErrorStats()
self._printer_profile = frozendict.frozendict(kwargs.get("printer_profile"))
self._plugin_manager = kwargs.get("plugin_manager")
self._event_bus = kwargs.get("event_bus")
self._settings = kwargs.get("settings")
if not isinstance(self._settings, ProtocolSettings):
self._settings = ProtocolSettings(self._settings, self)
self._job = None
self._transport = None
self._job_on_hold = CountedEvent()
self._args = {}
def args(self):
return copy.deepcopy(self._args)
def set_current_args(self, **value):
self._args = copy.deepcopy(value)
@contextlib.contextmanager
def job_put_on_hold(self, blocking=True):
if not self._job_on_hold.acquire(blocking=blocking):
raise RuntimeError("Could not acquire job_on_hold lock")
self._job_on_hold.set()
try:
yield
finally:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
self._job_on_hold_cleared()
self._job_on_hold.release()
@property
def job_on_hold(self):
return self._job_on_hold.counter > 0
def set_job_on_hold(self, value, blocking=True):
if not self._job_on_hold.acquire(blocking=blocking):
return False
try:
if value:
self._job_on_hold.set()
else:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
self._job_on_hold_cleared()
finally:
self._job_on_hold.release()
return True
@property
def transport(self):
return self._transport
@property
def state(self):
return self._state
@state.setter
def state(self, new_state):
old_state = self._state
if old_state == new_state:
return
self._state = new_state
name = f"_on_switching_state_{new_state}"
method = getattr(self, name, None)
if method is not None:
method(old_state)
self.log_message(f"Protocol state changed from '{old_state}' to '{new_state}'")
self.notify_listeners("on_protocol_state", self, old_state, new_state)
name = f"_on_switched_state_{new_state}"
method = getattr(self, name, None)
if method is not None:
method(old_state)
@property
def error(self):
return self._error
@error.setter
def error(self, new_error):
self._error = new_error
@property
def stats(self):
return self._stats
@property
def printer_profile(self):
return self._printer_profile
@property
def job(self):
return self._job
def connect(self, transport, transport_args=None, transport_kwargs=None):
if self.state not in (
ProtocolState.DISCONNECTED,
ProtocolState.DISCONNECTED_WITH_ERROR,
):
raise ProtocolAlreadyConnectedError("Already connected, disconnect first")
self.log_message(f"Protocol {self} connecting via transport {transport}...")
if transport_args is None:
transport_args = []
if transport_kwargs is None:
transport_kwargs = {}
self._transport = transport
self._transport.register_listener(self)
try:
if self._transport.state == TransportState.DISCONNECTED:
try:
self._transport.connect(*transport_args, **transport_kwargs)
except TransportRequiresAutodetection:
self.log_message(
"Attempting to auto detect correct transport configuration",
level=logging.INFO,
)
self._transport.start_autodetection(
*transport_args, **transport_kwargs
)
self.state = ProtocolState.CONNECTING
except TransportOutOfAutodetectionCandidates:
self.log_warning(
"Auto detection of transport configuration failed, no more candidates to test"
)
self._disconnect_transport(wait=False)
self.state = ProtocolState.DISCONNECTED
raise
except Exception as ex:
self.log_warning(f"There was an error while connecting: {str(ex)}")
self._disconnect_transport(wait=False)
self.state = ProtocolState.DISCONNECTED
raise
def disconnect(self, error=False, wait=True, timeout=10.0):
if self.state in (
ProtocolState.DISCONNECTED,
ProtocolState.DISCONNECTED_WITH_ERROR,
ProtocolState.DISCONNECTING,
ProtocolState.DISCONNECTING_WITH_ERROR,
):
raise ProtocolNotConnectedError("Already disconnecting or disconnected")
if error:
self.state = ProtocolState.DISCONNECTING_WITH_ERROR
else:
self.state = ProtocolState.DISCONNECTING
self.log_message(
f"Protocol {self} disconnecting from transport {self._transport}..."
)
if wait:
self.join(timeout=timeout)
error = self._disconnect_transport(wait=wait) or error
if error:
self.state = ProtocolState.DISCONNECTED_WITH_ERROR
else:
self.state = ProtocolState.DISCONNECTED
def _disconnect_transport(self, wait=True):
error = False
self._transport.unregister_listener(self)
if self._transport.state == TransportState.CONNECTED:
try:
self._transport.disconnect(wait=wait)
except Exception:
self._logger.exception(
f"Error while disconnecting from transport {self._transport}"
)
error = True
self._transport = None
return error
def process(self, job, position=0, user=None, tags=None, **kwargs):
if not job.can_process(self):
raise ValueError(f"Job {job} cannot be processed with protocol {self}")
self._job = job
self._job.register_listener(self)
self.state = ProtocolState.STARTING
self.notify_listeners(
"on_protocol_job_starting", self, self._job, user=user, tags=tags, **kwargs
)
self._job.process(self, position=position, user=user, tags=tags, **kwargs)
def pause_processing(self, user=None, tags=None, **kwargs):
if self._job is None or self.state not in ProtocolState.PROCESSING_STATES:
return
self.state = ProtocolState.PAUSING
self.notify_listeners(
"on_protocol_job_pausing", self, self._job, user=user, tags=tags, **kwargs
)
self._job.pause(user=user, tags=tags)
def resume_processing(self, user=None, tags=None, **kwargs):
if self._job is None or self.state not in (
ProtocolState.PAUSING,
ProtocolState.PAUSED,
):
return
self.state = ProtocolState.RESUMING
self.notify_listeners(
"on_protocol_job_resuming", self, self._job, user=user, tags=tags, **kwargs
)
self._job.resume(user=user, tags=tags, **kwargs)
def cancel_processing(self, error=False, user=None, tags=None, **kwargs):
if self._job is not None and self.state in ProtocolState.PROCESSING_STATES + (
ProtocolState.PAUSED,
):
self.state = ProtocolState.CANCELLING
self.notify_listeners(
"on_protocol_job_cancelling",
self,
self._job,
user=user,
tags=tags,
**kwargs,
)
self._job.cancel(error=error, user=user, tags=tags, **kwargs)
def can_send(self):
return True
def send_commands(self, command_type=None, tags=None, *commands):
pass
def send_script(self, script, context=None, user=None, tags=None):
"""
Sends the specified script/the GCODE script with the specified name.
Args:
script (GcodeScript or unicode): Script or name of the script to send
context (dict): Additional render context
user (str): The user on whose behalf the script is being sent. May be None
tags (set): And tags to send with the script commands. May be None
"""
pass
def repair(self):
pass
def join(self, timeout=None):
pass
def on_job_started(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_started", self, job, *args, **kwargs)
self.state = ProtocolState.PROCESSING
def on_job_paused(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_paused", self, job, *args, **kwargs)
self.state = ProtocolState.PAUSED
def on_job_resumed(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_resumed", self, job, *args, **kwargs)
self.state = ProtocolState.PROCESSING
def on_job_done(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_done", self, job, *args, **kwargs)
self._job_processed(job)
def on_job_cancelled(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_cancelled", self, job, *args, **kwargs)
self._job_processed(job)
def on_job_failed(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_failed", self, job, *args, **kwargs)
self._job_processed(job)
def _job_processed(self, job, *args, **kwargs):
self._job.unregister_listener(self)
self.state = ProtocolState.CONNECTED
def on_transport_disconnected(self, transport, error=None):
self.error = error
self.disconnect(error=error is not None, wait=False)
def on_transport_log_received_data(self, transport, data):
message = to_unicode(data, errors="replace").strip()
self.notify_listeners("on_protocol_log_received", self, message)
self.log_message(message, prefix=self.LOG_PREFIX_RX, level=None)
def on_transport_log_sent_data(self, transport, data):
message = to_unicode(data, errors="replace").strip()
self.notify_listeners("on_protocol_log_sent", self, message)
self.log_message(message, prefix=self.LOG_PREFIX_TX, level=None)
def on_transport_log_message(self, transport, data):
message = to_unicode(data, errors="replace").strip()
self.notify_listeners("on_protocol_log_message", self, message)
self.log_message(message, level=None)
def on_transport_validate_connection(self, transport):
try:
self._transport.autodetection_step()
except TransportOutOfAutodetectionCandidates:
self.log_warning(
"Auto detection of transport configuration failed, no more candidates to test"
)
self.state = ProtocolState.DISCONNECTED
def process_protocol_log(self, message: str):
self._connection_logger.debug(message)
self.notify_listeners("on_protocol_log", self, message)
def log_message(
self,
message: str,
level: Union[int, None] = logging.DEBUG,
prefix: str = LOG_PREFIX_MSG,
):
if level is not None:
self._logger.log(level, message)
self.process_protocol_log(prefix + message)
def log_warning(self, message: str, level: Union[int, None] = logging.WARNING):
self.log_message(message, level=level, prefix=self.LOG_PREFIX_WARN)
def _job_on_hold_cleared(self):
pass
def __str__(self):
return self.__class__.__name__
class ProtocolState:
CONNECTING = "connecting"
CONNECTED = "connected"
DISCONNECTING = "disconnecting"
DISCONNECTED = "disconnected"
STARTING = "starting"
PROCESSING = "processing"
FINISHING = "finishing"
CANCELLING = "cancelling"
PAUSING = "pausing"
RESUMING = "resuming"
PAUSED = "paused"
ERROR = "error"
DISCONNECTING_WITH_ERROR = "disconnecting_with_error"
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
PROCESSING_STATES = (STARTING, PROCESSING, CANCELLING, PAUSING, RESUMING, FINISHING)
OPERATIONAL_STATES = (CONNECTED, PAUSED) + PROCESSING_STATES
class ProtocolSettings(SubSettings):
def __init__(self, settings, protocol):
SubSettings.__init__(
self,
settings,
SETTINGS_PATH
+ [
protocol.key,
],
)
class ProtocolAlreadyConnectedError(Exception):
pass
class ProtocolNotConnectedError(Exception):
pass
class ThreeAxisProtocolMixin:
def move(
self, x=None, y=None, z=None, feedrate=None, relative=False, *args, **kwargs
):
pass
def home(self, x=False, y=False, z=False, *args, **kwargs):
pass
def set_feedrate_multiplier(self, multiplier, *args, **kwargs):
pass
class HeaterProtocolMixin:
def set_temperature(self, heater, temperature, wait=False, *args, **kwargs):
pass
def set_temperature_offset(self, heater, offset, *args, **kwargs):
pass
def get_temperature_offsets(self):
return {}
class MultiToolProtocolMixin:
def change_tool(self, tool, *args, **kwargs):
pass
class Fdm3dPrinterProtocolMixin(
ThreeAxisProtocolMixin, HeaterProtocolMixin, MultiToolProtocolMixin
):
def move(
self,
x=None,
y=None,
z=None,
e=None,
feedrate=None,
relative=False,
*args,
**kwargs,
):
pass
def set_extrusion_multiplier(self, multiplier, *args, **kwargs):
pass
class FanControlProtocolMixin:
def set_fan_speed(self, speed, *args, **kwargs):
pass
def get_fan_speed(self, speed, *args, **kwargs):
pass
class MotorControlProtocolMixin:
def enable_motors(self, *args, **kwargs):
self.set_motor_state(True)
def disable_motors(self, *args, **kwargs):
self.set_motor_state(False)
def set_motor_state(self, enabled, *args, **kwargs):
pass
def get_motor_state(self, *args, **kwargs):
pass
class PowerControlProtocolMixin:
def enable_power(self, *args, **kwargs):
self.set_power_state(True)
def disable_power(self, *args, **kwargs):
self.set_power_state(False)
def set_power_state(self, enabled, *args, **kwargs):
pass
def get_power_state(self, *args, **kwargs):
return None
class FileAwareProtocolMixin:
def init_file_storage(self, *args, **kwargs):
pass
def eject_file_storage(self, *args, **kwargs):
pass
def list_files(self, *args, **kwargs):
pass
def start_file_print(self, name, position=0, tags=None, *args, **kwargs):
pass
def pause_file_print(self, *args, **kwargs):
pass
def resume_file_print(self, *args, **kwargs):
pass
def get_file_print_status(self, *args, **kwargs):
pass
def start_file_print_status_monitor(self, *args, **kwargs):
pass
def stop_file_print_status_monitor(self, *args, **kwargs):
pass
class FileManagementProtocolMixin(FileAwareProtocolMixin):
def delete_file(self, name, *args, **kwargs):
pass
class FileStreamingProtocolMixin(FileManagementProtocolMixin):
def record_file(self, name, *args, **kwargs):
pass
def stop_recording_file(self, *args, **kwargs):
pass
class ProtocolListener:
def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs):
pass
def on_protocol_temperature(self, protocol, temperatures, *args, **kwargs):
pass
def on_protocol_log(self, protocol, message, *args, **kwargs):
pass
def on_protocol_log_received(self, protocol, message, *args, **kwargs):
pass
def on_protocol_log_sent(self, protocol, message, *args, **kwargs):
pass
def on_protocol_log_message(self, protocol, message, *args, **kwargs):
pass
def on_protocol_reset(self, protocol, idle, *args, **kwargs):
pass
def on_protocol_job_started(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_pausing(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_paused(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_resuming(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_resumed(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_cancelling(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_cancelled(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_finishing(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_done(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_failed(self, protocol, job, *args, **kwargs):
pass
def on_protocol_message_suppressed(
self, protocol, command, message, severity, *args, **kwargs
):
pass
class FileAwareProtocolListener:
def on_protocol_file_storage_available(self, protocol, available, *args, **kwargs):
pass
def on_protocol_file_list(self, protocol, files, *args, **kwargs):
pass
def on_protocol_file_status(self, protocol, pos, total, *args, **kwargs):
pass
def on_protocol_file_print_started(
self, protocol, name, long_name, size, *args, **kwargs
):
pass
def on_protocol_file_print_done(self, protocol, *args, **kwargs):
pass
def on_protocol_file_print_paused(self, protocol, *args, **kwargs):
pass
def on_protocol_file_print_resumed(self, protocol, *args, **kwargs):
pass
class PositionAwareProtocolListener:
def on_protocol_position_all_update(self, protocol, position, *args, **kwargs):
pass
def on_protocol_position_z_update(self, protocol, z, *args, **kwargs):
pass
class MultiToolAwareProtocolListener:
def on_protocol_tool_change(self, protocol, old_tool, new_tool, *args, **kwargs):
pass
def on_protocol_tool_invalid(
self, protocol, invalid_tool, fallback_tool, *args, **kwargs
):
pass
class FirmwareDataAwareProtocolListener:
def on_protocol_firmware_info(self, protocol, info, *args, **kwargs):
pass
def on_protocol_firmware_capability(
self, protocol, capability, enabled, capabilities, *args, **kwargs
):
pass
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,93 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
import re
from octoprint.util import pp
_compiled_regex_type = type(re.compile(r"a"))
def _is_compiled_regex(obj):
return isinstance(obj, _compiled_regex_type)
__registry = {}
def _register_command_class(cls):
__registry[cls.__name__] = cls
def to_command(line, type=None, tags=None, **kwargs):
if isinstance(line, Command):
return line
for cls in __registry.values():
if cls.pattern:
# noinspection PyUnresolvedReferences,PyProtectedMember
if _is_compiled_regex(cls.pattern) and cls.pattern.match(line):
return cls.from_line(line, type=type, tags=tags, **kwargs)
elif callable(cls.pattern) and cls.pattern(line):
return cls.from_line(line, type=type, tags=tags, **kwargs)
return Command.from_line(line, type=type, tags=tags, **kwargs)
class CommandMetaClass(type):
def __new__(mcs, *args, **kwargs):
c = type.__new__(mcs, *args, **kwargs)
_register_command_class(c)
return c
class Command(metaclass=CommandMetaClass):
pattern = None
@classmethod
def from_line(cls, line, type=None, tags=None, **kwargs):
return cls(line, type=type, tags=tags, **kwargs)
def __init__(self, line, type=None, tags=None, **kwargs):
if tags is None:
tags = set()
self.line = line
self.bytes = line.encode("ascii", errors="replace")
self.type = type
self.tags = tags
def __repr__(self):
return "{}({!r},type={!r},tags={})".format(
self.__class__.__name__, self.line, self.type, pp(self.tags)
)
def __str__(self):
return self.line
def __bytes__(self):
return self.bytes
def __key(self):
return self.line, self.type
def __eq__(self, other):
return self.__key() == other.__key()
def __hash__(self):
return hash(self.__key())
def with_type(self, type):
c = copy.deepcopy(self)
c.type = type
return c
def with_tags(self, tags):
if tags is None:
return self
c = copy.deepcopy(self)
c.tags |= tags
return c
@@ -0,0 +1,34 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.commands import Command
from octoprint.util import pp
class AtCommand(Command):
pattern = staticmethod(lambda x: x.startswith("@"))
@staticmethod
def from_line(line, **kwargs):
split = line.split(None, 1)
if len(split) == 2:
atcommand = split[0]
parameters = split[1]
else:
atcommand = split[0]
parameters = ""
atcommand = atcommand[1:]
return AtCommand(line, atcommand, parameters, **kwargs)
def __init__(self, line, atcommand, parameters, **kwargs):
self.atcommand = atcommand
self.parameters = parameters
super().__init__(line, **kwargs)
def __repr__(self):
return "AtCommand({!r},{!r},{!r},type={!r},tags={}".format(
self.line, self.atcommand, self.parameters, self.type, pp(self.tags)
)
@@ -0,0 +1,162 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import re
import string
from octoprint.comm.protocol.reprap.commands import Command
from octoprint.util import pp
class GcodeCommand(Command):
pattern = staticmethod(lambda x: GcodeCommand.command_regex.match(x))
command_regex = re.compile(
r"^\s*((?P<GM>[GM](?P<number>\d+))(\\.(?P<subcode>\d+))?|(?P<T>T(?P<tool>\d+))|(?P<F>F(?P<feedrate>\d+)))"
)
parameter_regex = re.compile(
r"(?P<key>[A-Z])((?P<value>[-+]?[0-9]*\.?[0-9]+)(?!\d)|(\s|$))"
)
possible_params = tuple(string.ascii_lowercase) + (
"subcode",
"param",
"tool",
"feedrate",
"original",
)
@staticmethod
def from_line(line, **kwargs):
if isinstance(line, GcodeCommand):
return line
tags = kwargs.get("tags")
if tags is None:
tags = set()
command_type = kwargs.get("type")
line = line.strip()
code = ""
args = {"original": line, "type": command_type, "tags": tags}
match = GcodeCommand.command_regex.match(line)
if match is None:
# not a gcode command
return Command.from_line(line, **kwargs)
if match.group("GM"):
code = match.group("GM")
if match.group("subcode"):
args["subcode"] = int(match.group("subcode"))
if match.group(0) != line:
rest = line[len(match.group(0)) :]
while True:
matched_param = GcodeCommand.parameter_regex.search(rest)
if not matched_param:
break
key = matched_param.group("key").lower()
if matched_param.group("value"):
value = matched_param.group("value")
if "." in value:
value = float(value)
else:
value = int(value)
else:
value = True
args[key] = value
rest = rest[: matched_param.start()] + rest[matched_param.end() :]
rest = rest.lstrip()
if rest:
args["param"] = rest
elif match.group("T"):
code = "T"
args["tool"] = int(match.group("tool"))
elif match.group("F"):
code = "F"
args["feedrate"] = int(match.group("feedrate"))
return GcodeCommand(code, **args)
def __init__(self, code, **kwargs):
self.code = code
self.subcode = kwargs.pop("subcode", None)
self.tool = kwargs.pop("tool", None)
self.feedrate = kwargs.pop("feedrate", None)
self.param = kwargs.pop("param", None)
self.original = kwargs.pop("original", None)
command_type = kwargs.pop("type", None)
tags = kwargs.pop("tags", None)
self.args = kwargs
if self.original is None:
line = self._to_line()
else:
line = self.original
super().__init__(line, type=command_type, tags=tags)
self._repr = self._to_repr()
def with_args(self, **kwargs):
args = {
"subcode": self.subcode,
"tool": self.tool,
"feedrate": self.feedrate,
"param": self.param,
"type": self.type,
"tags": self.tags,
}
args.update(self.args)
args.update(kwargs)
return GcodeCommand(self.code, **args)
def __getattr__(self, item):
if len(item) == 1:
return self.args.get(item, None)
raise AttributeError(f"'GcodeCommand' object has no attribute '{item}'")
def __repr__(self):
return self._repr
def _to_line(self):
attr = []
for key in string.ascii_lowercase:
value = self.args.get(key, None)
if value is not None:
if value is True:
attr.append(key.upper())
else:
attr.append(f"{key.upper()}{value!r}")
attribute_str = " ".join(attr)
return "{}{}{}".format(
self.code.upper(),
" " + attribute_str if attribute_str else "",
" " + self.param if self.param else "",
)
def _to_repr(self):
args = [
k + "=" + repr(getattr(self, k))
for k in self.possible_params
if getattr(self, k, None) is not None
]
return "GcodeCommand({!r}{},type={!r},tags={})".format(
self.code, "," + ",".join(args) if args else "", self.type, pp(self.tags)
)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,14 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from .repetier import RepetierFlavor
class AnetA8RepetierFlavor(RepetierFlavor):
key = "aneta8repetier"
name = "Anet A8"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "anet_a8" in firmware_name.lower()
@@ -0,0 +1,16 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors import StandardFlavor
class KlipperFlavor(StandardFlavor):
key = "klipper"
name = "Klipper"
unknown_requires_ack = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "klipper" in firmware_name.lower()
@@ -0,0 +1,19 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors import StandardFlavor
class MalyanFlavor(StandardFlavor):
key = "malyan"
name = "Malyan"
send_checksum = "printing"
block_while_dwelling = True
sd_always_available = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "malyan" in firmware_name.lower()
@@ -0,0 +1,51 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import re
from octoprint.comm.protocol.reprap.flavors import StandardFlavor
class MarlinFlavor(StandardFlavor):
key = "marlin"
name = "Marlin"
emergency_commands = ["M112", "M108", "M410"]
heatup_abortable = True
regex_marlin_kill_error = re.compile(
r"Heating failed|Thermal Runaway|MAXTEMP triggered|MINTEMP triggered|Invalid extruder number|Watchdog barked|KILL caused"
)
"""Regex matching first line of kill causing errors from Marlin."""
def comm_error(self, line, lower_line):
result = super().comm_error(line, lower_line)
if self.regex_min_max_error.match(line):
self._protocol.internal_state.multiline_error = line
return result
class MarlinLegacyFlavor(StandardFlavor):
key = "marlinlegacy"
name = "Legacy Marlin"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "marlin v1" in firmware_name.lower()
class PrusaMarlinFlavor(MarlinFlavor):
key = "prusamarlin"
name = "Marlin: Prusa variant"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return (
"prusa-firmware" in firmware_name.lower()
and "marlin" in firmware_name.lower()
)
@@ -0,0 +1,107 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import re
from octoprint.comm.protocol.reprap.flavors import StandardFlavor
from octoprint.comm.protocol.reprap.util import regex_positive_float_pattern
class RepetierFlavor(StandardFlavor):
key = "repetier"
name = "Repetier"
send_checksum = "always"
identical_resends_countdown = 5
block_while_dwelling = True
detect_external_heatups = False
sd_always_available = True
regex_tempextr = re.compile(
r"targetextr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern
)
"""Regex for matching target temp reporting from Repetier.
Groups will be as follows:
* ``toolnum``: number of the extruder to which the target temperature
report belongs (int)
* ``target``: new target temperature (float)
"""
regex_tempbed = re.compile("targetbed:(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier for beds.
Groups will be as follows:
* ``target``: new target temperature (float)
"""
def __init__(self, protocol):
super().__init__(protocol)
self.resend_swallow_repetitions_counter = 0
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "repetier" in firmware_name.lower()
def message_temperature(self, line, lower_line):
return (
super().message_temperature(line, lower_line)
or "targetextr" in lower_line
or "targetbed" in lower_line
)
def parse_message_temperature(self, line, lower_line):
if "targetextr" in lower_line:
match = self.regex_tempextr.match(lower_line)
if match is not None:
tool_num = int(match.group("toolnum"))
target = float(match.group("target"))
tool = f"T{tool_num}"
temperatures = {}
temperatures[tool] = (None, target)
return {
"max_tool_num": max(
tool_num, self._protocol.internal_state.current_tool
),
"temperatures": temperatures,
"heatup_detected": False,
}
elif "targetbed" in lower_line:
match = self.regex_tempbed.match(lower_line)
if match is not None:
target = float(match.group("target"))
temperatures = {"bed": (None, target)}
return {
"max_tool_num": self._protocol.internal_state.current_tool,
"temperatures": temperatures,
"heatup_detected": False,
}
else:
# Repetier sends temperature output on it's own line, so we can't use the
# "no ok in temperature output" metric to detected external heatups
result = super().parse_message_temperature(line, lower_line)
result["heatup_detected"] = False
return result
##~~ Preprocessors, returning True stops further processing by the protocol
def preprocess_comm_resend(self, linenumber):
if (
self._protocol.internal_state.resend
and self.resend_swallow_repetitions_counter
and linenumber == self._protocol.internal_state.resend_requested
and self.resend_swallow_repetitions_counter > 0
):
self._logger.debug(
"Ignoring resend request for line {}, that is "
"probably a repetition sent by the firmware to "
"ensure it arrives, not a real request".format(linenumber)
)
self.resend_swallow_repetitions_counter -= 1
return True
self.resend_swallow_repetitions_counter = self.identical_resends_countdown
@@ -0,0 +1,16 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors import StandardFlavor
class ReprapFirmwareFlavor(StandardFlavor):
key = "reprapfirmware"
name = "RepRapFirmware"
sd_relative_path = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "reprapfirmware" in firmware_name.lower()
@@ -0,0 +1,10 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors import StandardFlavor
class ReprapFirmwareFlavor(StandardFlavor):
key = "smoothieware"
name = "Smoothieware"
@@ -0,0 +1,25 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.util import process_gcode_line
from octoprint.comm.scripts import Script, UnknownScript
class GcodeScript(Script):
def __init__(self, settings, name, context=None):
def renderer(ctx):
lines = settings.loadScript("gcode", name, context=ctx)
if lines is None:
raise UnknownScript(name)
return lines
super().__init__(name, renderer, context=context)
def render(self, context=None):
script = super().render(context)
return list(
filter(
lambda x: x is not None and x.strip() != "",
map(lambda x: process_gcode_line(x), script),
)
)
@@ -0,0 +1,367 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
import threading
from octoprint.comm.protocol.reprap.commands import Command, to_command
from octoprint.comm.util.gcode import strip_comment
from octoprint.util import CountedEvent
regex_float_pattern = r"[-+]?[0-9]*\.?[0-9]+"
regex_positive_float_pattern = r"[+]?[0-9]*\.?[0-9]+"
regex_int_pattern = r"\d+"
def process_gcode_line(line, offsets=None, current_tool=None):
line = strip_comment(line).strip()
if not len(line):
return None
# TODO: apply offsets
# if offsets is not None:
# line = apply_temperature_offsets(line, offsets, current_tool=current_tool)
return line
def normalize_command_handler_result(command, handler_results, tags_to_add=None):
"""
Normalizes a command handler result.
Handler results can be either ``None``, a single result entry or a list of result
entries.
``None`` results are ignored, the provided ``command``, ``command_type``,
``gcode``, ``subcode`` and ``tags`` are returned in that case (as single-entry list with
one 5-tuple as entry).
Single result entries are either:
* a single string defining a replacement ``command``
* a 1-tuple defining a replacement ``command``
* a 2-tuple defining a replacement ``command`` and ``command_type``
* a 3-tuple defining a replacement ``command`` and ``command_type`` and additional ``tags`` to set
A ``command`` that is ``None`` will lead to the entry being ignored for
the normalized result.
The method returns a list of normalized result entries. Normalized result
entries always are a 4-tuple consisting of ``command``, ``command_type``,
``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may
be empty in which case the command is to be suppressed.
Examples:
>>> from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
>>> normalize_command_handler_result(GcodeCommand("M105"), None) # doctest: +ALLOW_UNICODE
[GcodeCommand('M105',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), GcodeCommand("M110")) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110", "lineno_reset"), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type='lineno_reset',tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), []) # doctest: +ALLOW_UNICODE
[]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", None]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), (None, "ignored")]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type='display_message',tags=set()), GcodeCommand('M110',original='M110',type='lineno_reset',tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2'})]
>>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"], tags_to_add={"tag3"}) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2', 'tag3'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2', 'tag3'})]
Arguments:
command (Command): The command for which the handler result was
generated
handler_results: The handler result(s) to normalized. Can be either
a single result entry or a list of result entries.
tags_to_add (set of unicode or None): List of tags to add to expanded result
entries
Returns:
(list) - A list of normalized handler result entries, which are
``Command`` instances
"""
original = command
if handler_results is None:
# handler didn't return anything, we'll just continue
return [original]
if not isinstance(handler_results, list):
handler_results = [
handler_results,
]
result = []
for handler_result in handler_results:
# we iterate over all handler result entries and process each one
# individually here
if handler_result is None:
# entry is None, we'll ignore that entry and continue
continue
def expand_tags(tags, tags_to_add):
tags = tags.copy()
if tags_to_add and isinstance(tags_to_add, set):
tags |= tags_to_add
return tags
if isinstance(handler_result, str):
# entry is just a string, replace command with it
if handler_result != original.line:
# command changed, swap it
command = to_command(
handler_result,
type=original.type,
tags=expand_tags(original.tags, tags_to_add),
)
result.append(command)
elif isinstance(handler_result, Command):
if handler_result != original:
command = copy.copy(handler_result)
command.tags = expand_tags(original.tags, tags_to_add)
result.append(command)
elif isinstance(handler_result, tuple):
# entry is a tuple, extract command and command_type
hook_result_length = len(handler_result)
command_type = original.type
command_tags = original.tags
if hook_result_length == 1:
# handler returned just the command
(command_line,) = handler_result
elif hook_result_length == 2:
# handler returned command and command_type
command_line, command_type = handler_result
elif hook_result_length == 3:
# handler returned command, command type and additional tags
command_line, command_type, command_tags = handler_result
else:
# handler returned a tuple of an unexpected length, ignore
# and continue
continue
if command_line is None:
# command is None, ignore it and continue
continue
if command_line != original.line or command_type != original.type:
# command or command_type changed, tags need to be rewritten
command_tags = expand_tags(command_tags, tags_to_add)
result.append(to_command(command_line, type=command_type, tags=command_tags))
# reset to original
command = original
return result
class SendToken(CountedEvent):
def __init__(self, value=0, maximum=None, **kwargs):
super().__init__(value=value, maximum=maximum, **kwargs)
self._ignored = 0
def set(self, ignore=False):
with self._mutex:
if ignore:
self._ignored += 1
self._internal_set(self._counter + 1)
def clear(self, completely=False):
with self._mutex:
if completely:
self._internal_set(0)
self._ignored = 0
else:
if self._ignored > 0:
self._ignored -= 1
self._internal_set(self._counter - 1)
self._internal_set(self._counter - 1)
class LineHistory:
def __init__(self, max=None):
self.max = max
self._lines = []
self._mutex = threading.RLock()
self._line_number_lookup = {}
@property
def lines(self):
with self._mutex:
return [x[0] for x in self._lines]
def append(self, line, line_number=None):
with self._mutex:
self._lines.append((line, line_number))
if line_number is not None:
self._line_number_lookup[line_number] = line
self._cleanup()
def clear(self):
with self._mutex:
self._lines = []
self._line_number_lookup = {}
def __len__(self):
with self._mutex:
return len(self._lines)
def __getitem__(self, line_number):
with self._mutex:
return self._line_number_lookup[line_number]
def __contains__(self, line_number):
with self._mutex:
return line_number in self._line_number_lookup
def __iter__(self):
return iter(self.lines)
def _cleanup(self):
if len(self._lines) <= self.max:
return
while len(self._lines) > self.max:
_, line_number = self._lines.pop(0)
if line_number is not None:
try:
del self._line_number_lookup[line_number]
except KeyError:
pass
class PositionRecord:
_standard_attrs = {"x", "y", "z", "e", "f", "t"}
@classmethod
def valid_e(cls, attr):
if not attr.startswith("e"):
return False
try:
int(attr[1:])
except Exception:
return False
return True
def __init__(self, *args, **kwargs):
attrs = self._standard_attrs | {key for key in kwargs if self.valid_e(key)}
for attr in attrs:
setattr(self, attr, kwargs.get(attr))
def copy_from(self, other):
# make sure all standard attrs and attrs from other are set
attrs = self._standard_attrs | {key for key in dir(other) if self.valid_e(key)}
for attr in attrs:
setattr(self, attr, getattr(other, attr))
# delete attrs other doesn't have
attrs = {key for key in dir(self) if self.valid_e(key)} - attrs
for attr in attrs:
delattr(self, attr)
def as_dict(self):
attrs = self._standard_attrs | {key for key in dir(self) if self.valid_e(key)}
return {attr: getattr(self, attr) for attr in attrs}
class TemperatureRecord:
def __init__(self):
self._tools = {}
self._bed = (None, None)
self._chamber = (None, None)
def copy_from(self, other):
self._tools = other.tools
self._bed = other.bed
self._chamber = other.chamber
def set_tool(self, tool, actual=None, target=None):
current = self._tools.get(tool, (None, None))
self._tools[tool] = self._to_new_tuple(current, actual, target)
def set_bed(self, actual=None, target=None):
current = self._bed
self._bed = self._to_new_tuple(current, actual, target)
def set_chamber(self, actual=None, target=None):
current = self._chamber
self._chamber = self._to_new_tuple(current, actual, target)
@property
def tools(self):
return dict(self._tools)
@property
def bed(self):
return self._bed
@property
def chamber(self):
return self._chamber
def as_dict(self):
result = {}
tools = self.tools
for tool, data in tools.items():
result[f"tool{tool}"] = {"actual": data[0], "target": data[1]}
bed = self.bed
result["bed"] = {"actual": bed[0], "target": bed[1]}
chamber = self.chamber
result["chamber"] = {"actual": chamber[0], "target": chamber[1]}
return result
def as_script_dict(self):
result = self.as_dict()
# backwards compatibility
tools = self.tools
for tool, data in tools.items():
result[tool] = {"actual": data[0], "target": data[1]}
bed = self.bed
result["b"] = {"actual": bed[0], "target": bed[1]}
chamber = self.chamber
result["c"] = {"actual": chamber[0], "target": chamber[1]}
return result
@classmethod
def _to_new_tuple(cls, current, actual, target):
if current is None or not isinstance(current, tuple) or len(current) != 2:
current = (None, None)
if actual is None and target is None:
return current
old_actual, old_target = current
if actual is None:
return old_actual, target
elif target is None:
return actual, old_target
else:
return actual, target
@@ -0,0 +1,190 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import contextlib
import logging
import queue
import threading
from octoprint.util import PrependableQueue, TypeAlreadyInQueue, TypedQueue
class ScriptQueue(PrependableQueue):
pass
class JobQueue(PrependableQueue):
pass
class CommandQueue(TypedQueue):
def __init__(self, *args, **kwargs):
TypedQueue.__init__(self, *args, **kwargs)
self._unblocked = threading.Event()
self._unblocked.set()
def block(self):
self._unblocked.clear()
def unblock(self):
self._unblocked.set()
@contextlib.contextmanager
def blocked(self):
self.block()
try:
yield
finally:
self.unblock()
def get(self, *args, **kwargs):
self._unblocked.wait()
return TypedQueue.get(self, *args, **kwargs)
def put(self, *args, **kwargs):
self._unblocked.wait()
return TypedQueue.put(self, *args, **kwargs)
def clear(self):
cleared = []
while True:
try:
cleared.append(TypedQueue.get(self, False))
TypedQueue.task_done(self)
except queue.Empty:
break
return cleared
class SendQueue(PrependableQueue):
def __init__(self, maxsize=0):
PrependableQueue.__init__(self, maxsize=maxsize)
self._unblocked = threading.Event()
self._unblocked.set()
self._resend_queue = PrependableQueue()
self._send_queue = PrependableQueue()
self._lookup = set()
self._resend_active = False
@property
def resend_active(self):
return self._resend_active
@resend_active.setter
def resend_active(self, resend_active):
with self.mutex:
self._resend_active = resend_active
def block(self):
self._unblocked.clear()
def unblock(self):
self._unblocked.set()
@contextlib.contextmanager
def blocked(self):
self.block()
try:
yield
finally:
self.unblock()
def prepend(self, item, item_type=None, target=None, block=True, timeout=None):
self._unblocked.wait()
PrependableQueue.prepend(
self, (item, item_type, target), block=block, timeout=timeout
)
def put(self, item, item_type=None, target=None, block=True, timeout=None):
self._unblocked.wait()
PrependableQueue.put(
self, (item, item_type, target), block=block, timeout=timeout
)
def get(self, block=True, timeout=None):
self._unblocked.wait()
item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout)
return item
def clear(self):
cleared = []
while True:
try:
cleared.append(PrependableQueue.get(self, False))
PrependableQueue.task_done(self)
except queue.Empty:
break
return cleared
def _put(self, item):
_, item_type, target = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(
item_type, f"Type {item_type} is already in queue"
)
else:
self._lookup.add(item_type)
if target == "resend":
self._resend_queue.put(item)
else:
self._send_queue.put(item)
def _prepend(self, item):
_, item_type, target = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(
item_type, f"Type {item_type} is already in queue"
)
else:
self._lookup.add(item_type)
if target == "resend":
self._resend_queue.prepend(item)
else:
self._send_queue.prepend(item)
def _get(self):
if self.resend_active:
item = self._resend_queue.get(block=False)
else:
try:
item = self._resend_queue.get(block=False)
except queue.Empty:
item = self._send_queue.get(block=False)
_, item_type, _ = item
if item_type is not None:
if item_type in self._lookup:
self._lookup.remove(item_type)
return item
def _qsize(self, len=len):
if self.resend_active:
return self._resend_queue.qsize()
else:
return self._resend_queue.qsize() + self._send_queue.qsize()
class QueueMarker:
def __init__(self, callback):
self.callback = callback
def run(self):
if callable(self.callback):
try:
self.callback()
except Exception:
logging.getLogger(__name__).exception(
"Error while running callback of QueueMarker"
)
class SendQueueMarker(QueueMarker):
pass
+34
View File
@@ -0,0 +1,34 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
class Script:
def __init__(self, name, renderer, context=None):
if context is None:
context = {}
self.name = name
self.renderer = renderer
self.context = context
def render(self, context=None):
if context is None:
context = {}
render_context = dict(self.context)
render_context.update(context)
content = self.renderer(render_context)
if content is None:
return None
return content.split("\n")
class UnknownScript(Exception):
def __init__(self, name, *args, **kwargs):
self.name = name
class InvalidScript(Exception):
pass
+511
View File
@@ -0,0 +1,511 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
import logging
from typing import Union
from octoprint.plugin import plugin_manager
from octoprint.settings import SubSettings
from octoprint.settings.parameters import get_param_dict, register_settings_overlay
from octoprint.util import Timeout
from octoprint.util.listener import ListenerAware
SETTINGS_PATH = ["connection", "transports"]
_registry = {}
def register_transports(settings):
from .serialtransport import SerialTransport
from .sockettransport import TCPSocketTransport
# stock transports
for transport in (
SerialTransport,
TCPSocketTransport,
):
register_transport(transport, settings, SETTINGS_PATH)
try:
from .sockettransport import UnixDomainSocketTransport
register_transport(UnixDomainSocketTransport, settings, SETTINGS_PATH)
except ImportError:
# Not available on this platform
pass
# Commented out for now since this is far from working
# try:
# from .namedpipetransport import NamedPipeTransport
#
# register_transport(NamedPipeTransport, settings, SETTINGS_PATH)
# except ImportError:
# # Not available on this platform
# pass
# more transports provided by plugins
logger = logging.getLogger(__name__)
hooks = plugin_manager().get_hooks("octoprint.comm.transport.register")
for name, hook in hooks.items():
try:
transports = hook()
for transport in transports:
try:
register_transport(transport, settings, SETTINGS_PATH)
except Exception:
logger.exception(
"Error while registering transport class {} for plugin {}".format(
transport, name
)
)
except Exception:
logger.exception(
"Error executing octoprint.comm.transport.register hook for plugin {}".format(
name
)
)
def register_transport(transport_class, settings, path):
logger = logging.getLogger(__name__)
if not hasattr(transport_class, "key"):
raise ValueError(f"Transport class {transport_class} is missing key")
# register settings overlay
overlay = register_transport_overlay(transport_class, settings, path)
logger.debug(
"Registered settings overlay for transport {} under key {}".format(
transport_class, overlay
)
)
# register transport
key = transport_class.key
overrides = settings.get(path, merged=True)
_registry[key] = (
transport_class,
transport_class.with_settings(**overrides.get(key, {})),
)
def register_transport_overlay(transport_class, settings, path):
if not hasattr(transport_class, "key"):
raise ValueError(f"Transport class {transport_class} is missing key")
if not hasattr(transport_class, "settings"):
raise ValueError(f"Transport class {transport_class} is missing settings")
params = transport_class.settings
return register_settings_overlay(settings, path + [transport_class.key], params)
def refresh_transports(settings, path):
for key in _registry:
refresh_transport(key, settings, path)
def refresh_transport(key, settings, path):
transport_class, _ = _registry[key]
overrides = settings.get(path, merged=True)
_registry[key] = (
transport_class,
transport_class.with_settings(**overrides.get(key, {})),
)
def lookup_transport(key):
return _registry.get(key, (None, None))[1]
def all_transports():
return map(lambda x: x[1], _registry.values())
class Transport(ListenerAware):
"""
Transport base class.
Implement at least ``in_waiting``, ``do_read`` and ``do_write``.
"""
name = None
key = None
message_integrity = False
settings = []
@classmethod
def with_settings(cls, **settings):
return type(
cls.__name__ + "WithSettings",
(cls,),
settings,
)
@classmethod
def get_connection_options(cls):
return []
def __init__(self, *args, **kwargs):
super().__init__()
self._logger = logging.getLogger(__name__)
self._state = TransportState.DISCONNECTED
self._args = {}
self._printer_profile = kwargs.get("printer_profile")
self._plugin_manager = kwargs.get("plugin_manager")
self._event_bus = kwargs.get("event_bus")
self._settings = kwargs.get("settings")
if not isinstance(self._settings, TransportSettings):
self._settings = TransportSettings(self._settings, self)
def args(self):
return copy.deepcopy(self._args)
def set_current_args(self, **value):
self._args = copy.deepcopy(value)
@property
def state(self):
return self._state
@state.setter
def state(self, value):
old_state = self.state
self._state = value
self.notify_listeners(
"on_transport_log_message",
self,
f"Transport state changed from '{old_state}' to '{value}'",
)
def can_connect(self, **params):
options = self.get_connection_options()
param_dict = get_param_dict(params, options)
return self.check_connection(**param_dict)
def connect(self, **params):
if self.state == TransportState.CONNECTED:
raise TransportAlreadyConnectedError("Already connected, disconnect first")
options = self.get_connection_options()
param_dict = get_param_dict(params, options)
self.state = TransportState.CONNECTING
if self.create_connection(**param_dict):
self.signal_connected()
def signal_connected(self):
if self.state != TransportState.CONNECTING:
return
self.state = TransportState.CONNECTED
self.notify_listeners("on_transport_connected", self)
def disconnect(self, error=None, wait=True):
if self.state == TransportState.DISCONNECTED:
raise TransportNotConnectedError("Already disconnected")
success = self.drop_connection(wait=wait)
if not success and not error:
error = "Error disconnecting transport"
if error:
self.state = TransportState.DISCONNECTED_WITH_ERROR
self.notify_listeners("on_transport_log_message", self, error)
else:
self.state = TransportState.DISCONNECTED
self.notify_listeners("on_transport_disconnected", self, error=error)
def create_connection(self, *args, **kwargs):
return True
def drop_connection(self, wait=True):
return True
def check_connection(self, *args, **kwargs):
return True
def start_autodetection(self, *args, **kwargs):
self.do_init_autodetection(*args, **kwargs)
self.autodetection_step()
def autodetection_step(self):
try:
self.do_autodetection_step()
self.notify_listeners("on_transport_validate_connection", self)
except TransportOutOfAutodetectionCandidates:
self.state = TransportState.DISCONNECTED
raise
def read(self, size=None, timeout=None):
data = self.do_read(size=size, timeout=timeout)
self.notify_listeners("on_transport_log_received_data", self, data)
return data
def write(self, data):
self.do_write(data)
self.notify_listeners("on_transport_log_sent_data", self, data)
@property
def in_waiting(self):
return 0
def do_read(self, size=None, timeout=None):
return b""
def do_write(self, data):
pass
def do_init_autodetection(self, *args, **kwargs):
pass
def do_autodetection_step(self):
pass
def process_transport_log(self, message):
self.notify_listeners("on_protocol_log", self, message)
def log_message(self, message: str, level: Union[int, None] = logging.DEBUG):
if level is not None:
self._logger.log(level, message)
self.process_transport_log(message)
def __str__(self):
return self.__class__.__name__
class TransportState:
CONNECTING = "connecting"
CONNECTED = "connected"
DISCONNECTED = "disconnected"
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
class TransportSettings(SubSettings):
def __init__(self, settings, transport):
self.transport = transport.key
SubSettings.__init__(self, settings, SETTINGS_PATH + [transport.key])
class TransportNotConnectedError(Exception):
pass
class TransportAlreadyConnectedError(Exception):
pass
class TransportWrapper(ListenerAware):
unforwarded_handlers = []
"""Allows to explicitly disable certain transport listener handlers on sub classes."""
def __init__(self, transport):
ListenerAware.__init__(self)
self.transport = transport
self.transport.register_listener(self)
# make sure we forward any transport listener calls to our own registered listeners
def forward_handler(name):
def f(*args, **kwargs):
# replace references to self.transport with self
args = [self if arg == self.transport else arg for arg in args]
kwargs = {
key: self if value == self.transport else value
for key, value in kwargs.items()
}
# forward
self.notify_listeners(name, *args, **kwargs)
return f
for handler in filter(
lambda x: x.startswith("on_transport_"), dir(TransportListener)
):
if handler not in self.__class__.unforwarded_handlers:
setattr(self, handler, forward_handler(handler))
def __getattr__(self, item):
return getattr(self.transport, item)
class SeparatorAwareTransportWrapper(TransportWrapper):
unforwarded_handlers = ["on_transport_log_received_data"]
"""We have read overwritten and hence send our own received_data notification."""
def __init__(self, transport, terminator):
TransportWrapper.__init__(self, transport)
self.terminator = terminator
self._buffered = bytearray()
def read(self, size=None, timeout=None):
termlen = len(self.terminator)
timeout = Timeout(timeout)
def check_for_terminator():
# check for terminator, if it's there we have found our line
termpos = self._buffered.find(self.terminator)
if termpos >= 0:
# line: everything up to and incl. the terminator, buffered: rest
line = self._buffered[: termpos + termlen]
del self._buffered[: termpos + termlen]
received = bytes(line)
return received
else:
return None
# do we already have a full line in the buffer?
line = check_for_terminator()
if line is not None:
self.notify_listeners("on_transport_log_received_data", self, line)
return line
# we don't have a full line yet, read more data
while not timeout.expired:
self._buffered += self.transport.read(
size=self.transport.in_waiting, timeout=timeout.remaining
)
line = check_for_terminator()
if line is not None:
self.notify_listeners("on_transport_log_received_data", self, line)
return line
if timeout.expired:
break
# if we arrive here we so far couldn't read a full line, wait for more data
c = self.transport.read(size=1, timeout=timeout.remaining)
if not c:
# EOF
break
# add to data and loop
self._buffered += c
raise TimeoutTransportException()
def __str__(self):
return "SeparatorAwareTransportWrapper({}, separator={})".format(
self.transport, self.terminator
)
class LineAwareTransportWrapper(SeparatorAwareTransportWrapper):
def __init__(self, transport):
SeparatorAwareTransportWrapper.__init__(self, transport, b"\n")
def __str__(self):
return f"LineAwareTransportWrapper({self.transport})"
class PushingTransportWrapper(TransportWrapper):
def __init__(
self, transport, name=b"PushingTransportWrapper.receiver_loop", timeout=None
):
super().__init__(transport)
self.name = name
self.timeout = timeout
self._receiver_active = False
self._receiver_thread = None
@property
def active(self):
return self._receiver_active
def connect(self, **kwargs):
try:
self.transport.connect(**kwargs)
except TransportRequiresAutodetection:
self.transport.start_autodetection(**kwargs)
import threading
self._receiver_active = True
self._receiver_thread = threading.Thread(
target=self._receiver_loop, name=self.name
)
self._receiver_thread.daemon = True
self._receiver_thread.start()
def disconnect(self, *args, **kwargs):
self._receiver_active = False
self.transport.disconnect(*args, **kwargs)
def wait(self, timeout=None):
self._receiver_thread.join(timeout)
def _receiver_loop(self):
while self._receiver_active:
try:
data = self.transport.read(timeout=self.timeout)
self.notify_listeners("on_transport_data_pushed", self, data)
except TimeoutTransportException as ex:
self.notify_listeners("on_transport_data_exception", self, ex)
except Exception as ex:
if self._receiver_active:
self.notify_listeners("on_transport_data_exception", self, ex)
def __str__(self):
return f"PushingTransportWrapper({self.transport})"
class TransportListener:
def on_transport_connected(self, transport):
pass
def on_transport_disconnected(self, transport, error=None):
pass
def on_transport_autodetecting(self, transport):
pass
def on_transport_validate_connection(self, transport):
pass
def on_transport_log_sent_data(self, transport, data):
pass
def on_transport_log_received_data(self, transport, data):
pass
def on_transport_log_message(self, transport, data):
pass
class PushingTransportWrapperListener:
def on_transport_data_pushed(self, transport, data):
pass
def on_transport_data_exception(self, transport, exception):
pass
class TransportException(Exception):
pass
class TimeoutTransportException(TransportException):
pass
class EofTransportException(TransportException):
pass
class TransportRequiresAutodetection(TransportException):
pass
class TransportOutOfAutodetectionCandidates(TransportException):
pass
@@ -0,0 +1,157 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
"""
This is currently not included in OctoPrint's available transports since it still contains some horrible
bugs.
Further testing and development is needed.
"""
from os import scandir
from flask_babel import gettext
from octoprint.comm.transport import Transport
from octoprint.settings.parameters import SuggestionType, Value
from octoprint.util import to_bytes, to_unicode
try:
from win32 import win32file, win32pipe
class NamedPipeTransport(Transport):
PIPE_BASE = r"\\.\pipe"
name = "Named Pipe"
key = "namedpipe"
message_integrity = True
@classmethod
def get_pipe_path(cls, name):
return cls.PIPE_BASE + "\\" + name
@classmethod
def get_connection_options(cls):
return [
SuggestionType(
"name",
gettext("Pipe name"),
cls.get_available_pipes(),
lambda value: Value(value),
),
]
@classmethod
def get_available_pipes(cls):
pipes = []
for item in scandir(cls.PIPE_BASE):
if not item.is_file():
continue
pipes.append(item.name)
return [Value(pipe) for pipe in sorted(pipes)]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._pipe = None
def create_connection(self, name=None):
if name is None:
raise ValueError("name must not be None")
self._pipe = win32file.CreateFile(
self.get_pipe_path(name),
win32file.GENERIC_READ | win32file.GENERIC_WRITE,
0,
None,
win32file.OPEN_EXISTING,
0,
None,
)
win32pipe.SetNamedPipeHandleState(
self._pipe, win32pipe.PIPE_READMODE_MESSAGE, None, None
)
self.set_current_args(name=name)
return True
def drop_connection(self, wait=True):
try:
self._pipe.close()
except Exception:
self._logger.exception("Error closing pipe")
return False
def do_read(self, size=None, timeout=None):
if size is None:
size = 16
result, data = win32file.ReadFile(self._pipe, size, None)
return data
def do_write(self, data):
win32file.WriteFile(self._pipe, data)
def __str__(self):
return "NamedPipeTransport"
if __name__ == "__main__":
import sys
if len(sys.argv) < 3:
print("Usage: namedpipetransport.py client|server <name>", file=sys.stderr)
print()
print(repr(NamedPipeTransport.get_available_pipes()))
sys.exit(-1)
mode = sys.argv[1]
name = sys.argv[2]
if mode == "client":
client = NamedPipeTransport()
client.create_connection(name=name)
counter = 0
while counter < 10:
message = f"Counter={counter}"
counter += 1
print(">>> " + message)
client.do_write(to_bytes(message + "\n"))
reply = to_unicode(client.do_read(16))
print("<<< " + reply)
client.drop_connection()
elif mode == "server":
p = win32pipe.CreateNamedPipe(
NamedPipeTransport.get_pipe_path(name),
win32pipe.PIPE_ACCESS_DUPLEX,
win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,
1,
65536,
65536,
300,
None,
)
win32pipe.ConnectNamedPipe(p, None)
while True:
result, data = win32file.ReadFile(p, 16, None)
if result != 0:
break
data = to_unicode(data)
print("<<< " + data)
reply = f"Echo:{data}"
print(">>> " + reply)
win32file.WriteFile(p, to_bytes(reply + "\n"))
p.close()
except ImportError:
# no NamedPipeTransport
pass
@@ -0,0 +1,626 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import time
import serial
from serial.tools.list_ports import comports
from octoprint.comm.transport import (
Transport,
TransportOutOfAutodetectionCandidates,
TransportRequiresAutodetection,
TransportState,
)
from octoprint.settings.parameters import (
BooleanType,
ChoiceType,
ConditionalGroup,
FloatType,
IntegerType,
ListType,
SmallChoiceType,
UrlType,
Value,
)
from octoprint.util import dummy_gettext as gettext
from octoprint.util.platform import get_os, set_close_exec
class SerialTransport(Transport):
name = "Serial Connection"
key = "serial"
message_integrity = False
max_write_passes = 5
baudrates = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
autodetection_baudrates = [115200, 250000]
ignored_ports = [
"/dev/ttyAMA0",
"/dev/ttyS*",
]
autodetection_delay = 0.0
settings = [
ListType(
"baudrates",
gettext("Baudrates"),
sep="\n",
factory=int,
default=baudrates,
),
ListType(
"autodetection_baudrates",
gettext("Autodetection baudrates"),
sep="\n",
factory=int,
default=autodetection_baudrates,
),
ListType(
"ignored_ports",
gettext("Ignored ports"),
help=gettext("Serial ports you'd like to ignore"),
sep="\n",
default=ignored_ports,
),
FloatType(
"autodetection_delay",
gettext("Initial autodetection delay"),
advanced=True,
expert=True,
default=0.0,
unit="sec",
help=gettext(
"Some controllers need a bit of a breather before autodetection "
"after initial connect. If autodetection fails due to a "
"hanging controller, try increasing this value."
),
),
]
@classmethod
def get_connection_options(cls):
ports_by_name = cls.get_available_serial_ports("port")
ports_by_usbid = cls.get_available_serial_ports("usbid")
ports_by_usbserial = cls.get_available_serial_ports("usbserial")
ports_by_usbport = cls.get_available_serial_ports("usbloc")
baudrates = cls.get_available_baudrates()
no_serial_ports_found = gettext("No serial ports found")
# incomplete = gettext(
# "No serial port found, are you sure your printer is physically connected and supports serial communication? Try refreshing and if that doesn't help please see the [FAQ](https://faq.octoprint.org/no-candidates)."
# )
return [
ConditionalGroup(
"connect_via",
gettext("Connect via"),
[
Value("port", title=gettext("Port name & baudrate")),
Value("usbid", title=gettext("USB ID & baudrate")),
Value("usbserial", title=gettext("USB serial no. & baudrate")),
Value("usbloc", title=gettext("USB port & baudrate")),
Value("url", title=gettext("URL")),
],
{
"port": [
ChoiceType(
"port",
gettext("Port"),
ports_by_name,
placeholder=no_serial_ports_found,
),
ChoiceType(
"baudrate",
gettext("Baudrate"),
baudrates,
default=0,
),
],
"usbid": [
ChoiceType(
"usbid",
gettext("USB ID"),
ports_by_usbid,
placeholder=no_serial_ports_found,
),
ChoiceType(
"baudrate",
gettext("Baudrate"),
baudrates,
default=0,
),
],
"usbserial": [
ChoiceType(
"usbserial",
gettext("USB serial number"),
ports_by_usbserial,
placeholder=no_serial_ports_found,
),
ChoiceType(
"baudrate",
gettext("Baudrate"),
baudrates,
default=0,
),
],
"usbloc": [
ChoiceType(
"usbloc",
gettext("USB port"),
ports_by_usbport,
placeholder=no_serial_ports_found,
),
ChoiceType(
"baudrate",
gettext("Baudrate"),
baudrates,
default=0,
),
],
"url": [
UrlType(
"url",
"URL",
help=gettext(
"See [here](https://pythonhosted.org/pyserial/url_handlers.html#urls) for supported URL schemes"
),
)
],
},
default="port",
),
] + cls._get_common_options()
@classmethod
def _get_common_options(cls):
return [
IntegerType(
"read_timeout",
gettext("Read Timeout"),
min=1,
unit="sec",
default=2,
advanced=True,
),
IntegerType(
"write_timeout",
gettext("Write Timeout"),
min=1,
unit="sec",
default=10,
advanced=True,
),
BooleanType(
"exclusive",
gettext("Request exclusive access to the serial port"),
help=gettext(
"Uncheck this if you are having problems connecting to your printer."
),
default=True,
advanced=True,
),
BooleanType(
"low_latency",
gettext("Request low latency mode on the serial port (if supported)"),
help=gettext(""),
default=True,
advanced=True,
),
ChoiceType(
"parity",
gettext("Parity"),
[
Value(serial.PARITY_NONE, gettext("none")),
Value(serial.PARITY_ODD, gettext("odd")),
Value(serial.PARITY_EVEN, gettext("even")),
],
default=serial.PARITY_NONE,
advanced=True,
expert=True,
),
SmallChoiceType(
"parity_workaround",
gettext("Apply parity double open workaround"),
[
Value(
"always",
title=gettext("Always"),
help=gettext(
"Use this if you are running into [this problem](https://forum.arduino.cc/index.php?topic=91291.0)."
),
),
Value("detect", title=gettext("If detected as potentially needed")),
Value(
"never",
title=gettext("Never"),
help=gettext(
"Use this if connecting to your printer fails with `(22, 'Invalid argument')`."
),
),
],
default="detect",
advanced=True,
expert=True,
),
]
@classmethod
def get_available_serial_ports(cls, focus):
matcher = lambda x: True
if focus == "usbid":
matcher = lambda x: x.vid and x.pid
elif focus == "usbserial":
matcher = lambda x: x.serial_number
elif focus == "usbloc":
matcher = lambda x: x.location
def port_value(port):
if focus == "usbid":
vidpid = f"{port.vid:04x}:{port.pid:04x}"
return Value(vidpid, title=f"{port.description} [{vidpid}]")
elif focus == "usbserial":
usbserial = port.serial_number
return Value(usbserial, title=f"{port.description} [{usbserial}]")
elif focus == "usbloc":
usbloc = port.location
return Value(usbloc, title=f"{port.description} [{usbloc}]")
else:
return Value(port.device, title=f"{port.description} [{port.device}]")
available_ports = comports()
if available_ports:
return [Value(None, title="Auto detect")] + sorted(
[
port_value(port)
for port in comports()
if port.device not in cls.ignored_ports and matcher(port)
],
key=lambda x: x.title,
)
else:
return []
@classmethod
def get_available_baudrates(cls):
return [Value(0, title="Auto detect")] + sorted(
[Value(baudrate) for baudrate in cls.baudrates],
key=lambda x: x.title,
reverse=True,
)
def __init__(self, *args, **kwargs):
super().__init__()
self.serial_factory = kwargs.get("serial_factory", None)
self._logger = logging.getLogger(__name__)
self._serial = None
self._closing = False
self._autodetect_candidates = None
self._autodetect_kwargs = None
self._autodetect_timer = None
def create_connection(self, **kwargs):
factory = self.serial_factory
if self.serial_factory is None:
factory = self._default_serial_factory
self._closing = False
self._serial = factory(**kwargs)
self.set_current_args(**kwargs)
return True
def drop_connection(self, wait=True):
error = False
if self._serial is not None:
self._closing = True
try:
if callable(getattr(self._serial, "cancel_read", None)):
self._serial.cancel_read()
except Exception:
self._logger.exception(
"Error while cancelling pending reads from the serial port"
)
try:
if callable(getattr(self._serial, "cancel_write", None)):
self._serial.cancel_write()
except Exception:
self._logger.exception(
"Error while cancelling pending writes to the serial port"
)
try:
self._serial.close()
except Exception:
self._logger.exception("Error while closing the serial port")
error = True
self._serial = None
return not error
def check_connection(self, *args, **kwargs):
try:
self._create_serial(**kwargs)
return True
except ValueError:
return False
def do_read(self, size=None, timeout=None):
if timeout is not None:
self._serial.timeout = timeout
return self._serial.read(size=size)
def do_write(self, data):
written = 0
passes = 0
def try_to_write(d):
result = self._serial.write(d)
if result is None or not isinstance(result, int):
# probably some plugin not returning the written bytes, assuming all of them
return len(data)
else:
return result
while written < len(data):
to_send = data[written:]
old_written = written
try:
written += try_to_write(to_send)
except serial.SerialTimeoutException:
self._logger.warning(
"Serial timeout while writing to serial port, trying again."
)
try:
# second try
written += try_to_write(to_send)
except Exception:
if not self._closing:
message = "Unexpected error while writing to serial port"
self._logger.exception(message)
self.disconnect(error=message)
break
except Exception:
if not self._closing:
message = "Unexpected error while writing to serial port"
self._logger.exception(message)
self.disconnect(error=message)
break
if old_written == written:
passes += 1
if passes > self.max_write_passes:
message = (
"Could not write anything to the serial port in {} tries, "
"something appears to be wrong with the communication".format(
self.max_write_passes
)
)
self._logger.error(message)
self.disconnect(error=message)
break
@property
def in_waiting(self):
return getattr(self._serial, "in_waiting", 0)
def do_init_autodetection(self, *args, **kwargs):
self._autodetect_kwargs = {
k: v
for k, v in kwargs.items()
if k not in ("connect_via", "port", "baudrate")
}
port = self._find_serial_port(focus=kwargs.get("connect_via"))
baudrate = kwargs.get("baudrate")
if port:
port_candidates = [
port.device,
]
else:
port_candidates = [port.device for port in comports()]
if baudrate:
baudrate_candidates = [
baudrate,
]
else:
baudrate_candidates = [*self.autodetection_baudrates]
self._autodetect_candidates = [
(p, b) for b in baudrate_candidates for p in port_candidates
]
self.log_message(
"Performing autodetection with {} port/baudrate candidates: {}".format(
len(self._autodetect_candidates),
", ".join(map(lambda x: "{}@{}".format(*x), self._autodetect_candidates)),
),
level=logging.INFO,
)
return True
def do_autodetection_step(self):
while self.state == TransportState.CONNECTING and self._autodetect_candidates:
(p, b) = self._autodetect_candidates.pop(0)
try:
self.log_message(f"Trying port {p}@{b}", level=logging.INFO)
if self._serial is None or self._serial.port != p:
if not self.create_connection(
connect_via="port",
port=p,
baudrate=b,
**self._autodetect_kwargs,
):
self.log_message(
f"Could not open {p}@{b}, skipping", level=logging.INFO
)
continue
else:
self._serial.baudrate = b
if self.autodetection_delay:
time.sleep(self.autodetection_delay)
return
except Exception:
message = f"Unexpected error while setting baudrate {b}, skipping"
self._logger.exception(message)
self.log_message(message, level=None)
if not self._autodetect_candidates:
raise TransportOutOfAutodetectionCandidates()
def _default_serial_factory(self, **kwargs):
serial_obj = self._create_serial(**kwargs)
self._apply_parity_workaround(serial_obj, **kwargs)
serial_obj.open()
self._set_close_exec(serial_obj, **kwargs)
self._set_low_latency(serial_obj, **kwargs)
return serial_obj
@classmethod
def _find_serial_port(cls, focus="port", **kwargs):
value = kwargs.get(focus)
if value is None:
return None
if focus == "port":
matcher = lambda p: p.device == value
elif focus == "usbid":
vid, pid = value.split(":")
matcher = lambda p: f"{p.vid:04x}" == vid and f"{p.pid:04x}" == pid
elif focus == "usbserial":
matcher = lambda p: p.serial_number == value
elif focus == "usbloc":
matcher = lambda p: p.location == value
else:
return None
try:
return match_port(matcher)
except PortNotFound:
return None
@classmethod
def _create_serial(cls, **kwargs):
focus = kwargs.pop("connect_via")
port_based = ("port", "usbid", "usbserial", "usbloc")
if focus in port_based:
port = cls._find_serial_port(focus=focus, **kwargs)
for k in port_based:
if k in kwargs:
kwargs.pop(k)
baudrate = kwargs.pop("baudrate", 0)
if port is None or baudrate == 0:
raise TransportRequiresAutodetection()
return cls._create_serial_for_port_and_baudrate(
port.device, baudrate, **kwargs
)
elif focus == "url":
return serial.serial_for_url(kwargs.get("url"), do_not_open=True)
else:
raise ValueError(f"Invalid focus: {focus}")
@classmethod
def _create_serial_for_port_and_baudrate(cls, port, baudrate, **kwargs):
serial_obj = serial.Serial(
baudrate=baudrate,
exclusive=kwargs.get("exclusive", True),
parity=kwargs.get("parity", serial.PARITY_NONE),
timeout=kwargs.get("read_timeout", 2),
write_timeout=kwargs.get("write_timeout", 10),
)
serial_obj.port = port # set port only now to prevent auto open
return serial_obj
@classmethod
def _apply_parity_workaround(cls, serial_obj, **kwargs):
use_parity_workaround = kwargs.get("parity_workaround")
needs_parity_workaround = get_os() == "linux" and os.path.exists(
"/etc/debian_version"
) # See #673
if use_parity_workaround == "always" or (
needs_parity_workaround and use_parity_workaround == "detect"
):
serial_obj.parity = serial.PARITY_ODD
serial_obj.open()
serial_obj.close()
serial_obj.parity = kwargs.get("parity")
return serial_obj
@classmethod
def _set_close_exec(cls, serial_obj, **kwargs):
if hasattr(serial_obj, "fd"):
# posix
set_close_exec(serial_obj.fd)
elif hasattr(serial_obj, "_port_handle"):
# win32
# noinspection PyProtectedMember
set_close_exec(serial_obj._port_handle)
return serial_obj
@classmethod
def _set_low_latency(cls, serial_obj, **kwargs):
use_low_latency = kwargs.get("low_latency", False)
if hasattr(serial_obj, "set_low_latency_mode"):
if use_low_latency:
try:
serial_obj.set_low_latency_mode(True)
except Exception:
logging.getLogger(__name__).exception(
"Could not set low latency mode on serial port"
)
else:
logging.getLogger(__name__).info(
"Platform doesn't support low latency mode on serial port"
)
return serial_obj
def __str__(self):
return "SerialTransport"
class PortNotFound(Exception):
pass
def match_port(matcher):
for port in comports():
if matcher(port):
return port
else:
raise PortNotFound()
if __name__ == "__main__":
# list ports
ports = SerialTransport.get_available_serial_ports()
for port in ports:
print(port.title + ": " + port.value)
@@ -0,0 +1,159 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import select
import socket
import time
from flask_babel import gettext
from octoprint.comm.transport import TimeoutTransportException, Transport
from octoprint.settings.parameters import IntegerType, TextType
class SocketTransport(Transport):
name = "Socket Connection"
key = "socket"
BUFSIZE = 4096
@classmethod
def get_connection_options(cls):
return [
TextType("host", "Host"),
IntegerType("port", "Port", min=1, max=65535),
] + cls.get_common_connection_options()
@classmethod
def get_common_connection_options(cls):
return [
IntegerType(
"read_timeout",
gettext("Read Timeout"),
min=1,
unit="sec",
default=2,
advanced=True,
),
IntegerType(
"write_timeout",
gettext("Write Timeout"),
min=1,
unit="sec",
default=10,
advanced=True,
),
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._socket = None
def create_connection(self, **kwargs):
result = self.create_socket(**kwargs)
self._socket.setblocking(False)
self.set_current_args(**kwargs)
return result
def in_waiting(self):
return 0 # we don't know how many bytes are waiting, we'll ignore size on do_read
def drop_connection(self, wait=True):
try:
self._logger.debug(f"Closing down socket {self._socket}...")
self._socket.close()
return True
except Exception:
self._logger.exception("Error closing socket")
return False
def do_read(self, size=None, timeout=None):
if timeout is None:
timeout = self._args.get("read_timeout", 2)
# size is unused here, but is used by other transports
ready = select.select([self._socket], [], [], timeout)
if not ready[0]:
raise TimeoutTransportException()
return self._socket.recv(self.BUFSIZE)
def do_write(self, data):
start = time.monotonic()
timeout = self._args.get("write_timeout", 10)
total_sent = 0
while total_sent < len(data):
ready = select.select(
[], [self._socket], [], timeout - (time.monotonic() - start)
)
if not ready[1]:
raise TimeoutTransportException()
sent = self._socket.send(data[total_sent:])
if sent == 0:
raise OSError("Connection closed")
total_sent += sent
def create_socket(self, **kwargs):
raise NotImplementedError()
@classmethod
def _socket_factory(cls, family, type, address):
s = socket.socket(family=family, type=type)
s.connect(address)
return s
def __str__(self):
return "SocketTransport"
class TCPSocketTransport(SocketTransport):
name = "TCP Connection"
key = "tcpsocket"
message_integrity = True
@classmethod
def get_connection_options(cls):
return [
TextType("host", "Host"),
IntegerType("port", "Port", min=1, max=65535),
] + cls.get_common_connection_options()
def create_socket(self, host=None, port=None, **kwargs):
if host is None:
raise ValueError("host must not be None")
if port is None:
raise ValueError("port must not be None")
self._socket = self._socket_factory(
socket.AF_INET, socket.SOCK_STREAM, (host, port)
)
return True
def __str__(self):
return "TCPSocketTransport"
if hasattr(socket, "AF_UNIX"):
class UnixDomainSocketTransport(SocketTransport):
name = "Unix Domain Socket"
key = "unixdomainsocket"
message_integrity = True
@classmethod
def get_connection_options(cls):
return [TextType("path", "Path")] + cls.get_common_connection_options()
def create_socket(self, path=None, **kwargs):
if path is None:
raise ValueError("path must not be None")
self._socket = self._socket_factory(socket.AF_UNIX, socket.SOCK_STREAM, path)
return True
def __str__(self):
return "UnixDomainSocketTransport"
View File
Whitespace-only changes.
+17
View File
@@ -0,0 +1,17 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
def strip_comment(line):
if ";" not in line:
# shortcut
return line
escaped = False
result = []
for c in line:
if c == ";" and not escaped:
break
result += c
escaped = (c == "\\") and not escaped
return "".join(result).strip()
+26 -20
View File
@@ -16,7 +16,7 @@ from octoprint.util import yaml
from .analysis import AnalysisQueue, QueueEntry # noqa: F401
from .destinations import FileDestinations # noqa: F401
from .storage import LocalFileStorage # noqa: F401
from .storage.local import LocalFileStorage # noqa: F401
from .util import AbstractFileWrapper, DiskFileWrapper, StreamWrapper # noqa: F401
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
@@ -891,6 +891,9 @@ class FileManager:
)
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
def create_print_job(self, destination, path, user=None):
return self._storage(destination).create_print_job(path, user=user)
def has_analysis(self, destination, path):
return self._storage(destination).has_analysis(path)
@@ -907,25 +910,28 @@ class FileManager:
self, destination, path, timestamp, print_time, success, printer_profile
):
try:
if success:
self._storage(destination).add_history(
path,
{
"timestamp": timestamp,
"printTime": print_time,
"success": success,
"printerProfile": printer_profile,
},
)
else:
self._storage(destination).add_history(
path,
{
"timestamp": timestamp,
"success": success,
"printerProfile": printer_profile,
},
)
try:
if success:
self._storage(destination).add_history(
path,
{
"timestamp": timestamp,
"printTime": print_time,
"success": success,
"printerProfile": printer_profile,
},
)
else:
self._storage(destination).add_history(
path,
{
"timestamp": timestamp,
"success": success,
"printerProfile": printer_profile,
},
)
except NotImplementedError:
pass
eventManager().fire(
Events.METADATA_STATISTICS_UPDATED, {"storage": destination, "path": path}
)
@@ -0,0 +1,457 @@
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
class Storage:
"""
Interface of storage adapters for OctoPrint.
"""
@property
def analysis_backlog(self):
"""
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
to recurse into folders if your storage adapter supports those.
:return: an iterator yielding all un-analysed files in the storage
"""
# empty generator pattern, yield is intentionally unreachable
return
# noinspection PyUnreachableCode
yield
def analysis_backlog_for_path(self, path=None):
# empty generator pattern, yield is intentionally unreachable
return
# noinspection PyUnreachableCode
yield
def last_modified(self, path=None, recursive=False):
"""
Get the last modification date of the specified ``path`` or ``path``'s subtree.
Args:
path (str or None): Path for which to determine the subtree's last modification date. If left out or
set to None, defatuls to storage root.
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
the whole ``path``'s subtree (True).
Returns: (float) The last modification date of the indicated subtree
"""
raise NotImplementedError()
def file_in_path(self, path, filepath):
"""
Returns whether the file indicated by ``file`` is inside ``path`` or not.
:param string path: the path to check
:param string filepath: path to the file
:return: ``True`` if the file is inside the path, ``False`` otherwise
"""
return NotImplementedError()
def file_exists(self, path):
"""
Returns whether the file indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the file exists, ``False`` otherwise
"""
raise NotImplementedError()
def folder_exists(self, path):
"""
Returns whether the folder indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the folder exists, ``False`` otherwise
"""
raise NotImplementedError()
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": {
"name": "some_folder",
"path": "some_folder",
"type": "folder",
"children": {
"some_sub_folder": {
"name": "some_sub_folder",
"path": "some_folder/some_sub_folder",
"type": "folder",
"typePath": ["folder"],
"children": { ... }
},
"some_file.gcode": {
"name": "some_file.gcode",
"path": "some_folder/some_file.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"name": "test.gcode",
"path": "test.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"name": "test.stl",
"path": "test.stl",
"type": "model",
"typePath": ["model", "stl"],
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param function 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 bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
do one step down into sub folders to be able to populate the ``children``.
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True, display=None):
"""
Adds a folder as ``path``
The ``path`` will be sanitized.
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:param unicode display: display name of the folder
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``
:param string path: the path of the folder to remove
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
"""
raise NotImplementedError()
def copy_folder(self, source, destination):
"""
Copies the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the path in the storage to the copy of the folder
"""
raise NotImplementedError()
def move_folder(self, source, destination):
"""
Moves the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the new path in the storage to the folder
"""
raise NotImplementedError()
def add_file(
self,
path,
file_object,
printer_profile=None,
links=None,
allow_overwrite=False,
display=None,
):
"""
Adds the file ``file_object`` as ``path``
:param string path: the file's new path, will be sanitized
:param object 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 object printer_profile: the printer profile associated with this file (if any)
:param list links: any links to add with the file
:param bool 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
:param unicode display: display name of the file
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
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 string path: path of the file to remove
"""
raise NotImplementedError()
def copy_file(self, source, destination):
"""
Copies the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the path in the storage to the copy of the file
"""
raise NotImplementedError()
def move_file(self, source, destination):
"""
Moves the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the new path in the storage to the file
"""
raise NotImplementedError()
def has_analysis(self, path):
"""
Returns whether the file at path has been analysed yet
:param path: virtual path to the file for which to retrieve the metadata
"""
raise NotImplementedError()
def create_print_job(self, path, user=None):
"""
Retrieves the :class:`~octoprint.job.PrintJob` instance
to use for printing ``path``.
"""
raise NotImplementedError()
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
"""
raise NotImplementedError()
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``
referring 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`` referring 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
"""
raise NotImplementedError()
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
"""
raise NotImplementedError()
def add_history(self, path, data):
"""
Adds a history entry for the given ``path``.
:param path: path of the file for which to add the history entry
:param data: history entry
"""
raise NotImplementedError()
def update_history(self, path, index, data):
"""
Updates the history entry for ``path`` at ``index``.
:param path: path of the file for which to update the history entry
:param index: index
:param data: history entry
"""
raise NotImplementedError()
def remove_history(self, path, index):
"""
Removes the history entry for ``path`` at ``index``.
:param path: path of the file for which to remove the history entry
:param index: index
"""
raise NotImplementedError()
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
"""
raise NotImplementedError()
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
"""
raise NotImplementedError()
def canonicalize(self, path):
"""
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
implementation must separate those if necessary.
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
of stripping any invalid characters.
Args:
path: the path to canonicalize
Returns:
a 2-tuple containing the canonicalized path and file name
"""
return self.sanitize(path)
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
:param string path: the path to sanitize
:return: a 2-tuple containing the sanitized path and file name
"""
raise NotImplementedError()
def sanitize_path(self, path):
"""
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
:param string path: the path to sanitize
:return: the sanitized path
"""
raise NotImplementedError()
def sanitize_name(self, name):
"""
Sanitizes the given file ``name``, stripping it of all invalid characters.
:param string name: the file name to sanitize
:return: the sanitized name
"""
raise NotImplementedError()
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)
"""
raise NotImplementedError()
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
"""
raise NotImplementedError()
def path_on_disk(self, path):
"""
Retrieves the path on disk for ``path``.
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
raise an :class:`io.UnsupportedOperation`
Opposite of :func:`path_in_storage`.
:param string path: the virtual path for which to retrieve the path on disk
:return: the path on disk to ``path``
"""
raise NotImplementedError()
def path_in_storage(self, path):
"""
Retrieves the equivalent in the storage adapter for ``path``.
Opposite of :func:`path_on_disk`.
:param string path: the path for which to retrieve the storage path
:return: the path in storage to ``path``
"""
raise NotImplementedError()
class StorageError(Exception):
UNKNOWN = "unknown"
INVALID_DIRECTORY = "invalid_directory"
INVALID_FILE = "invalid_file"
INVALID_SOURCE = "invalid_source"
INVALID_DESTINATION = "invalid_destination"
DOES_NOT_EXIST = "does_not_exist"
ALREADY_EXISTS = "already_exists"
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
NOT_EMPTY = "not_empty"
def __init__(self, message, code=None, cause=None):
BaseException.__init__(self)
self.message = message
self.cause = cause
if code is None:
code = StorageError.UNKNOWN
self.code = code
@@ -22,439 +22,10 @@ from octoprint.util import (
)
from octoprint.util.files import sanitize_filename
from . import Storage, StorageError
class StorageInterface:
"""
Interface of storage adapters for OctoPrint.
"""
# noinspection PyUnreachableCode
@property
def analysis_backlog(self):
"""
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
to recurse into folders if your storage adapter supports those.
:return: an iterator yielding all un-analysed files in the storage
"""
# empty generator pattern, yield is intentionally unreachable
return
yield
# noinspection PyUnreachableCode
def analysis_backlog_for_path(self, path=None):
# empty generator pattern, yield is intentionally unreachable
return
yield
def last_modified(self, path=None, recursive=False):
"""
Get the last modification date of the specified ``path`` or ``path``'s subtree.
Args:
path (str or None): Path for which to determine the subtree's last modification date. If left out or
set to None, defatuls to storage root.
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
the whole ``path``'s subtree (True).
Returns: (float) The last modification date of the indicated subtree
"""
raise NotImplementedError()
def file_in_path(self, path, filepath):
"""
Returns whether the file indicated by ``file`` is inside ``path`` or not.
:param string path: the path to check
:param string filepath: path to the file
:return: ``True`` if the file is inside the path, ``False`` otherwise
"""
return NotImplementedError()
def file_exists(self, path):
"""
Returns whether the file indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the file exists, ``False`` otherwise
"""
raise NotImplementedError()
def folder_exists(self, path):
"""
Returns whether the folder indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the folder exists, ``False`` otherwise
"""
raise NotImplementedError()
def list_files(
self, path=None, filter=None, recursive=True, level=0, force_refresh=False
):
"""
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": {
"name": "some_folder",
"path": "some_folder",
"type": "folder",
"children": {
"some_sub_folder": {
"name": "some_sub_folder",
"path": "some_folder/some_sub_folder",
"type": "folder",
"typePath": ["folder"],
"children": { ... }
},
"some_file.gcode": {
"name": "some_file.gcode",
"path": "some_folder/some_file.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"name": "test.gcode",
"path": "test.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"name": "test.stl",
"path": "test.stl",
"type": "model",
"typePath": ["model", "stl"],
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param function 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 bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
do one step down into sub folders to be able to populate the ``children``.
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True, display=None):
"""
Adds a folder as ``path``
The ``path`` will be sanitized.
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:param unicode display: display name of the folder
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``
:param string path: the path of the folder to remove
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
"""
raise NotImplementedError()
def copy_folder(self, source, destination):
"""
Copies the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the path in the storage to the copy of the folder
"""
raise NotImplementedError()
def move_folder(self, source, destination):
"""
Moves the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the new path in the storage to the folder
"""
raise NotImplementedError()
def add_file(
self,
path,
file_object,
printer_profile=None,
links=None,
allow_overwrite=False,
display=None,
):
"""
Adds the file ``file_object`` as ``path``
:param string path: the file's new path, will be sanitized
:param object 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 object printer_profile: the printer profile associated with this file (if any)
:param list links: any links to add with the file
:param bool 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
:param unicode display: display name of the file
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
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 string path: path of the file to remove
"""
raise NotImplementedError()
def copy_file(self, source, destination):
"""
Copies the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the path in the storage to the copy of the file
"""
raise NotImplementedError()
def move_file(self, source, destination):
"""
Moves the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the new path in the storage to the file
"""
raise NotImplementedError()
def has_analysis(self, path):
"""
Returns whether the file at path has been analysed yet
:param path: virtual path to the file for which to retrieve the metadata
"""
raise NotImplementedError()
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
"""
raise NotImplementedError()
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``
referring 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`` referring 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
"""
raise NotImplementedError()
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
"""
raise NotImplementedError()
def get_additional_metadata(self, path, key):
"""
Fetches additional metadata at ``key`` from the metadata of ``path``.
:param path: the virtual path to the file for which to fetch additional metadata
:param key: key of metadata to fetch
"""
raise NotImplementedError()
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
"""
raise NotImplementedError()
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
"""
raise NotImplementedError()
def canonicalize(self, path):
"""
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
implementation must separate those if necessary.
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
of stripping any invalid characters.
Args:
path: the path to canonicalize
Returns:
a 2-tuple containing the canonicalized path and file name
"""
return self.sanitize(path)
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
:param string path: the path to sanitize
:return: a 2-tuple containing the sanitized path and file name
"""
raise NotImplementedError()
def sanitize_path(self, path):
"""
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
:param string path: the path to sanitize
:return: the sanitized path
"""
raise NotImplementedError()
def sanitize_name(self, name):
"""
Sanitizes the given file ``name``, stripping it of all invalid characters.
:param string name: the file name to sanitize
:return: the sanitized name
"""
raise NotImplementedError()
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)
"""
raise NotImplementedError()
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
"""
raise NotImplementedError()
def path_on_disk(self, path):
"""
Retrieves the path on disk for ``path``.
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
raise an :class:`io.UnsupportedOperation`
Opposite of :func:`path_in_storage`.
:param string path: the virtual path for which to retrieve the path on disk
:return: the path on disk to ``path``
"""
raise NotImplementedError()
def path_in_storage(self, path):
"""
Retrieves the equivalent in the storage adapter for ``path``.
Opposite of :func:`path_on_disk`.
:param string path: the path for which to retrieve the storage path
:return: the path in storage to ``path``
"""
raise NotImplementedError()
class StorageError(Exception):
UNKNOWN = "unknown"
INVALID_DIRECTORY = "invalid_directory"
INVALID_FILE = "invalid_file"
INVALID_SOURCE = "invalid_source"
INVALID_DESTINATION = "invalid_destination"
DOES_NOT_EXIST = "does_not_exist"
ALREADY_EXISTS = "already_exists"
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
NOT_EMPTY = "not_empty"
def __init__(self, message, code=None, cause=None):
BaseException.__init__(self)
self.message = message
self.cause = cause
if code is None:
code = StorageError.UNKNOWN
self.code = code
class LocalFileStorage(StorageInterface):
class LocalFileStorage(Storage):
"""
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
@@ -464,7 +35,7 @@ class LocalFileStorage(StorageInterface):
This storage type implements :func:`path_on_disk`.
"""
def __init__(self, basefolder, create=False, really_universal=False):
def __init__(self, basefolder, create=False, key="local", really_universal=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
if necessary and ``create`` is set to ``True``.
@@ -1023,6 +594,22 @@ class LocalFileStorage(StorageInterface):
metadata = self.get_metadata(path)
return "analysis" in metadata
def create_print_job(self, path, user=None):
from octoprint.comm.job.gcode import LocalGcodeFilePrintjob
return LocalGcodeFilePrintjob(
self.path_on_disk(path),
"local",
self.path_in_storage(path),
name=self.path_in_storage(path),
user=user,
event_data={
"path": path,
"name": self.split_path(path)[1],
"origin": "local",
},
)
def get_metadata(self, path):
path, name = self.sanitize(path)
return self._get_metadata_entry(path, name)
@@ -0,0 +1,12 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import Storage
class PrinterSDStorage(Storage):
def create_print_job(self, path, user=None):
from octoprint.comm.job import SDFilePrintjob
return SDFilePrintjob("/" + path, user=user)
+5 -7
View File
@@ -67,13 +67,13 @@ class TriggeredRolloverLogHandler(
AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler
):
do_rollover = False
do_rollover = {}
suffix_template = "%Y-%m-%d_%H-%M-%S"
file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
@classmethod
def arm_rollover(cls):
cls.do_rollover = True
def arm_rollover(cls, logger):
cls.do_rollover[logger] = True
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
@@ -81,7 +81,7 @@ class TriggeredRolloverLogHandler(
self.cleanupFiles()
def shouldRollover(self, record):
return self.do_rollover
return self.do_rollover.pop(record.name, False)
def getFilesToDelete(self):
"""
@@ -110,8 +110,6 @@ class TriggeredRolloverLogHandler(
os.remove(path)
def doRollover(self):
self.do_rollover = False
if self.stream:
self.stream.close()
self.stream = None
@@ -129,7 +127,7 @@ class TriggeredRolloverLogHandler(
self.stream = self._open()
class SerialLogHandler(TriggeredRolloverLogHandler):
class CommunicationLogHandler(TriggeredRolloverLogHandler):
pass
+18 -144
View File
@@ -22,8 +22,8 @@ import os
from octoprint.plugin.core import Plugin, PluginInfo, PluginManager # noqa: F401
from octoprint.plugin.types import * # noqa: F401,F403 ## used by multiple other modules
from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin
from octoprint.settings import SubSettings
from octoprint.settings import settings as s
from octoprint.util import deprecated
# singleton
_instance = None
@@ -165,7 +165,9 @@ def plugin_settings(
)
def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
def plugin_settings_for_settings_plugin(
plugin_key, instance, settings=None, defaults=None
):
"""
Factory method for creating a :class:`PluginSettings` instance for a given :class:`SettingsPlugin` instance.
@@ -173,8 +175,9 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
Arguments:
plugin_key (string): The plugin identifier for which to create the settings instance.
implementation (octoprint.plugin.SettingsPlugin): The :class:`SettingsPlugin` instance.
instance (octoprint.plugin.SettingsPlugin): The :class:`SettingsPlugin` instance.
settings (octoprint.settings.Settings): The settings instance to use. Defaults to the global OctoPrint settings.
defaults (dict): The defaults to use.
Returns:
PluginSettings or None: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's
@@ -193,6 +196,7 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
return plugin_settings(
plugin_key,
defaults=defaults,
get_preprocessors=get_preprocessors,
set_preprocessors=set_preprocessors,
settings=settings,
@@ -278,7 +282,7 @@ def call_plugin(
error_callback(plugin._identifier, plugin, exc)
class PluginSettings:
class PluginSettings(SubSettings):
"""
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
@@ -391,86 +395,19 @@ class PluginSettings:
get_preprocessors=None,
set_preprocessors=None,
):
self.settings = settings
self.plugin_key = plugin_key
if defaults is not None:
self.defaults = {"plugins": {}}
self.defaults["plugins"][plugin_key] = defaults
SubSettings.__init__(
self,
settings,
["plugins", plugin_key],
defaults=defaults,
get_preprocessors=get_preprocessors,
set_preprocessors=set_preprocessors,
)
if self.defaults is not None:
self.defaults["plugins"][plugin_key]["_config_version"] = None
else:
self.defaults = None
if get_preprocessors is None:
get_preprocessors = {}
self.get_preprocessors = {"plugins": {}}
self.get_preprocessors["plugins"][plugin_key] = get_preprocessors
if set_preprocessors is None:
set_preprocessors = {}
self.set_preprocessors = {"plugins": {}}
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
def prefix_path_in_args(args, index=0):
result = []
if index == 0:
result.append(self._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(self._prefix_path(args[index]))
result.extend(args_after)
return result
def add_getter_kwargs(kwargs):
if "defaults" not in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if "preprocessors" not in kwargs:
kwargs.update(preprocessors=self.get_preprocessors)
return kwargs
def add_setter_kwargs(kwargs):
if "defaults" not in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if "preprocessors" not in kwargs:
kwargs.update(preprocessors=self.set_preprocessors)
return kwargs
def wrap_overlay(args):
result = list(args)
overlay = result[0]
result[0] = {"plugins": {plugin_key: overlay}}
return result
self.access_methods = {
"has": ("has", prefix_path_in_args, add_getter_kwargs),
"get": ("get", prefix_path_in_args, add_getter_kwargs),
"get_int": ("getInt", prefix_path_in_args, add_getter_kwargs),
"get_float": ("getFloat", prefix_path_in_args, add_getter_kwargs),
"get_boolean": ("getBoolean", prefix_path_in_args, add_getter_kwargs),
"set": ("set", prefix_path_in_args, add_setter_kwargs),
"set_int": ("setInt", prefix_path_in_args, add_setter_kwargs),
"set_float": ("setFloat", prefix_path_in_args, add_setter_kwargs),
"set_boolean": ("setBoolean", prefix_path_in_args, add_setter_kwargs),
"remove": ("remove", prefix_path_in_args, lambda x: x),
"add_overlay": ("add_overlay", wrap_overlay, lambda x: x),
"remove_overlay": ("remove_overlay", lambda x: x, lambda x: x),
}
self.deprecated_access_methods = {
"getInt": "get_int",
"getFloat": "get_float",
"getBoolean": "get_boolean",
"setInt": "set_int",
"setFloat": "set_float",
"setBoolean": "set_boolean",
}
def _prefix_path(self, path=None):
if path is None:
path = list()
return ["plugins", self.plugin_key] + path
def global_has(self, path, **kwargs):
return self.settings.has(path, **kwargs)
@@ -561,66 +498,3 @@ class PluginSettings:
filename += "_" + postfix
filename += ".log"
return os.path.join(self.settings.getBaseFolder("logs"), filename)
@deprecated(
"PluginSettings.get_plugin_data_folder has been replaced by OctoPrintPlugin.get_plugin_data_folder",
includedoc="Replaced by :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`",
since="1.2.0",
)
def get_plugin_data_folder(self):
path = os.path.join(self.settings.getBaseFolder("data"), self.plugin_key)
if not os.path.isdir(path):
os.makedirs(path)
return path
def get_all_data(self, **kwargs):
merged = kwargs.get("merged", True)
asdict = kwargs.get("asdict", True)
defaults = kwargs.get("defaults", self.defaults)
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
kwargs.update(
{
"merged": merged,
"asdict": asdict,
"defaults": defaults,
"preprocessors": preprocessors,
}
)
return self.settings.get(self._prefix_path(), **kwargs)
def clean_all_data(self):
self.settings.remove(self._prefix_path())
def __getattr__(self, item):
all_access_methods = list(self.access_methods.keys()) + list(
self.deprecated_access_methods.keys()
)
if item in all_access_methods:
decorator = None
if item in self.deprecated_access_methods:
new = self.deprecated_access_methods[item]
decorator = deprecated(
f"{item} has been renamed to {new}",
stacklevel=2,
)
item = new
settings_name, args_mapper, kwargs_mapper = self.access_methods[item]
if hasattr(self.settings, settings_name) and callable(
getattr(self.settings, settings_name)
):
orig_func = getattr(self.settings, settings_name)
if decorator is not None:
orig_func = decorator(orig_func)
def _func(*args, **kwargs):
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
_func.__name__ = item
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
return _func
return getattr(self.settings, item)
+358 -28
View File
@@ -3,6 +3,46 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
from octoprint.comm.transport.serialtransport import SerialTransport
class VirtualSerialTransport(SerialTransport):
name = "Virtual Connection"
key = "virtual"
settings = []
pluginSettings = None
datafolder = None
@classmethod
def with_settings_and_data(cls, settings, datafolder):
return type(
f"{cls.__name__}WithSettingsAndData",
(cls,),
{"pluginSettings": settings, "datafolder": datafolder},
)
@classmethod
def get_connection_options(cls):
return []
def create_connection(self, *args, **kwargs):
from . import virtual
self._serial = virtual.VirtualPrinter(self.pluginSettings, self.datafolder)
def check_connection(self, *args, **kwargs):
return True
def do_init_autodetection(self, *args, **kwargs):
pass
def do_autodetection_step(self):
pass
def __str__(self):
return "VirtualSerialTransport"
class VirtualPrinterPlugin(
@@ -90,41 +130,331 @@ class VirtualPrinterPlugin(
)
self._settings.global_remove(["devel", "virtualPrinter"])
def virtual_printer_factory(self, comm_instance, port, baudrate, read_timeout):
if not port == "VIRTUAL":
return None
def register_transport_hook(self, *args, **kwargs):
return [
VirtualSerialTransport.with_settings_and_data(
self._settings, self.get_plugin_data_folder()
)
]
if not self._settings.get_boolean(["enabled"]):
return None
def cli_commands(self, cli_group, pass_octoprint_ctx, *args, **kwargs):
import os
import select
import socket
import stat
import sys
import threading
import logging.handlers
import click
import serial
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
seriallog_handler = CleaningTimedRotatingFileHandler(
self._settings.get_plugin_logfile_path(postfix="serial"),
when="D",
backupCount=3,
)
seriallog_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
seriallog_handler.setLevel(logging.DEBUG)
from octoprint.util import to_bytes, to_unicode
from . import virtual
serial_obj = virtual.VirtualPrinter(
self._settings,
data_folder=self.get_plugin_data_folder(),
seriallog_handler=seriallog_handler,
read_timeout=float(read_timeout),
faked_baudrate=baudrate,
settings = octoprint.plugin.plugin_settings_for_settings_plugin(
"virtual_printer",
self,
settings=cli_group.settings,
defaults=self.get_settings_defaults(),
)
return serial_obj
datafolder = os.path.join(settings.getBaseFolder("data"), "virtual_printer")
def get_additional_port_names(self, *args, **kwargs):
if self._settings.get_boolean(["enabled"]):
return ["VIRTUAL"]
class VirtualPrinterWrapper(virtual.VirtualPrinter):
TERMINATOR = b"\n"
CHUNK_SIZE = 16
def __init__(self, *args, **kwargs):
self._reader = threading.Thread(
target=self._copy_to_incoming, name="reader"
)
self._reader.daemon = True
self._reader.start()
super().__init__(*args, **kwargs)
def wait(self):
self._read_thread.join()
def _copy_to_incoming(self):
"""Copies received lines to incoming queue"""
buffered = bytearray()
termlen = len(self.TERMINATOR)
try:
while True:
chunk = self._do_read(self.CHUNK_SIZE)
if len(chunk) == 0:
continue
buffered.extend(chunk)
# check for terminator, if it's there we have found our line
termpos = buffered.find(self.TERMINATOR)
if termpos >= 0:
# line: everything up to and incl. the terminator, buffered: rest
line = buffered[: termpos + termlen]
del buffered[: termpos + termlen]
received = bytes(line)
print(f"<<< {to_unicode(received.rstrip())}")
self.incoming.put(received)
except ConnectionAbortedError:
self.close()
except ValueError as ex:
self.close()
if "file descriptor cannot be a negative number" in str(ex):
pass
else:
raise
except Exception:
self.close()
raise
def _send(self, line):
# type: (str) -> None
if not line.endswith("\n"):
line += "\n"
try:
self._do_write(to_bytes(line, encoding="ascii", errors="replace"))
print(f">>> {line.rstrip()}")
except Exception:
self.close()
raise
def _do_read(self, size):
raise NotImplementedError()
def _do_write(self, data):
raise NotImplementedError()
class SocketVirtualPrinterWrapper(VirtualPrinterWrapper):
def __init__(self, socket, *args, **kwargs):
self._socket = socket
self._socket.setblocking(False)
super().__init__(*args, **kwargs)
def _do_read(self, size):
data = b""
ready = select.select([self._socket], [], [], 2)
if self._socket in ready[0]:
data = self._socket.recv(size)
return data
def _do_write(self, data):
ready = select.select([], [self._socket], [], 10)
if self._socket in ready[1]:
self._socket.sendall(data)
class FileVirtualPrinterWrapper(VirtualPrinterWrapper):
def __init__(self, fd, *args, **kwargs):
self._fd = fd
super().__init__(*args, **kwargs)
def _do_read(self, size):
data = b""
try:
data = os.read(self._fd, size)
except BlockingIOError:
pass
return data
def _do_write(self, data):
os.write(self._fd, data)
class SerialVirtualPrinterWrapper(VirtualPrinterWrapper):
def __init__(self, serial_obj, *args, **kwargs):
self._serial = serial_obj
super().__init__(*args, **kwargs)
def _do_read(self, size):
data = self._serial.read(size)
return data
def _do_write(self, data):
self._serial.write(data)
##~~ TCP Socket
@click.command("tcp")
@click.option("--host", "host", type=str, default="127.0.0.1")
@click.option("--port", "port", type=int, default=5543)
def tcp_command(host, port):
click.echo(f"Creating TCP server on {host}:{port}...")
with socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) as s:
s.bind((host, port))
s.listen()
while True:
conn, addr = s.accept()
print(f"Connection from {addr}")
with conn:
virtual = SocketVirtualPrinterWrapper(conn, settings, datafolder)
virtual.wait()
print(f"Connection closed from {addr}")
commands = [
tcp_command,
]
##~~ Unix Domain Socket
if hasattr(socket, "AF_UNIX"):
@click.command("uds")
@click.option(
"--path",
"path",
type=click.Path(),
default="/tmp/octoprint-virtual_printer",
)
def uds_command(path):
if os.path.exists(path):
with os.open(path, os.O_PATH) as fd:
mode = os.fstat(fd).st_mode
if stat.S_ISSOCK(mode):
os.unlink(path)
else:
print(
f"{path} already exists and is not a socket. Unable to continue."
)
sys.exit(1)
click.echo(f"Creating Unix Domain Socket server on {path}...")
with socket.socket(family=socket.AF_UNIX, type=socket.SOCK_STREAM) as s:
s.bind(path)
s.listen()
while True:
conn, _ = s.accept()
print("Connection opened")
with conn:
virtual = SocketVirtualPrinterWrapper(
conn, settings, datafolder
)
virtual.wait()
print("Connection closed")
commands.append(uds_command)
##~~ Unix PTY
try:
import fcntl
import pty
import termios
except ImportError:
pass
else:
return []
@click.command("pty")
@click.option(
"--path",
"path",
type=click.Path(),
default="/tmp/octoprint-virtual_printer",
)
def pty_command(path):
if os.path.islink(path):
realpath = os.path.realpath(path)
if not os.path.exists(realpath):
os.unlink(path)
else:
print(
f"{path} already exists as a valid symlink. Unable to continue."
)
sys.exit(1)
elif os.path.exists(path):
print(f"{path} already exists. Unable to continue.")
sys.exit(1)
click.echo(f"Creating Unix PTY on {path}...")
mfd, sfd = pty.openpty()
sfd_path = os.ttyname(sfd)
os.symlink(sfd_path, path)
fcntl.fcntl(
mfd, fcntl.F_SETFL, fcntl.fcntl(mfd, fcntl.F_GETFL) | os.O_NONBLOCK
)
attrs = termios.tcgetattr(mfd)
attrs[3] = attrs[3] & ~termios.ECHO
termios.tcsetattr(mfd, termios.TCSADRAIN, attrs)
virtual = FileVirtualPrinterWrapper(mfd, settings, datafolder)
virtual.wait()
commands.append(pty_command)
##~~ Serial
@click.command("serial")
@click.option("--port", "port", type=str, required=True)
@click.option("--baud", "baud", type=int, required=True)
def serial_command(port, baud):
try:
serial_obj = serial.Serial(
port=port, baudrate=baud, write_timeout=0, timeout=0
)
except serial.SerialException as ex:
print(ex)
sys.exit(1)
serial_obj.flushInput()
click.echo(f"Serving from serial port {port} at {baud} baud...")
virtual = SerialVirtualPrinterWrapper(serial_obj, settings, datafolder)
virtual.wait()
commands.append(serial_command)
##~~ Win32 Named Pipe
# Commented out for now since this is far from working
# try:
# from win32 import win32file, win32pipe
#
# class PipeVirtualPrinterWrapper(VirtualPrinterWrapper):
# def __init__(self, pipe, *args, **kwargs):
# self._pipe = pipe
# super().__init__(*args, **kwargs)
#
# def _do_read(self, size):
# result, data = win32file.ReadFile(self._pipe, size, None)
# return data
#
# def _do_write(self, data):
# win32file.WriteFile(self._pipe, data)
#
# @click.command("win32pipe")
# @click.option("--name", "name", default="OctoPrint-VirtualPrinter")
# def win32pipe_command(name):
# click.echo(f"Creating named pipe {name}...")
# p = win32pipe.CreateNamedPipe(
# r"\\.\pipe\\" + name,
# win32pipe.PIPE_ACCESS_DUPLEX,
# win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,
# 1,
# 65536,
# 65536,
# 300,
# None,
# )
# win32pipe.ConnectNamedPipe(p, None)
# virtual = PipeVirtualPrinterWrapper(p, settings, datafolder)
# virtual.wait()
#
# commands.append(win32pipe_command)
# except ImportError:
# # not supported on this platform
# pass
# return collected commands
return commands
__plugin_name__ = "Virtual Printer"
@@ -145,6 +475,6 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.comm.transport.serial.factory": plugin.virtual_printer_factory,
"octoprint.comm.transport.serial.additional_port_names": plugin.get_additional_port_names,
"octoprint.comm.transport.register": plugin.register_transport_hook,
"octoprint.cli.commands": plugin.cli_commands,
}
@@ -72,7 +72,7 @@ class VirtualPrinter:
self._rx_buffer_size = self._settings.get_int(["rxBuffer"])
self.incoming = CharCountingQueue(self._rx_buffer_size, name="RxBuffer")
self.outgoing = queue.Queue()
self.outgoing = Outgoing()
self.buffered = queue.Queue(maxsize=self._settings.get_int(["commandBuffer"]))
if self._settings.get_boolean(["simulateReset"]):
@@ -134,7 +134,7 @@ class VirtualPrinter:
self._virtual_eeprom = (
VirtualEEPROM(self._plugin_data_folder)
if self._settings.get_boolean(["enable_eeprom"])
if self._settings.get_boolean(["enable_eeprom"]) and self._plugin_data_folder
else None
)
self._support_M503 = self._settings.get_boolean(["support_M503"])
@@ -202,17 +202,19 @@ class VirtualPrinter:
self._triggerResendWithMissingLinenoAt110 = True
self._triggerResendWithChecksumMismatchAt115 = True
readThread = threading.Thread(
self._read_thread = threading.Thread(
target=self._processIncoming,
name="octoprint.plugins.virtual_printer.wait_thread",
)
readThread.start()
self._read_thread.daemon = True
self._read_thread.start()
bufferThread = threading.Thread(
self._buffer_thread = threading.Thread(
target=self._processBuffer,
name="octoprint.plugins.virtual_printer.buffer_thread",
)
bufferThread.start()
self._buffer_thread.daemon = True
self._buffer_thread.start()
def __str__(self):
return "VIRTUAL(read_timeout={read_timeout},write_timeout={write_timeout},options={options})".format(
@@ -226,6 +228,10 @@ class VirtualPrinter:
def _reset(self):
with self._incoming_lock:
self._clearQueue(self.incoming)
self.outgoing = bytearray("")
self._clearQueue(self.buffered)
self._relative = True
self._lastX = 0.0
self._lastY = 0.0
@@ -291,7 +297,6 @@ class VirtualPrinter:
self._sdstatus_reporter = None
self._clearQueue(self.incoming)
self._clearQueue(self.outgoing)
self._clearQueue(self.buffered)
if self._settings.get_boolean(["simulateReset"]):
@@ -622,7 +627,10 @@ class VirtualPrinter:
def _gcode_M26(self, data: str) -> None:
if self._sdCardReady:
pos = int(re.search(r"S([0-9]+)", data).group(1))
match = re.search(r"S([0-9]+)", data)
if not match:
return
pos = int(match.group(1))
self._setSdPos(pos)
def _gcode_M27(self, data: str) -> None:
@@ -696,6 +704,8 @@ class VirtualPrinter:
for cap, enabled in self._capabilities.items():
self._send("Cap:{}:{}".format(cap.upper(), "1" if enabled else "0"))
self._send("echo:OctoPrint Virtual Printer reporting for duty")
def _gcode_M117(self, data: str) -> None:
# we'll just use this to echo a message, to allow playing around with pause triggers
if self._echoOnM117:
@@ -1804,6 +1814,11 @@ class VirtualPrinter:
handle = open(file, "wt", encoding="utf-8")
except Exception:
self._send("error writing to file")
if handle is not None:
try:
handle.close()
except Exception:
pass
self._writingToSdHandle = handle
self._writingToSd = True
self._selectedSdFile = file
@@ -2040,7 +2055,8 @@ class VirtualPrinter:
)
raise SerialTimeoutException()
def readline(self) -> bytes:
def read(self, size=1):
# type: (int) -> bytes
if self._debug_awol:
time.sleep(self._read_timeout)
return b""
@@ -2067,15 +2083,11 @@ class VirtualPrinter:
# use the full read timeout as timeout
timeout = self._read_timeout
try:
# fetch a line from the queue, wait no longer than timeout
line = to_unicode(self.outgoing.get(timeout=timeout), errors="replace")
self._seriallog.info(f">>> {line.strip()}")
self.outgoing.task_done()
return to_bytes(line)
except queue.Empty:
# queue empty? return empty line
return b""
return self.outgoing.read(size=size, timeout=timeout)
@property
def in_waiting(self):
return self.outgoing.in_waiting
def close(self):
self._killed = True
@@ -2097,8 +2109,16 @@ class VirtualPrinter:
def _send(self, line):
# type: (str) -> None
if self.outgoing is not None:
self.outgoing.put(line)
if not line.endswith("\n"):
line += "\n"
try:
self.outgoing.write(to_bytes(line, encoding="ascii", errors="replace"))
except Exception:
if self.outgoing is None:
pass
else:
raise
def _ok(self):
ok = self._okFormatString
@@ -2115,6 +2135,44 @@ class VirtualPrinter:
return "Error: {}".format(self._errors.get(error).format(*args, **kwargs))
class Outgoing:
def __init__(self):
self._outgoing = bytearray()
self._mutex = threading.RLock()
self._event = threading.Event()
@property
def in_waiting(self):
# type: () -> int
with self._mutex:
return len(self._outgoing)
def read(self, size=1, timeout=0):
# type: (int, int) -> bytes
start = time.monotonic()
result = bytearray()
while len(result) < size:
if self.in_waiting >= size:
with self._mutex:
result.extend(self._outgoing[:size])
self._outgoing = self._outgoing[size:]
if not len(self._outgoing):
self._event.clear()
return bytes(result)
self._event.wait(start + timeout - time.monotonic())
if start + timeout < time.monotonic():
break
return b""
def write(self, data):
# type: (bytes) -> None
with self._mutex:
self._outgoing += data
self._event.set()
class VirtualEEPROM:
def __init__(self, data_folder):
self._data_folder = data_folder
+68 -72
View File
@@ -20,18 +20,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import re
from octoprint.comm.scripts import UnknownScript # noqa: F401,F403
from octoprint.filemanager import FileDestinations
from octoprint.settings import settings
from octoprint.util import deprecated, natural_key
@deprecated(
message="get_connection_options has been replaced by PrinterInterface.get_connection_options",
includedoc="Replaced by :func:`PrinterInterface.get_connection_options`",
since="1.3.0",
)
def get_connection_options():
return PrinterInterface.get_connection_options()
from octoprint.util import deprecated
class PrinterInterface:
@@ -49,33 +40,16 @@ class PrinterInterface:
valid_heater_regex = re.compile(r"^(tool\d+|bed|chamber)$")
"""Regex for valid heater identifiers."""
@classmethod
def get_connection_options(cls, *args, **kwargs):
"""
Retrieves the available ports, baudrates, preferred port and baudrate for connecting to the printer.
Returned ``dict`` has the following structure::
ports: <list of available serial ports>
baudrates: <list of available baudrates>
portPreference: <configured default serial port>
baudratePreference: <configured default baudrate>
autoconnect: <whether autoconnect upon server startup is enabled or not>
Returns:
(dict): A dictionary holding the connection options in the structure specified above
"""
import octoprint.util.comm as comm
return {
"ports": sorted(comm.serialList(), key=natural_key),
"baudrates": sorted(comm.baudrateList(), reverse=True),
"portPreference": settings().get(["serial", "port"]),
"baudratePreference": settings().getInt(["serial", "baudrate"]),
"autoconnect": settings().getBoolean(["serial", "autoconnect"]),
}
def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs):
def connect(
self,
protocol=None,
protocol_options=None,
transport=None,
transport_options=None,
profile=None,
*args,
**kwargs
):
"""
Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a
connection is already established, that connection will be closed prior to connecting anew with the provided
@@ -301,6 +275,58 @@ class PrinterInterface:
"""
raise NotImplementedError()
def select_job(self, job, start_printing=False, pos=None):
"""
Selects the specified ``job`` for printing. Optionally can also directly start the print after selecting
the job.
Arguments:
job (octoprint.job.PrintJob): The job to select for printing
start_printing (bool): Whether to start printing directly or not.
"""
raise NotImplementedError()
def unselect_job(self):
"""
Unselects the currently selected job.
"""
raise NotImplementedError()
# TODO add a since to the deprecation message as soon as the version this stuff will be included in is defined
@deprecated(
"select_file has been deprecated, use select_job instead",
includedoc="Replaced by :func:`select_job`",
)
def select_file(self, path, sd, printAfterSelect=False, pos=None):
"""
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
Optionally can also directly start the print after selecting the file.
Arguments:
path (str): The path to select for printing. Either an absolute path or relative path to a local file in
the uploads folder or a filename on the printer's SD card.
sd (boolean): Indicates whether the file is on the printer's SD card or not.
printAfterSelect (boolean): Indicates whether a print should be started
after the file is selected.
Raises:
InvalidFileLocation: if an absolute path was provided and not contained within local storage or
doesn't exist
InvalidFileType: if the file is not a machinecode file and hence cannot be printed
"""
raise NotImplementedError()
# TODO add a since to the deprecation message as soon as the version this stuff will be included in is defined
@deprecated(
"unselect_file has been deprecated, use unselect_job instead",
includedoc="Replaced by :func:`unselect_job`",
)
def unselect_file(self):
"""
Unselects and currently selected file.
"""
raise NotImplementedError()
def can_modify_file(self, path, sd, *args, **kwargs):
"""
Determines whether the ``path`` (on the printer's SD if ``sd`` is True) may be modified (updated or deleted)
@@ -363,35 +389,7 @@ class PrinterInterface:
return False
def select_file(
self, path, sd, printAfterSelect=False, pos=None, tags=None, *args, **kwargs
):
"""
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
Optionally can also directly start the print after selecting the file.
Arguments:
path (str): The path to select for printing. Either an absolute path or relative path to a local file in
the uploads folder or a filename on the printer's SD card.
sd (boolean): Indicates whether the file is on the printer's SD card or not.
printAfterSelect (boolean): Indicates whether a print should be started
after the file is selected.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
Raises:
InvalidFileType: if the file is not a machinecode file and hence cannot be printed
InvalidFileLocation: if an absolute path was provided and not contained within local storage or
doesn't exist
"""
raise NotImplementedError()
def unselect_file(self, *args, **kwargs):
"""
Unselects and currently selected file.
"""
raise NotImplementedError()
def start_print(self, tags=None, *args, **kwargs):
def start_print(self, tags=None, pos=None, *args, **kwargs):
"""
Starts printing the currently selected file. If no file is currently selected, does nothing.
@@ -466,7 +464,10 @@ class PrinterInterface:
* CONNECTING
* OPERATIONAL
* PRINTING
* PAUSING
* PAUSED
* RESUMING
* FINISHING
* CLOSED
* ERROR
* CLOSED_WITH_ERROR
@@ -722,11 +723,6 @@ class PrinterCallback:
pass
class UnknownScript(Exception):
def __init__(self, name, *args, **kwargs):
self.name = name
class InvalidFileLocation(Exception):
pass
+8 -2
View File
@@ -27,17 +27,23 @@ class PrintTimeEstimator:
["estimation", "printTime", "forceDumbAfterMin"]
)
self._job_type = job_type
self._data = None
self.reset()
def reset(self):
threshold = None
rolling_window = None
countdown = None
if job_type == "local" or job_type == "sdcard":
if self._job_type == "local" or self._job_type == "sdcard":
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = settings().getFloat(
["estimation", "printTime", "stableThreshold"]
)
if job_type == "sdcard":
if self._job_type == "sdcard":
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
# by that divided by the sd status polling interval
interval = settings().getFloat(["serial", "timeout", "sdStatus"])
File diff suppressed because it is too large. Load diff
+47 -36
View File
@@ -73,6 +73,7 @@ debug = False
safe_mode = False
printer = None
connectionProfileManager = None
printerProfileManager = None
fileManager = None
slicingManager = None
@@ -121,6 +122,7 @@ import octoprint.timelapse # noqa: E402
# only import further octoprint stuff down here, as it might depend on things defined above to be initialized already
from octoprint import __branch__, __display_version__, __revision__, __version__
from octoprint.comm.connectionprofile import ConnectionProfileManager
from octoprint.printer.profile import PrinterProfileManager
from octoprint.printer.standard import Printer
from octoprint.server.util import (
@@ -276,6 +278,7 @@ class Server:
global babel
global printer
global connectionProfileManager
global printerProfileManager
global fileManager
global slicingManager
@@ -381,6 +384,7 @@ class Server:
###
### See also issues #2035 and #2090
connectionProfileManager = ConnectionProfileManager()
printerProfileManager = PrinterProfileManager()
eventManager = self._event_manager
@@ -407,16 +411,7 @@ class Server:
self._settings.getBaseFolder("slicingProfiles"), printerProfileManager
)
storage_managers = {}
storage_managers[
octoprint.filemanager.FileDestinations.LOCAL
] = octoprint.filemanager.storage.LocalFileStorage(
self._settings.getBaseFolder("uploads"),
really_universal=self._settings.getBoolean(
["feature", "enforceReallyUniversalFilenames"]
),
)
storage_managers = self._collect_initial_storage_managers()
fileManager = octoprint.filemanager.FileManager(
analysisQueue,
slicingManager,
@@ -476,6 +471,7 @@ class Server:
components = {
"plugin_manager": pluginManager,
"connection_profile_manager": connectionProfileManager,
"printer_profile_manager": printerProfileManager,
"event_bus": eventManager,
"analysis_queue": analysisQueue,
@@ -576,7 +572,12 @@ class Server:
extra={"plugin": name},
)
else:
printer = Printer(fileManager, analysisQueue, printerProfileManager)
printer = Printer(
fileManager,
analysisQueue,
connectionProfileManager,
printerProfileManager,
)
components.update({"printer": printer})
from octoprint import (
@@ -601,6 +602,16 @@ class Server:
pluginManager.log_all_plugins()
# register available transports
from octoprint.comm.transport import register_transports
register_transports(self._settings)
# register available protocols
from octoprint.comm.protocol import register_protocols
register_protocols(self._settings)
# log environment data now
self._environment_detector.log_detected_environment()
@@ -1086,36 +1097,19 @@ class Server:
# analysis backlog
fileManager.process_backlog()
# auto connect
if self._settings.getBoolean(["serial", "autoconnect"]):
if self._settings.getBoolean(["connection", "profiles", "autoconnect_default"]):
self._logger.info(
"Autoconnect on startup is configured, trying to connect to the printer..."
"Autoconnect on startup is configured, "
"trying to connect via the default connection profile"
)
try:
(port, baudrate) = (
self._settings.get(["serial", "port"]),
self._settings.getInt(["serial", "baudrate"]),
)
printer_profile = printerProfileManager.get_default()
connectionOptions = printer.__class__.get_connection_options()
if port in connectionOptions["ports"] or port == "AUTO" or port is None:
self._logger.info(
f"Trying to connect to configured serial port {port}"
)
printer.connect(
port=port,
baudrate=baudrate,
profile=printer_profile["id"]
if "id" in printer_profile
else "_default",
)
else:
self._logger.info(
"Could not find configured serial port {} in the system, cannot automatically connect to a non existing printer. Is it plugged in and booted up yet?"
)
if not printer.autoconnect():
self._logger.info("Could not autoconnect")
except Exception:
self._logger.exception(
"Something went wrong while attempting to automatically connect to the printer"
"Something went wrong while attempting to "
"automatically connect to the default connection "
"profile"
)
# start up watchdogs
@@ -1334,6 +1328,21 @@ class Server:
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
def _collect_initial_storage_managers(self):
from octoprint.filemanager.storage.local import LocalFileStorage
from octoprint.filemanager.storage.sdcard import PrinterSDStorage
storage_managers = {
octoprint.filemanager.FileDestinations.LOCAL: LocalFileStorage(
self._settings.getBaseFolder("uploads"),
really_universal=self._settings.get(
["feature", "enforceReallyUniversalFilenames"]
),
),
octoprint.filemanager.FileDestinations.SDCARD: PrinterSDStorage(),
}
return storage_managers
def _setup_heartbeat_logging(self):
logger = logging.getLogger(__name__ + ".heartbeat")
@@ -2087,8 +2096,10 @@ class Server:
"js/lib/modernizr.custom.js",
"js/lib/lodash.min.js",
"js/lib/sprintf.min.js",
"js/lib/markdown-it.min.js",
"js/lib/knockout.js",
"js/lib/knockout.mapping-latest.js",
"js/lib/knockout.markdown.js",
"js/lib/babel.js",
"js/lib/avltree.js",
"js/lib/bootstrap/bootstrap.js",
+319 -43
View File
@@ -2,29 +2,48 @@ __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 abort, jsonify, request
import logging
from flask import abort, jsonify, make_response, request
from werkzeug.exceptions import BadRequest
from octoprint.access.permissions import Permissions
from octoprint.server import NO_CONTENT, printer, printerProfileManager
from octoprint.server.api import api
from octoprint.server.util.flask import get_json_command_from_request, no_firstrun_access
from octoprint.comm.connectionprofile import InvalidProfileError, SaveError
from octoprint.comm.protocol import all_protocols
from octoprint.comm.transport import all_transports
from octoprint.server import (
NO_CONTENT,
connectionProfileManager,
printer,
printerProfileManager,
)
from octoprint.server.api import api, valid_boolean_trues
from octoprint.server.util.flask import (
get_json_command_from_request,
no_firstrun_access,
with_revalidation_checking,
)
from octoprint.settings import settings
from octoprint.settings.parameters import get_param_structure
from octoprint.util import dict_merge
##~~ Connection state & commands
@api.route("/connection", methods=["GET"])
@Permissions.STATUS.require(403)
def connectionState():
state, port, baudrate, printer_profile = printer.get_current_connection()
params = printer.get_current_connection_parameters()
current = {
"state": state,
"port": port,
"baudrate": baudrate,
"printerProfile": printer_profile["id"]
if printer_profile is not None and "id" in printer_profile
else "_default",
"state": params["state"],
"connection": params["connection"],
"profile": params["printer_profile"],
"protocol": params["protocol"],
"protocolOptions": params["protocol_args"],
"transport": params["transport"],
"transportOptions": params["transport_args"],
}
return jsonify({"current": current, "options": _get_options()})
return jsonify(current=current)
@api.route("/connection", methods=["POST"])
@@ -38,47 +57,70 @@ def connectionCommand():
return response
if command == "connect":
connection_options = printer.__class__.get_connection_options()
kwargs = {}
if "connection" in data:
kwargs["connection"] = data["connection"]
if "protocol" in data:
kwargs["protocol"] = data["protocol"]
if "protocolOptions" in data:
kwargs["protocol_options"] = data["protocolOptions"]
if "transport" in data:
kwargs["transport"] = data["transport"]
if "transportOptions" in data:
kwargs["transport_options"] = data["transportOptions"]
port = None
baudrate = None
printerProfile = None
if "port" in data:
port = data["port"]
if port not in connection_options["ports"] and port != "AUTO":
abort(400, description="port is invalid")
if "baudrate" in data:
baudrate = data["baudrate"]
if baudrate not in connection_options["baudrates"] and baudrate != 0:
abort(400, description="baudrate is invalid")
if "printerProfile" in data:
printerProfile = data["printerProfile"]
if not printerProfileManager.exists(printerProfile):
abort(400, description="printerProfile is invalid")
if "save" in data and data["save"]:
settings().set(["serial", "port"], port)
settings().setInt(["serial", "baudrate"], baudrate)
printerProfileManager.set_default(printerProfile)
kwargs["profile"] = printerProfile
if "autoconnect" in data:
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
settings().setBoolean(
["connection", "profiles", "autoconnect_default"], data["autoconnect"]
)
##~~ legacy
# TODO remove in 2.5
if "port" in data.keys():
kwargs["port"] = data["port"]
if "baudrate" in data.keys():
kwargs["baudrate"] = data["baudrate"]
settings().save()
printer.connect(port=port, baudrate=baudrate, profile=printerProfile)
printer.connect(**kwargs)
elif command == "disconnect":
printer.disconnect()
elif command == "fake_ack":
printer.fake_ack()
return NO_CONTENT
def _get_options():
connection_options = printer.__class__.get_connection_options()
profile_options = printerProfileManager.get_all()
default_profile = printerProfileManager.get_default()
##~~ Connection options (profiles, protocols, transports)
@api.route("/connection/options", methods=["GET"])
@Permissions.STATUS.require(403)
def connectionOptions():
printer_profiles = printerProfileManager.get_all()
default_printer = printerProfileManager.get_default()
connection_profiles = connectionProfileManager.get_all()
default_connection = connectionProfileManager.get_default()
options = {
"ports": connection_options["ports"],
"baudrates": connection_options["baudrates"],
"printerProfiles": [
{
"id": printer_profile["id"],
@@ -86,14 +128,248 @@ def _get_options():
if "name" in printer_profile
else printer_profile["id"],
}
for printer_profile in profile_options.values()
for printer_profile in printer_profiles.values()
if "id" in printer_profile
],
"portPreference": connection_options["portPreference"],
"baudratePreference": connection_options["baudratePreference"],
"printerProfilePreference": default_profile["id"]
if "id" in default_profile
"connectionProfiles": [
connection_profile.as_dict()
for connection_profile in connection_profiles.values()
],
"printerProfilePreference": default_printer["id"]
if "id" in default_printer
else None,
"connectionProfilePreference": default_connection.id
if default_connection
else None,
"protocols": _get_protocols(),
"transports": _get_transports(),
}
return options
return jsonify(options=options)
##~~ Connection profiles
def _connection_profiles_lastmodified():
return connectionProfileManager.last_modified
def _connection_profiles_etag(lm=None):
if lm is None:
lm = _connection_profiles_lastmodified()
import hashlib
hash = hashlib.sha1()
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
hash_update(str(lm))
hash_update(repr(connectionProfileManager.get_default()))
hash_update(repr(connectionProfileManager.get_current()))
return hash.hexdigest()
@api.route("/connection/profiles", methods=["GET"])
@with_revalidation_checking(
etag_factory=_connection_profiles_etag,
lastmodified_factory=_connection_profiles_lastmodified,
unless=lambda: request.values.get("force", "false") in valid_boolean_trues,
)
@no_firstrun_access
@Permissions.CONNECTION.require(403)
def connectionProfilesList():
all_profiles = connectionProfileManager.get_all()
return jsonify({"profiles": _convert_connection_profiles(all_profiles)})
@api.route("/connection/profiles/<string:identifier>", methods=["GET"])
@no_firstrun_access
@Permissions.CONNECTION.require(403)
def connectionProfilesGet(identifier):
profile = connectionProfileManager.get(identifier)
if profile is None:
return make_response(f"Unknown profile: {identifier}", 404)
else:
return jsonify({"profile": _convert_connection_profile(profile)})
@api.route("/connection/profiles/<string:identifier>", methods=["PUT"])
@no_firstrun_access
@Permissions.CONNECTION.require(403)
def connectionProfileSet(identifier):
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
json_data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if json_data is None:
return make_response("Malformed JSON body in request", 400)
if "profile" not in json_data:
return make_response("No profile included in request", 400)
allow_overwrite = json_data.get("overwrite", False)
make_default = json_data.get("default", False)
new_profile = json_data["profile"]
if "name" not in new_profile:
return make_response("Profile does not contain mandatory 'name' field", 400)
if "id" not in new_profile:
new_profile["id"] = identifier
profile = connectionProfileManager.to_profile(new_profile)
try:
connectionProfileManager.save(
profile, allow_overwrite=allow_overwrite, make_default=make_default
)
except InvalidProfileError:
return make_response("Profile is invalid", 400)
except SaveError:
return make_response(f"Profile {profile.id} could not be saved", 400)
except Exception as e:
logging.getLogger(__name__).exception(e)
return make_response(
f"Could not save profile due to an unexpected error: {e}", 500
)
else:
return jsonify({"profile": _convert_connection_profile(profile)})
@api.route("/connection/profiles/<string:identifier>", methods=["DELETE"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def connectionProfilesDelete(identifier):
current_profile = connectionProfileManager.get_current()
if current_profile and current_profile.id == identifier:
return make_response(
f"Cannot delete currently selected profile: {identifier}", 409
)
default_profile = connectionProfileManager.get_default()
if default_profile and default_profile.id == identifier:
return make_response(f"Cannot delete default profile: {identifier}", 409)
connectionProfileManager.remove(identifier)
return NO_CONTENT
@api.route("/connection/profiles/<string:identifier>", methods=["PATCH"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def connectionProfilesUpdate(identifier):
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
json_data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if json_data is None:
return make_response("Malformed JSON body in request", 400)
if "profile" not in json_data:
return make_response("No profile included in request", 400)
profile = connectionProfileManager.get(identifier)
if profile is None:
return make_response("Profile {} doesn't exist", 404)
profile_data = json_data["profile"]
make_default = profile_data.pop("default", False)
profile_data.pop("id", None)
merged_profile_data = dict_merge(profile.as_dict(), profile_data)
new_profile = connectionProfileManager.to_profile(merged_profile_data)
try:
saved_profile = connectionProfileManager.save(
new_profile, allow_overwrite=True, make_default=make_default
)
except InvalidProfileError:
return make_response("Profile is invalid", 400)
except SaveError:
return make_response(f"Profile {profile.id} could not be saved", 400)
except Exception as e:
return make_response(
f"Could not save profile due to an unexpected error: {e}", 500
)
else:
return jsonify({"profile": _convert_connection_profile(saved_profile)})
def _convert_connection_profiles(profiles):
result = {}
for identifier, profile in profiles.items():
result[identifier] = _convert_connection_profile(profile)
return result
def _convert_connection_profile(profile):
current = connectionProfileManager.get_current()
default = connectionProfileManager.get_default()
result = profile.as_dict()
result["current"] = profile.id == current.id if current is not None else False
result["default"] = profile.id == default.id if default is not None else False
return result
##~~ Protocols
@api.route("/connection/protocols", methods=["GET"])
@no_firstrun_access
@Permissions.CONNECTION.require(403)
def getProtocols():
return jsonify({"protocols": _get_protocols()})
##~~ Transports
@api.route("/connection/transports", methods=["GET"])
@no_firstrun_access
@Permissions.CONNECTION.require(403)
def getTransports():
return jsonify({"transports": _get_transports()})
##~~ Helpers
def _get_protocols():
protocols = []
for protocol in all_protocols():
protocols.append(
{
"name": protocol.name,
"key": protocol.key,
"options": get_param_structure(protocol.get_connection_options()),
"settings": get_param_structure(protocol.settings),
}
)
return protocols
def _get_transports():
transports = []
for transport in all_transports():
transports.append(
{
"name": transport.name,
"key": transport.key,
"options": get_param_structure(transport.get_connection_options()),
"settings": get_param_structure(transport.settings),
}
)
return transports
+14 -16
View File
@@ -63,6 +63,8 @@ def _create_lastmodified(path, recursive):
for storage in fileManager.registered_storages:
try:
lms.append(fileManager.last_modified(storage, recursive=recursive))
except NotImplementedError:
pass
except Exception:
logging.getLogger(__name__).exception(
"There was an error retrieving the last modified data from storage {}".format(
@@ -615,6 +617,7 @@ def uploadGcodeFile(target):
absFilename,
on_success=selectAndOrPrint,
tags={"source:api", "api:files.sd"},
user=user,
)
else:
selectAndOrPrint(filename, absFilename, destination)
@@ -827,23 +830,18 @@ def gcodeFileCommand(filename, target):
description="Printer is already printing, cannot select a new file",
)
printAfterLoading = False
if "print" in data and data["print"] in valid_boolean_trues:
with Permissions.PRINT.require(403):
if not printer.is_operational():
abort(
409,
description="Printer is not operational, cannot directly start printing",
)
printAfterLoading = True
print_after_loading = False
if "print" in data and data["print"] in valid_boolean_trues:
with Permissions.PRINT.require(403):
if not printer.is_operational():
abort(
409,
description="Printer is not operational, cannot directly start printing",
)
print_after_loading = True
sd = False
if target == FileDestinations.SDCARD:
filenameToSelect = filename
sd = True
else:
filenameToSelect = fileManager.path_on_disk(target, filename)
printer.select_file(filenameToSelect, sd, printAfterLoading, user)
job = fileManager.create_print_job(target, filename, user=user)
printer.select_job(job, start_printing=print_after_loading)
elif command == "unselect":
with Permissions.FILES_SELECT.require(403):
+128 -12
View File
@@ -11,10 +11,15 @@ from flask_login import current_user
import octoprint.plugin
import octoprint.util
from octoprint.access.permissions import Permissions
from octoprint.server import pluginManager, printer, userManager
from octoprint.server import pluginManager, userManager
from octoprint.server.api import api
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking
from octoprint.settings import settings, valid_boolean_trues
from octoprint.settings.parameters import (
get_param_dict,
get_param_structure,
save_params_to_settings,
)
# ~~ settings
@@ -31,7 +36,6 @@ def _etag(lm=None):
if lm is None:
lm = _lastmodified()
connection_options = printer.__class__.get_connection_options()
plugins = sorted(octoprint.plugin.plugin_manager().enabled_plugins)
plugin_settings = _get_plugin_settings()
@@ -64,9 +68,6 @@ def _etag(lm=None):
# output that are not stored in config.yaml
hash_update(repr(sorted_plugin_settings))
# connection options are also part of the settings
hash_update(repr(connection_options))
# if the list of plugins changes, the settings structure changes too
hash_update(repr(plugins))
@@ -93,8 +94,6 @@ def getSettings():
s = settings()
connectionOptions = printer.__class__.get_connection_options()
# NOTE: Remember to adjust the docs of the data model on the Settings API if anything
# is changed, added or removed here
@@ -161,12 +160,7 @@ def getSettings():
"bedZ": s.getFloat(["gcodeAnalysis", "bedZ"]),
},
"serial": {
"port": connectionOptions["portPreference"],
"baudrate": connectionOptions["baudratePreference"],
"exclusive": s.getBoolean(["serial", "exclusive"]),
"lowLatency": s.getBoolean(["serial", "lowLatency"]),
"portOptions": connectionOptions["ports"],
"baudrateOptions": connectionOptions["baudrates"],
"autoconnect": s.getBoolean(["serial", "autoconnect"]),
"timeoutConnection": s.getFloat(["serial", "timeout", "connection"]),
"timeoutDetectionFirst": s.getFloat(["serial", "timeout", "detectionFirst"]),
@@ -261,6 +255,14 @@ def getSettings():
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
"ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]),
},
"connection": {
"protocols": _get_protocol_settings(),
"transports": _get_transport_settings(),
"log": {
"connection": s.getBoolean(["connection", "log", "connection"]),
"commdebug": s.getBoolean(["connection", "log", "commdebug"]),
},
},
"folder": {
"uploads": s.getBaseFolder("uploads"),
"timelapse": s.getBaseFolder("timelapse"),
@@ -380,6 +382,50 @@ def _get_plugin_settings():
return data
def _get_protocol_settings():
from octoprint.comm.protocol import all_protocols
current = settings().get(["connection", "protocols"], merged=True)
result = {}
for protocol in all_protocols():
result[protocol.key] = get_param_dict(
current.get(protocol.key, {}), protocol.settings
)
return result
def _get_protocol_structure():
from octoprint.comm.protocol import all_protocols
result = {}
for protocol in all_protocols():
result[protocol.key] = get_param_structure(protocol.settings)
return result
def _get_transport_settings():
from octoprint.comm.transport import all_transports
current = settings().get(["connection", "transports"], merged=True)
result = {}
for transport in all_transports():
result[transport.key] = get_param_dict(
current.get(transport.key, {}), transport.settings
)
return result
def _get_transport_structure():
from octoprint.comm.transport import all_transports
result = {}
for transport in all_transports():
result[transport.key] = get_param_structure(transport.settings)
return result
@api.route("/settings", methods=["POST"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
@@ -397,6 +443,19 @@ def setSettings():
return getSettings()
@api.route("/settings/structure", methods=["GET"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def fetchSettingsStructure():
structure = {
"connection": {
"protocols": _get_protocol_structure(),
"transports": _get_transport_structure(),
},
}
return jsonify(structure)
@api.route("/settings/templates", methods=["GET"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
@@ -959,6 +1018,36 @@ def _saveSettings(data):
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
if "connection" in data:
if "log" in data["connection"]:
def toggle_log(log_type, logger_name):
old_setting = s.getBoolean(["connection", "log", log_type])
if log_type in data["connection"]["log"]:
s.setBoolean(
["connection", "log", log_type],
data["connection"]["log"][log_type] in valid_boolean_trues,
)
new_setting = s.getBoolean(["connection", "log", log_type])
if old_setting and not new_setting:
# disable logging
logging.getLogger(logger_name).debug("Disabling logging")
logging.getLogger(logger_name).setLevel(logging.INFO)
elif not old_setting and new_setting:
# enable logging
logging.getLogger(logger_name).setLevel(logging.DEBUG)
logging.getLogger(logger_name).debug("Enabling logging")
toggle_log("connection", "CONNECTION")
toggle_log("commdebug", "COMMDEBUG")
if "protocols" in data["connection"]:
_set_protocol_settings(data["connection"]["protocols"])
if "transports" in data["connection"]:
_set_transport_settings(data["connection"]["transports"])
if "temperature" in data:
if "profiles" in data["temperature"]:
result = []
@@ -1135,3 +1224,30 @@ def _saveSettings(data):
)
s.save(trigger_event=True)
def _set_protocol_settings(data):
from octoprint.comm.protocol import all_protocols
base_path = ["connection", "protocols"]
for protocol in all_protocols():
if protocol.key in data:
save_params_to_settings(
protocol.settings, settings(), base_path + [protocol.key]
)
def _set_transport_settings(data):
from octoprint.comm.transport import all_transports
base_path = ["connection", "transports"]
for transport in all_transports():
if transport.key in data:
save_params_to_settings(
data[transport.key],
transport.settings,
settings(),
base_path + [transport.key],
)
+2
View File
@@ -1722,6 +1722,7 @@ def collect_core_assets(preferred_stylesheet="css"):
"js/app/viewmodels/access.js",
"js/app/viewmodels/appearance.js",
"js/app/viewmodels/connection.js",
"js/app/viewmodels/connectionprofiles.js",
"js/app/viewmodels/control.js",
"js/app/viewmodels/files.js",
"js/app/viewmodels/loginstate.js",
@@ -1748,6 +1749,7 @@ def collect_core_assets(preferred_stylesheet="css"):
"js/app/client/access.js",
"js/app/client/browser.js",
"js/app/client/connection.js",
"js/app/client/connectionprofiles.js",
"js/app/client/control.js",
"js/app/client/files.js",
"js/app/client/job.js",
+14 -6
View File
@@ -975,13 +975,21 @@ def fetch_template_data(refresh=False):
# settings dialog
templates["settings"]["entries"] = {
"section_printer": (gettext("Printer"), None),
"serial": (
gettext("Serial Connection"),
"section_printer": (gettext("Connection & Printer"), None),
"connection": (
gettext("General"),
{
"template": "dialogs/settings/serialconnection.jinja2",
"_div": "settings_serialConnection",
"custom_bindings": False,
"template": "dialogs/settings/connection.jinja2",
"_div": "settings_connection",
"custom_bindings": True,
},
),
"connectionprofiles": (
gettext("Connection Profiles"),
{
"template": "dialogs/settings/connectionprofiles.jinja2",
"_div": "settings_connectionProfiles",
"custom_bindings": True,
},
),
"printerprofiles": (
@@ -23,7 +23,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import fnmatch
import logging
import os
import re
import sys
import time
from collections import ChainMap
@@ -35,6 +34,7 @@ from yaml import YAMLError
from octoprint.util import (
CaseInsensitiveSet,
atomic_write,
deprecated,
dict_merge,
fast_deepcopy,
is_hidden_path,
@@ -170,6 +170,12 @@ default_settings = {
# command specific flags
"triggerOkForM29": True,
},
"connection": {
"log": {"connection": False, "commdebug": False},
"profiles": {"default": None, "autoconnect_default": False},
"protocols": {},
"transports": {},
},
"server": {
"host": None,
"port": 5000,
@@ -286,6 +292,7 @@ default_settings = {
"plugins": None,
"slicingProfiles": None,
"printerProfiles": None,
"connectionProfiles": None,
"scripts": None,
"translations": None,
"generated": None,
@@ -339,7 +346,8 @@ default_settings = {
],
"settings": [
"section_printer",
"serial",
"connection",
"connectionprofiles",
"printerprofiles",
"temperatures",
"terminalfilters",
@@ -1119,510 +1127,20 @@ class Settings:
return False
def _migrate_config(self, config=None, persist=False):
from .migrations import all_migrations
if config is None:
config = self._config
persist = True
dirty = False
migrators = (
self._migrate_event_config,
self._migrate_reverse_proxy_config,
self._migrate_printer_parameters,
self._migrate_gcode_scripts,
self._migrate_core_system_commands,
self._migrate_serial_features,
self._migrate_resend_without_ok,
self._migrate_string_temperature_profile_values,
self._migrate_blocked_commands,
self._migrate_gcodeviewer_enabled,
)
for migrate in migrators:
dirty = migrate(config) or dirty
for migrate in all_migrations():
dirty = migrate(self, config) or dirty
if dirty and persist:
self.save(force=True)
def _migrate_gcode_scripts(self, config):
"""
Migrates an old development version of gcode scripts to the new template based format.
Added in 1.2.0
"""
dirty = False
if "scripts" in config:
if "gcode" in config["scripts"]:
if "templates" in config["scripts"]["gcode"]:
del config["scripts"]["gcode"]["templates"]
replacements = {
"disable_steppers": "M84",
"disable_hotends": "{% snippet 'disable_hotends' %}",
"disable_bed": "M140 S0",
"disable_fan": "M106 S0",
}
for name, script in config["scripts"]["gcode"].items():
self.saveScript("gcode", name, script.format(**replacements))
del config["scripts"]
dirty = True
return dirty
def _migrate_printer_parameters(self, config):
"""
Migrates the old "printer > parameters" data structure to the new printer profile mechanism.
Added in 1.2.0
"""
default_profile = (
config["printerProfiles"]["defaultProfile"]
if "printerProfiles" in config
and "defaultProfile" in config["printerProfiles"]
else {}
)
dirty = False
if "printerParameters" in config:
printer_parameters = config["printerParameters"]
if (
"movementSpeed" in printer_parameters
or "invertAxes" in printer_parameters
):
dirty = True
default_profile["axes"] = {"x": {}, "y": {}, "z": {}, "e": {}}
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 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 config["printerParameters"]["invertedAxes"]
if (
"numExtruders" in printer_parameters
or "extruderOffsets" in printer_parameters
):
dirty = True
if "extruder" not in default_profile:
default_profile["extruder"] = {}
if "numExtruders" in printer_parameters:
default_profile["extruder"]["count"] = printer_parameters[
"numExtruders"
]
del 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 config["printerParameters"]["extruderOffsets"]
if "bedDimensions" in printer_parameters:
dirty = True
bed_dimensions = printer_parameters["bedDimensions"]
if "volume" not in default_profile:
default_profile["volume"] = {}
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 config["printerParameters"]["bedDimensions"]
if dirty:
if "printerProfiles" not in config:
config["printerProfiles"] = {}
config["printerProfiles"]["defaultProfile"] = default_profile
return dirty
def _migrate_reverse_proxy_config(self, config):
"""
Migrates the old "server > baseUrl" and "server > scheme" configuration entries to
"server > reverseProxy > prefixFallback" and "server > reverseProxy > schemeFallback".
Added in 1.2.0
"""
if "server" in config and (
"baseUrl" in config["server"] or "scheme" in config["server"]
):
prefix = ""
if "baseUrl" in config["server"]:
prefix = config["server"]["baseUrl"]
del config["server"]["baseUrl"]
scheme = ""
if "scheme" in config["server"]:
scheme = config["server"]["scheme"]
del config["server"]["scheme"]
if "reverseProxy" not in config["server"] or not isinstance(
config["server"]["reverseProxy"], dict
):
config["server"]["reverseProxy"] = {}
if prefix:
config["server"]["reverseProxy"]["prefixFallback"] = prefix
if scheme:
config["server"]["reverseProxy"]["schemeFallback"] = scheme
self._logger.info("Migrated reverse proxy configuration to new structure")
return True
else:
return False
def _migrate_event_config(self, config):
"""
Migrates the old event configuration format of type "events > gcodeCommandTrigger" and
"event > systemCommandTrigger" to the new events format.
Added in 1.2.0
"""
if "events" in config and (
"gcodeCommandTrigger" in config["events"]
or "systemCommandTrigger" in config["events"]
):
self._logger.info("Migrating config (event subscriptions)...")
# migrate event hooks to new format
placeholderRe = re.compile(r"%\((.*?)\)s")
eventNameReplacements = {
"ClientOpen": "ClientOpened",
"TransferStart": "TransferStarted",
}
payloadDataReplacements = {
"Upload": {"data": "{file}", "filename": "{file}"},
"Connected": {"data": "{port} at {baudrate} baud"},
"FileSelected": {"data": "{file}", "filename": "{file}"},
"TransferStarted": {"data": "{remote}", "filename": "{remote}"},
"TransferDone": {"data": "{remote}", "filename": "{remote}"},
"ZChange": {"data": "{new}"},
"CaptureStart": {"data": "{file}"},
"CaptureDone": {"data": "{file}"},
"MovieDone": {"data": "{movie}", "filename": "{gcode}"},
"Error": {"data": "{error}"},
"PrintStarted": {"data": "{file}", "filename": "{file}"},
"PrintDone": {"data": "{file}", "filename": "{file}"},
}
def migrateEventHook(event, command):
# migrate placeholders
command = placeholderRe.sub("{__\\1}", command)
# migrate event names
if event in eventNameReplacements:
event = eventNameReplacements["event"]
# migrate payloads to more specific placeholders
if event in payloadDataReplacements:
for key in payloadDataReplacements[event]:
command = command.replace(
"{__%s}" % key, payloadDataReplacements[event][key]
)
# return processed tuple
return event, command
disableSystemCommands = False
if (
"systemCommandTrigger" in config["events"]
and "enabled" in config["events"]["systemCommandTrigger"]
):
disableSystemCommands = not config["events"]["systemCommandTrigger"][
"enabled"
]
disableGcodeCommands = False
if (
"gcodeCommandTrigger" in config["events"]
and "enabled" in config["events"]["gcodeCommandTrigger"]
):
disableGcodeCommands = not config["events"]["gcodeCommandTrigger"][
"enabled"
]
disableAllCommands = disableSystemCommands and disableGcodeCommands
newEvents = {"enabled": not disableAllCommands, "subscriptions": []}
if (
"systemCommandTrigger" in config["events"]
and "subscriptions" in config["events"]["systemCommandTrigger"]
):
for trigger in config["events"]["systemCommandTrigger"]["subscriptions"]:
if not ("event" in trigger and "command" in trigger):
continue
newTrigger = {"type": "system"}
if disableSystemCommands and not disableAllCommands:
newTrigger["enabled"] = False
newTrigger["event"], newTrigger["command"] = migrateEventHook(
trigger["event"], trigger["command"]
)
newEvents["subscriptions"].append(newTrigger)
if (
"gcodeCommandTrigger" in config["events"]
and "subscriptions" in config["events"]["gcodeCommandTrigger"]
):
for trigger in config["events"]["gcodeCommandTrigger"]["subscriptions"]:
if not ("event" in trigger and "command" in trigger):
continue
newTrigger = {"type": "gcode"}
if disableGcodeCommands and not disableAllCommands:
newTrigger["enabled"] = False
newTrigger["event"], newTrigger["command"] = migrateEventHook(
trigger["event"], trigger["command"]
)
newTrigger["command"] = newTrigger["command"].split(",")
newEvents["subscriptions"].append(newTrigger)
config["events"] = newEvents
self._logger.info(
"Migrated %d event subscriptions to new format and structure"
% len(newEvents["subscriptions"])
)
return True
else:
return False
def _migrate_core_system_commands(self, config):
"""
Migrates system commands for restart, reboot and shutdown as defined on OctoPi or
according to the official setup guide to new core system commands to remove
duplication.
If server commands for action is not yet set, migrates command. Otherwise only
deletes definition from custom system commands.
Added in 1.3.0
"""
changed = False
migration_map = {
"shutdown": "systemShutdownCommand",
"reboot": "systemRestartCommand",
"restart": "serverRestartCommand",
}
if (
"system" in config
and "actions" in config["system"]
and isinstance(config["system"]["actions"], (list, tuple))
):
actions = config["system"]["actions"]
to_delete = []
for index, spec in enumerate(actions):
action = spec.get("action")
command = spec.get("command")
if action is None or command is None:
continue
migrate_to = migration_map.get(action)
if migrate_to is not None:
if (
"server" not in config
or "commands" not in config["server"]
or migrate_to not in config["server"]["commands"]
):
if "server" not in config:
config["server"] = {}
if "commands" not in config["server"]:
config["server"]["commands"] = {}
config["server"]["commands"][migrate_to] = command
self._logger.info(
"Migrated {} action to server.commands.{}".format(
action, migrate_to
)
)
to_delete.append(index)
self._logger.info(
"Deleting {} action from configured system commands, superseded by server.commands.{}".format(
action, migrate_to
)
)
for index in reversed(to_delete):
actions.pop(index)
changed = True
if changed:
# let's make a backup of our current config, in case someone wants to roll back to an
# earlier version and needs to recover the former system commands for that
backup_path = self.backup("system_command_migration")
self._logger.info(
"Made a copy of the current config at {} to allow recovery of manual system command configuration".format(
backup_path
)
)
return changed
def _migrate_serial_features(self, config):
"""
Migrates feature flags identified as serial specific from the feature to the serial config tree and vice versa.
If a flag already exists in the target tree, only deletes the copy in the source tree.
Added in 1.3.7
"""
changed = False
FEATURE_TO_SERIAL = (
"waitForStartOnConnect",
"alwaysSendChecksum",
"neverSendChecksum",
"sendChecksumWithUnknownCommands",
"unknownCommandsNeedAck",
"sdRelativePath",
"sdAlwaysAvailable",
"swallowOkAfterResend",
"repetierTargetTemp",
"externalHeatupDetection",
"supportWait",
"ignoreIdenticalResends",
"identicalResendsCountdown",
"supportFAsCommand",
"firmwareDetection",
"blockWhileDwelling",
)
SERIAL_TO_FEATURE = ("autoUppercaseBlacklist",)
def migrate_key(key, source, target):
if source in config and key in config[source]:
if config.get(target) is None:
# make sure we have a serial tree
config[target] = {}
if key not in config[target]:
# only copy over if it's not there yet
config[target][key] = config[source][key]
# delete feature flag
del config[source][key]
return True
return False
for key in FEATURE_TO_SERIAL:
changed = migrate_key(key, "feature", "serial") or changed
for key in SERIAL_TO_FEATURE:
changed = migrate_key(key, "serial", "feature") or changed
if changed:
# let's make a backup of our current config, in case someone wants to roll back to an
# earlier version and needs a backup of their flags
backup_path = self.backup("serial_feature_migration")
self._logger.info(
"Made a copy of the current config at {} to allow recovery of serial feature flags".format(
backup_path
)
)
return changed
def _migrate_resend_without_ok(self, config):
"""
Migrates supportResendsWithoutOk flag from boolean to ("always", "detect", "never") value range.
True gets migrated to "always", False to "detect" (which is the new default).
Added in 1.3.7
"""
if (
"serial" in config
and "supportResendsWithoutOk" in config["serial"]
and config["serial"]["supportResendsWithoutOk"]
not in ("always", "detect", "never")
):
value = config["serial"]["supportResendsWithoutOk"]
if value:
config["serial"]["supportResendsWithoutOk"] = "always"
else:
config["serial"]["supportResendsWithoutOk"] = "detect"
return True
return False
def _migrate_string_temperature_profile_values(self, config):
"""
Migrates/fixes temperature profile wrongly saved with strings instead of ints as temperature values.
Added in 1.3.8
"""
if "temperature" in config and "profiles" in config["temperature"]:
profiles = config["temperature"]["profiles"]
if any(
map(
lambda x: not isinstance(x.get("extruder", 0), int)
or not isinstance(x.get("bed", 0), int),
profiles,
)
):
result = []
for profile in profiles:
try:
profile["extruder"] = int(profile["extruder"])
profile["bed"] = int(profile["bed"])
except ValueError:
pass
result.append(profile)
config["temperature"]["profiles"] = result
return True
return False
def _migrate_blocked_commands(self, config):
if "serial" in config and "blockM0M1" in config["serial"]:
blockM0M1 = config["serial"]["blockM0M1"]
blockedCommands = config["serial"].get("blockedCommands", [])
if blockM0M1:
blockedCommands = set(blockedCommands)
blockedCommands.add("M0")
blockedCommands.add("M1")
config["serial"]["blockedCommands"] = sorted(blockedCommands)
else:
config["serial"]["blockedCommands"] = sorted(
[v for v in blockedCommands if v not in ("M0", "M1")]
)
del config["serial"]["blockM0M1"]
return True
return False
def _migrate_gcodeviewer_enabled(self, config):
if (
"gcodeViewer" in config
and "enabled" in config["gcodeViewer"]
and not config["gcodeViewer"]["enabled"]
):
if "plugins" not in config:
config["plugins"] = {}
if "_disabled" not in config["plugins"]:
config["plugins"]["_disabled"] = []
config["plugins"]["_disabled"].append("gcodeviewer")
del config["gcodeViewer"]["enabled"]
return True
return False
def backup(self, suffix=None, path=None, ext=None, hidden=False):
import shutil
@@ -2161,6 +1679,153 @@ class Settings:
f.write(script)
class SubSettings:
def __init__(
self,
settings,
path,
defaults=None,
get_preprocessors=None,
set_preprocessors=None,
):
self.settings = settings
self.path = path
if defaults is not None:
self.defaults = self._path_structure(path, defaults)
else:
self.defaults = None
if get_preprocessors is None:
get_preprocessors = {}
self.get_preprocessors = self._path_structure(path, get_preprocessors)
if set_preprocessors is None:
set_preprocessors = {}
self.set_preprocessors = self._path_structure(path, set_preprocessors)
def prefix_path_in_args(args, index=0):
result = []
if index == 0:
result.append(self._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(self._prefix_path(args[index]))
result.extend(args_after)
return result
def add_getter_kwargs(kwargs):
if "defaults" not in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if "preprocessors" not in kwargs:
kwargs.update(preprocessors=self.get_preprocessors)
return kwargs
def add_setter_kwargs(kwargs):
if "defaults" not in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if "preprocessors" not in kwargs:
kwargs.update(preprocessors=self.set_preprocessors)
return kwargs
self.access_methods = {
"has": ("has", prefix_path_in_args, add_getter_kwargs),
"get": ("get", prefix_path_in_args, add_getter_kwargs),
"get_int": ("getInt", prefix_path_in_args, add_getter_kwargs),
"get_float": ("getFloat", prefix_path_in_args, add_getter_kwargs),
"get_boolean": ("getBoolean", prefix_path_in_args, add_getter_kwargs),
"set": ("set", prefix_path_in_args, add_setter_kwargs),
"set_int": ("setInt", prefix_path_in_args, add_setter_kwargs),
"set_float": ("setFloat", prefix_path_in_args, add_setter_kwargs),
"set_boolean": ("setBoolean", prefix_path_in_args, add_setter_kwargs),
"remove": ("remove", prefix_path_in_args, lambda x: x),
}
self.deprecated_access_methods = {
"getInt": "get_int",
"getFloat": "get_float",
"getBoolean": "get_boolean",
"setInt": "set_int",
"setFloat": "set_float",
"setBoolean": "set_boolean",
}
def _prefix_path(self, path=None):
if path is None:
path = list()
return self.path + path
def get_all_data(self, **kwargs):
merged = kwargs.get("merged", True)
asdict = kwargs.get("asdict", True)
defaults = kwargs.get("defaults", self.defaults)
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
kwargs.update(
{
"merged": merged,
"asdict": asdict,
"defaults": defaults,
"preprocessors": preprocessors,
}
)
return self.settings.get(self._prefix_path(), **kwargs)
def clean_all_data(self):
self.settings.remove(self._prefix_path())
def __getattr__(self, item):
all_access_methods = list(self.access_methods.keys()) + list(
self.deprecated_access_methods.keys()
)
if item in all_access_methods:
decorator = None
if item in self.deprecated_access_methods:
new = self.deprecated_access_methods[item]
decorator = deprecated(
f"{item} has been renamed to {new}",
stacklevel=2,
)
item = new
settings_name, args_mapper, kwargs_mapper = self.access_methods[item]
if hasattr(self.settings, settings_name) and callable(
getattr(self.settings, settings_name)
):
orig_func = getattr(self.settings, settings_name)
if decorator is not None:
orig_func = decorator(orig_func)
def _func(*args, **kwargs):
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
_func.__name__ = item
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
return _func
return getattr(self.settings, item)
@staticmethod
def _path_structure(path, data):
root = {}
if len(path) >= 1:
node = root
for entry in path[:-1]:
node[entry] = {}
node = node[entry]
node[path[-1]] = data
else:
root = data
return root
def _default_basedir(applicationName):
# taken from http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python
if sys.platform == "darwin":
+872
View File
@@ -0,0 +1,872 @@
import os
import re
import yaml
from octoprint.util import atomic_write
def all_migrations():
candidates = globals()
return [
candidates[x]
for x in candidates
if x.startswith("migrate_") and callable(candidates[x])
]
def migrate_gcode_scripts(settings, config):
"""
Migrates an old development version of gcode scripts to the new template based format.
Added in 1.2.0
"""
dirty = False
if "scripts" in config:
if "gcode" in config["scripts"]:
if "templates" in config["scripts"]["gcode"]:
del config["scripts"]["gcode"]["templates"]
replacements = {
"disable_steppers": "M84",
"disable_hotends": "{% snippet 'disable_hotends' %}",
"disable_bed": "M140 S0",
"disable_fan": "M106 S0",
}
for name, script in config["scripts"]["gcode"].items():
settings.saveScript("gcode", name, script.format(**replacements))
del config["scripts"]
dirty = True
return dirty
def migrate_printer_parameters(settings, config):
"""
Migrates the old "printer > parameters" data structure to the new printer profile mechanism.
Added in 1.2.0
"""
default_profile = (
config["printerProfiles"]["defaultProfile"]
if "printerProfiles" in config and "defaultProfile" in config["printerProfiles"]
else {}
)
dirty = False
if "printerParameters" in config:
printer_parameters = config["printerParameters"]
if "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters:
dirty = True
default_profile["axes"] = {"x": {}, "y": {}, "z": {}, "e": {}}
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 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 config["printerParameters"]["invertedAxes"]
if (
"numExtruders" in printer_parameters
or "extruderOffsets" in printer_parameters
):
dirty = True
if "extruder" not in default_profile:
default_profile["extruder"] = {}
if "numExtruders" in printer_parameters:
default_profile["extruder"]["count"] = printer_parameters["numExtruders"]
del 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 config["printerParameters"]["extruderOffsets"]
if "bedDimensions" in printer_parameters:
dirty = True
bed_dimensions = printer_parameters["bedDimensions"]
if "volume" not in default_profile:
default_profile["volume"] = {}
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 config["printerParameters"]["bedDimensions"]
if dirty:
if "printerProfiles" not in config:
config["printerProfiles"] = {}
config["printerProfiles"]["defaultProfile"] = default_profile
return dirty
def migrate_reverse_proxy_config(settings, config):
"""
Migrates the old "server > baseUrl" and "server > scheme" configuration entries to
"server > reverseProxy > prefixFallback" and "server > reverseProxy > schemeFallback".
Added in 1.2.0
"""
if "server" in config and (
"baseUrl" in config["server"] or "scheme" in config["server"]
):
prefix = ""
if "baseUrl" in config["server"]:
prefix = config["server"]["baseUrl"]
del config["server"]["baseUrl"]
scheme = ""
if "scheme" in config["server"]:
scheme = config["server"]["scheme"]
del config["server"]["scheme"]
if "reverseProxy" not in config["server"] or not isinstance(
config["server"]["reverseProxy"], dict
):
config["server"]["reverseProxy"] = {}
if prefix:
config["server"]["reverseProxy"]["prefixFallback"] = prefix
if scheme:
config["server"]["reverseProxy"]["schemeFallback"] = scheme
settings._logger.info("Migrated reverse proxy configuration to new structure")
return True
else:
return False
def migrate_event_config(settings, config):
"""
Migrates the old event configuration format of type "events > gcodeCommandTrigger" and
"event > systemCommandTrigger" to the new events format.
Added in 1.2.0
"""
if "events" in config and (
"gcodeCommandTrigger" in config["events"]
or "systemCommandTrigger" in config["events"]
):
settings._logger.info("Migrating config (event subscriptions)...")
# migrate event hooks to new format
placeholderRe = re.compile(r"%\((.*?)\)s")
eventNameReplacements = {
"ClientOpen": "ClientOpened",
"TransferStart": "TransferStarted",
}
payloadDataReplacements = {
"Upload": {"data": "{file}", "filename": "{file}"},
"Connected": {"data": "{port} at {baudrate} baud"},
"FileSelected": {"data": "{file}", "filename": "{file}"},
"TransferStarted": {"data": "{remote}", "filename": "{remote}"},
"TransferDone": {"data": "{remote}", "filename": "{remote}"},
"ZChange": {"data": "{new}"},
"CaptureStart": {"data": "{file}"},
"CaptureDone": {"data": "{file}"},
"MovieDone": {"data": "{movie}", "filename": "{gcode}"},
"Error": {"data": "{error}"},
"PrintStarted": {"data": "{file}", "filename": "{file}"},
"PrintDone": {"data": "{file}", "filename": "{file}"},
}
def migrateEventHook(event, command):
# migrate placeholders
command = placeholderRe.sub("{__\\1}", command)
# migrate event names
if event in eventNameReplacements:
event = eventNameReplacements["event"]
# migrate payloads to more specific placeholders
if event in payloadDataReplacements:
for key in payloadDataReplacements[event]:
command = command.replace(
"{__%s}" % key, payloadDataReplacements[event][key]
)
# return processed tuple
return event, command
disableSystemCommands = False
if (
"systemCommandTrigger" in config["events"]
and "enabled" in config["events"]["systemCommandTrigger"]
):
disableSystemCommands = not config["events"]["systemCommandTrigger"][
"enabled"
]
disableGcodeCommands = False
if (
"gcodeCommandTrigger" in config["events"]
and "enabled" in config["events"]["gcodeCommandTrigger"]
):
disableGcodeCommands = not config["events"]["gcodeCommandTrigger"]["enabled"]
disableAllCommands = disableSystemCommands and disableGcodeCommands
newEvents = {"enabled": not disableAllCommands, "subscriptions": []}
if (
"systemCommandTrigger" in config["events"]
and "subscriptions" in config["events"]["systemCommandTrigger"]
):
for trigger in config["events"]["systemCommandTrigger"]["subscriptions"]:
if not ("event" in trigger and "command" in trigger):
continue
newTrigger = {"type": "system"}
if disableSystemCommands and not disableAllCommands:
newTrigger["enabled"] = False
newTrigger["event"], newTrigger["command"] = migrateEventHook(
trigger["event"], trigger["command"]
)
newEvents["subscriptions"].append(newTrigger)
if (
"gcodeCommandTrigger" in config["events"]
and "subscriptions" in config["events"]["gcodeCommandTrigger"]
):
for trigger in config["events"]["gcodeCommandTrigger"]["subscriptions"]:
if not ("event" in trigger and "command" in trigger):
continue
newTrigger = {"type": "gcode"}
if disableGcodeCommands and not disableAllCommands:
newTrigger["enabled"] = False
newTrigger["event"], newTrigger["command"] = migrateEventHook(
trigger["event"], trigger["command"]
)
newTrigger["command"] = newTrigger["command"].split(",")
newEvents["subscriptions"].append(newTrigger)
config["events"] = newEvents
settings._logger.info(
"Migrated %d event subscriptions to new format and structure"
% len(newEvents["subscriptions"])
)
return True
else:
return False
def migrate_core_system_commands(settings, config):
"""
Migrates system commands for restart, reboot and shutdown as defined on OctoPi or
according to the official setup guide to new core system commands to remove
duplication.
If server commands for action is not yet set, migrates command. Otherwise only
deletes definition from custom system commands.
Added in 1.3.0
"""
changed = False
migration_map = {
"shutdown": "systemShutdownCommand",
"reboot": "systemRestartCommand",
"restart": "serverRestartCommand",
}
if (
"system" in config
and "actions" in config["system"]
and isinstance(config["system"]["actions"], (list, tuple))
):
actions = config["system"]["actions"]
to_delete = []
for index, spec in enumerate(actions):
action = spec.get("action")
command = spec.get("command")
if action is None or command is None:
continue
migrate_to = migration_map.get(action)
if migrate_to is not None:
if (
"server" not in config
or "commands" not in config["server"]
or migrate_to not in config["server"]["commands"]
):
if "server" not in config:
config["server"] = {}
if "commands" not in config["server"]:
config["server"]["commands"] = {}
config["server"]["commands"][migrate_to] = command
settings._logger.info(
"Migrated {} action to server.commands.{}".format(
action, migrate_to
)
)
to_delete.append(index)
settings._logger.info(
"Deleting {} action from configured system commands, superseded by server.commands.{}".format(
action, migrate_to
)
)
for index in reversed(to_delete):
actions.pop(index)
changed = True
if changed:
# let's make a backup of our current config, in case someone wants to roll back to an
# earlier version and needs to recover the former system commands for that
backup_path = settings.backup("system_command_migration")
settings._logger.info(
"Made a copy of the current config at {} to allow recovery of manual system command configuration".format(
backup_path
)
)
return changed
def migrate_serial_features(settings, config):
"""
Migrates feature flags identified as serial specific from the feature to the serial config tree and vice versa.
If a flag already exists in the target tree, only deletes the copy in the source tree.
Added in 1.3.7
"""
changed = False
FEATURE_TO_SERIAL = (
"waitForStartOnConnect",
"alwaysSendChecksum",
"neverSendChecksum",
"sendChecksumWithUnknownCommands",
"unknownCommandsNeedAck",
"sdRelativePath",
"sdAlwaysAvailable",
"swallowOkAfterResend",
"repetierTargetTemp",
"externalHeatupDetection",
"supportWait",
"ignoreIdenticalResends",
"identicalResendsCountdown",
"supportFAsCommand",
"firmwareDetection",
"blockWhileDwelling",
)
SERIAL_TO_FEATURE = ("autoUppercaseBlacklist",)
def migrate_key(key, source, target):
if source in config and key in config[source]:
if config.get(target) is None:
# make sure we have a serial tree
config[target] = {}
if key not in config[target]:
# only copy over if it's not there yet
config[target][key] = config[source][key]
# delete feature flag
del config[source][key]
return True
return False
for key in FEATURE_TO_SERIAL:
changed = migrate_key(key, "feature", "serial") or changed
for key in SERIAL_TO_FEATURE:
changed = migrate_key(key, "serial", "feature") or changed
if changed:
# let's make a backup of our current config, in case someone wants to roll back to an
# earlier version and needs a backup of their flags
backup_path = settings.backup("serial_feature_migration")
settings._logger.info(
"Made a copy of the current config at {} to allow recovery of serial feature flags".format(
backup_path
)
)
return changed
def migrate_resend_without_ok(settings, config):
"""
Migrates supportResendsWithoutOk flag from boolean to ("always", "detect", "never") value range.
True gets migrated to "always", False to "detect" (which is the new default).
Added in 1.3.7
"""
if (
"serial" in config
and "supportResendsWithoutOk" in config["serial"]
and config["serial"]["supportResendsWithoutOk"]
not in ("always", "detect", "never")
):
value = config["serial"]["supportResendsWithoutOk"]
if value:
config["serial"]["supportResendsWithoutOk"] = "always"
else:
config["serial"]["supportResendsWithoutOk"] = "detect"
return True
return False
def migrate_string_temperature_profile_values(settings, config):
"""
Migrates/fixes temperature profile wrongly saved with strings instead of ints as temperature values.
Added in 1.3.8
"""
if "temperature" in config and "profiles" in config["temperature"]:
profiles = config["temperature"]["profiles"]
if any(
map(
lambda x: not isinstance(x.get("extruder", 0), int)
or not isinstance(x.get("bed", 0), int),
profiles,
)
):
result = []
for profile in profiles:
try:
profile["extruder"] = int(profile["extruder"])
profile["bed"] = int(profile["bed"])
except ValueError:
pass
result.append(profile)
config["temperature"]["profiles"] = result
return True
return False
def migrate_blocked_commands(settings, config):
if "serial" in config and "blockM0M1" in config["serial"]:
blockM0M1 = config["serial"]["blockM0M1"]
blockedCommands = config["serial"].get("blockedCommands", [])
if blockM0M1:
blockedCommands = set(blockedCommands)
blockedCommands.add("M0")
blockedCommands.add("M1")
config["serial"]["blockedCommands"] = sorted(blockedCommands)
else:
config["serial"]["blockedCommands"] = sorted(
[v for v in blockedCommands if v not in ("M0", "M1")]
)
del config["serial"]["blockM0M1"]
return True
return False
def migrate_gcodeviewer_enabled(settings, config):
if (
"gcodeViewer" in config
and "enabled" in config["gcodeViewer"]
and not config["gcodeViewer"]["enabled"]
):
if "plugins" not in config:
config["plugins"] = {}
if "_disabled" not in config["plugins"]:
config["plugins"]["_disabled"] = []
config["plugins"]["_disabled"].append("gcodeviewer")
del config["gcodeViewer"]["enabled"]
return True
return False
def migrate_serial_to_connection_profile(settings, config):
if "serial" in config:
from octoprint.comm.connectionprofile import ConnectionProfile
from octoprint.comm.protocol.reprap import ReprapGcodeProtocol
from octoprint.comm.transport.serialtransport import SerialTransport
backup_path = settings.backup("serial_to_connection_profile")
settings._logger.info(
"Made a copy of the current config at {} to allow recovery of serial settings".format(
backup_path
)
)
def copy_config_to_profile(
config_path, profile_path, config, profile, converter=None
):
node = config
for p in config_path:
if p not in node:
return
node = node[p]
value = node
if callable(converter):
value = converter(value)
node = profile
for p in profile_path[:-1]:
if p not in node:
node[p] = {}
node = node[p]
node[profile_path[-1]] = value
printer_profile = config.get("printerProfiles", {"default": "_default"}).get(
"default", "_default"
)
protocol_parameters = {"flavor": "generic", "flavor_overrides": {}}
### flavor overrides
copy_config_to_profile(
["longRunningCommands"],
["flavor_overrides", "long_running_commands"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["blockedCommands"],
["flavor_overrides", "blocked_commands"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["pausingCommands"],
["flavor_overrides", "pausing_commands"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["emergencyCommands"],
["flavor_overrides", "emergency_commands"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["checksumRequiringCommands"],
["flavor_overrides", "checksum_requiring_commands"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["supportResendsWithoutOk"],
["flavor_overrides", "trigger_ok_after_resend"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["unknownCommandsNeedAck"],
["flavor_overrides", "unknown_requires_ack"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["sendChecksumWithUnknownCommands"],
["flavor_overrides", "unknown_with_checksum"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["externalHeatupDetection"],
["flavor_overrides", "detect_external_heatup"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["blockWhileDwelling"],
["flavor_overrides", "block_while_dwelling"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["sdRelativePath"],
["flavor_overrides", "sd_relative_path"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["sdAlwaysAvailable"],
["flavor_overrides", "sd_always_available"],
config["serial"],
protocol_parameters,
)
if (
"alwaysSendChecksum" in config["serial"]
or "neverSendChecksum" in config["serial"]
):
always = config["serial"].get("alwaysSendChecksum", False)
never = config["serial"].get("neverSendChecksum", False)
if not always and not never:
protocol_parameters["flavor_overrides"]["send_checksum"] = "printing"
elif always:
protocol_parameters["flavor_overrides"]["send_checksum"] = "always"
elif never:
protocol_parameters["flavor_overrides"]["send_checksum"] = "never"
### error handling
copy_config_to_profile(
["sendM112OnError"],
["error_handling", "send_m112"],
config["serial"],
protocol_parameters,
)
if (
"disconnectOnErrors" in config["serial"]
or "ignoreErrorsFromFirmware" in config["serial"]
):
disconnect = config["serial"].get("disconnectOnErrors", True)
ignore = config["serial"].get("ignoreErrorsFromFirmware", False)
if ignore:
protocol_parameters["error_handling"] = {"firmware_errors": "ignore"}
elif not disconnect:
protocol_parameters["error_handling"] = {"firmware_errors": "cancel"}
else:
protocol_parameters["error_handling"] = {"firmware_errors": "disconnect"}
### pausing
copy_config_to_profile(
["logPositionOnPause"],
["pausing", "log_position_on_pause"],
config["serial"],
protocol_parameters,
)
### cancelling
copy_config_to_profile(
["logPositionOnCancel"],
["cancelling", "log_position_on_cancel"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["abortHeatupOnCancel"],
["cancelling", "abort_heatups"],
config["serial"],
protocol_parameters,
)
### timeouts
copy_config_to_profile(
["timeout", "communication"],
["timeouts", "communication_timeout_normal"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["timeout", "communicationBusy"],
["timeouts", "communication_timeout_busy"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["timeout", "connection"],
["timeouts", "connection_timeout"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["timeout", "detection"],
["timeouts", "detection_timeout"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["timeout", "positionLogWait"],
["timeouts", "position_log_wait"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["timeout", "baudrateDetectionPause"],
["timeouts", "baudrate_detection_pause"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["timeout", "resendOk"],
["timeouts", "resendok_timeout"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["maxCommunicationTimeouts", "idle"],
["timeouts", "max_consecutive_timeouts_idle"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["maxCommunicationTimeouts", "printing"],
["timeouts", "max_consecutive_timeouts_printing"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["maxCommunicationTimeouts", "long"],
["timeouts", "max_consecutive_timeouts_long"],
config["serial"],
protocol_parameters,
)
### intervals
copy_config_to_profile(
["timeout", "temperature"],
["intervals", "temperature_interval_idle"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["timeout", "temperatureTargetSet"],
["intervals", "temperature_interval_target"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["timeout", "temperatureAutoreport"],
["intervals", "temperature_interval_auto"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["timeout", "sdStatus"],
["intervals", "sdstatus_interval_normal"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["timeout", "sdStatusAutoreport"],
["intervals", "sdstatus_interval_auto"],
config["serial"],
protocol_parameters,
)
### capabilities
copy_config_to_profile(
["capabilities", "autoreport_temp"],
["capabilities", "autoreport_temp"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["capabilities", "autoreport_sdstatus"],
["capabilities", "autoreport_sd_status"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["capabilities", "emergency_parser"],
["capabilities", "emergency_parser"],
config["serial"],
protocol_parameters,
)
copy_config_to_profile(
["capabilities", "busy_protocol"],
["capabilities", "busy_protocol"],
config["serial"],
protocol_parameters,
)
# TODO: chamber temp?
# TODO: maxWritePasses
# TODO: helloCommand
# TODO: terminalLogSize
# TODO: logResends
# TODO: waitForStartOnConnect
# TODO: maxNotSdPrinting
# TODO: swallowOkAfterResend
# TODO: repetierTargetTemp
# TODO: supportWait
# TODO: ignoreIdenticalResends
# TODO: identicalResendsCountdown
# TODO: supportFAsCommand
# TODO: firmwareDetection
# TODO: triggerOkForM29
### logging
if "log" in config["serial"]:
if "connection" not in config["serial"]:
config["serial"]["connection"] = {}
if "log" not in config["serial"]["connection"]:
config["serial"]["connection"]["log"] = {}
config["serial"]["connection"]["log"]["connection"] = config["serial"]["log"]
port = config["serial"].get("port")
transport_parameters = {}
if port == "VIRTUAL":
# special case for the virtual printer plugin
transport = "virtual"
else:
transport = SerialTransport.key
copy_config_to_profile(
["port"],
["port"],
config["serial"],
transport_parameters,
converter=lambda x: None if x == "AUTO" else x,
)
copy_config_to_profile(
["baudrate"], ["baudrate"], config["serial"], transport_parameters
)
copy_config_to_profile(
["exclusive"], ["exclusive"], config["serial"], transport_parameters
)
copy_config_to_profile(
["useParityWorkaround"],
["parity_workaround"],
config["serial"],
transport_parameters,
)
profile = ConnectionProfile(
"migrated",
name="Migrated from serial settings",
printer_profile=printer_profile,
protocol=ReprapGcodeProtocol.key,
protocol_parameters=protocol_parameters,
transport=transport,
transport_parameters=transport_parameters,
)
try:
with atomic_write(
os.path.join(
settings.getBaseFolder("connectionProfiles"), "migrated.profile"
),
mode="wt",
max_permissions=0o666,
) as f:
yaml.safe_dump(
profile.as_dict(),
f,
default_flow_style=False,
indent=2,
allow_unicode=True,
)
if "connection" not in config:
config["connection"] = {}
if "profiles" not in config["connection"]:
config["connection"]["profiles"] = {}
if not config["connection"]["profiles"]["default"]:
config["connection"]["profiles"]["default"] = "migrated"
except Exception:
settings._logger.exception(
"Error while trying to save migrated connection profile"
)
+379
View File
@@ -0,0 +1,379 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
def register_settings_overlay(settings, path, params, key=None):
overlay = {}
node = overlay
for p in path:
node[p] = {}
node = node[p]
node.update(**get_param_defaults(params))
# our overlay is now complete, register it
return settings.add_overlay(overlay, key=key)
def get_param_defaults(options):
result = {}
for option in options:
if option.type == "group":
result[option.name] = get_param_defaults(option.params)
elif option.type == "presetchoice":
result[option.name] = option.default
result[option.group.name] = option.defaults
elif option.type == "conditionalgroup":
result[option.name] = option.default
result.update(get_param_defaults(option.groups.get(option.default, [])))
else:
result[option.name] = option.default
return result
def get_param_dict(data, options):
options_by_name = {option.name: option for option in options}
result = get_param_defaults(options)
for key, value in data.items():
if key not in options_by_name:
continue
option = options_by_name[key]
result[key] = option.convert(value)
if option.type == "conditionalgroup":
result.update(get_param_dict(data, option.groups[value]))
return result
def get_param_structure(options):
return [option.as_dict() for option in options]
def save_params_to_settings(data, options, settings, path):
if data is None:
data = {}
for option in options:
if option.type == "group":
save_params_to_settings(
data.get(option.name), option.params, settings, path + [option.name]
)
elif option.type == "presetchoice":
save_params_to_settings(
data.get(option.group.name),
option.group.params,
settings,
path + [option.group.name],
)
elif option.type == "conditionalgroup":
save_params_to_settings(
data.get(option.name),
option.groups[option.value],
settings,
path + [option.name],
)
else:
save_param_to_settings(
data.get(option.name), option, settings, path + [option.name]
)
def save_param_to_settings(value, option, settings, path):
if value is None:
return
if option.type == "integer":
settings.setInt(path, value)
elif option.type == "float":
settings.setFloat(path, value)
elif option.type == "boolean":
settings.setBoolean(path, value)
else:
settings.set(path, value)
class ParamType:
type = "generic"
def __init__(
self,
name,
title,
default=None,
advanced=False,
expert=False,
warning=False,
labels=None,
help=None,
):
if labels is None:
labels = []
self.name = name
self.title = title
self.default = default
self.advanced = advanced
self.expert = expert
self.warning = warning
self.labels = labels
self.help = help
def as_dict(self):
return {
"name": self.name,
"title": self.title,
"default": self.default,
"advanced": self.advanced,
"expert": self.expert,
"warning": self.warning,
"labels": self.labels,
"help": self.help,
"type": self.type,
}
def convert(self, value):
return value
def __repr__(self):
return (
f"{self.__class__.__name__}("
+ ", ".join(
[
f"{key}={value!r}"
for key, value in self.__dict__.items()
if not key.startswith("_")
]
)
+ ")"
)
class TextType(ParamType):
type = "text"
def convert(self, value):
if isinstance(value, bytes):
value = value.decode("utf-8", "replace")
return value
class UrlType(TextType):
type = "url"
class IntegerType(ParamType):
type = "integer"
def __init__(self, name, title, min=None, max=None, unit=None, **kwargs):
self.min = min
self.max = max
self.unit = unit
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update({"min": self.min, "max": self.max, "unit": self.unit})
return result
def convert(self, value):
try:
value = int(value)
except ValueError:
raise ValueError(f"value {value!r} is not a valid integer")
if self.min is not None and value < self.min:
raise ValueError(f"value {value} is less than minimum valid value {self.min}")
if self.max is not None and value > self.max:
raise ValueError(
f"value {value} is greater than maximum valid value {self.max}"
)
return value
class FloatType(ParamType):
type = "float"
def __init__(self, name, title, min=None, max=None, unit=None, **kwargs):
self.min = min
self.max = max
self.unit = unit
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update({"min": self.min, "max": self.max, "unit": self.unit})
return result
def convert(self, value):
try:
value = float(value)
except ValueError:
raise ValueError(f"value {value!r} is not a valid float")
if self.min is not None and value < self.min:
raise ValueError(f"value {value} is less than minimum valid value {self.min}")
if self.max is not None and value > self.max:
raise ValueError(
f"value {value} is greater than maximum valid value {self.max}"
)
return value
class BooleanType(ParamType):
type = "boolean"
def convert(self, value):
try:
value = bool(value)
except ValueError:
raise ValueError(f"value {value!r} is not a valid boolean")
return value
class ChoiceType(ParamType):
type = "choice"
def __init__(self, name, title, choices, placeholder=None, **kwargs):
self.choices = choices
self.placeholder = placeholder
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(
{
"choices": list(map(lambda x: x.as_dict(), self.choices)),
"placeholder": self.placeholder,
}
)
return result
class SmallChoiceType(ChoiceType):
type = "smallchoice"
class PresetChoiceType(ChoiceType):
type = "presetchoice"
def __init__(self, name, title, choices, group, defaults=None, **kwargs):
if defaults is None:
defaults = {}
ChoiceType.__init__(self, name, title, choices, **kwargs)
self.group = group
self.defaults = defaults
def as_dict(self):
result = ChoiceType.as_dict(self)
result["group"] = self.group.as_dict()
result["defaults"] = self.defaults
return result
class ConditionalGroup(ChoiceType):
type = "conditionalgroup"
def __init__(self, name, title, choices, groups, **kwargs):
ChoiceType.__init__(self, name, title, choices, **kwargs)
self.groups = groups
def as_dict(self):
result = ChoiceType.as_dict(self)
result["groups"] = {
key: list(map(lambda x: x.as_dict(), value))
for key, value in self.groups.items()
}
return result
class SuggestionType(ParamType):
type = "suggestion"
def __init__(self, name, title, suggestions, factory, **kwargs):
self.suggestions = suggestions
self.factory = factory
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update({"suggestions": list(map(lambda x: x.as_dict(), self.suggestions))})
return result
class ListType(ParamType):
type = "list"
def __init__(self, name, title, sep=",", factory=None, **kwargs):
if factory is None:
factory = lambda x: x
self.factory = factory
self.sep = sep
if kwargs.get("default") is None:
kwargs["default"] = []
ParamType.__init__(self, name, title, **kwargs)
def convert(self, value):
if isinstance(value, str):
items = map(str.strip, value.split(self.sep))
elif isinstance(value, list):
items = value
else:
raise ValueError(
"value {!r} must be either a self.sep separated string or a list".format(
value
)
)
return list(map(self.factory, items))
class SmallListType(ListType):
type = "smalllist"
class ParamGroup(ParamType):
type = "group"
def __init__(self, name, title, params, **kwargs):
ParamType.__init__(self, name, title, **kwargs)
self.params = params
def as_dict(self):
result = ParamType.as_dict(self)
result["params"] = [x.as_dict() for x in self.params]
return result
def convert(self, value):
if not isinstance(value, dict):
raise ValueError(f"value {value!r} must be a dict")
return {k: v.convert() for k, v in value.items()}
class Value:
def __init__(self, value, title=None, warning=False, labels=None, help=None):
if labels is None:
labels = []
self.value = value
self.title = title if title else value
self.warning = warning
self.labels = labels
self.help = help
def as_dict(self):
return {
"value": self.value,
"title": self.title,
"warning": self.warning,
"labels": self.labels,
"help": self.help,
}
+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,.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;*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.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.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:focus,.btn:hover{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:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;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{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*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.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.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:focus,.btn:hover{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:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;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{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
@@ -6,6 +6,9 @@
}
})(this, function (OctoPrintClient) {
var url = "api/connection";
var optionsUrl = url + "/options";
var protocolsUrl = url + "/protocols";
var transportsUrl = url + "/transports";
var OctoPrintConnectionClient = function (base) {
this.base = base;
@@ -27,6 +30,18 @@
return this.base.issueCommand(url, "fake_ack", {}, opts);
};
OctoPrintConnectionClient.prototype.getOptions = function (opts) {
return this.base.get(optionsUrl, opts);
};
OctoPrintConnectionClient.prototype.getProtocols = function (opts) {
return this.base.get(protocolsUrl, opts);
};
OctoPrintConnectionClient.prototype.getTransports = function (opts) {
return this.base.get(transportsUrl, opts);
};
OctoPrintClient.registerComponent("connection", OctoPrintConnectionClient);
return OctoPrintConnectionClient;
});
@@ -0,0 +1,57 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient", "jquery"], factory);
} else {
factory(global.OctoPrintClient, global.$);
}
})(this, function (OctoPrintClient, $) {
var url = "api/connection/profiles";
var profileUrl = function (profile) {
return url + "/" + profile;
};
var OctoPrintConnectionProfileClient = function (base) {
this.base = base;
};
OctoPrintConnectionProfileClient.prototype.list = function (opts) {
return this.base.get(url, opts);
};
OctoPrintConnectionProfileClient.prototype.get = function (id, opts) {
return this.base.get(profileUrl(id), opts);
};
OctoPrintConnectionProfileClient.prototype.set = function (
id,
profile,
allowOverwrite,
makeDefault,
opts
) {
profile = profile || {};
var data = {profile: profile, overwrite: allowOverwrite, default: makeDefault};
return this.base.putJson(profileUrl(id), data, opts);
};
OctoPrintConnectionProfileClient.prototype.update = function (id, profile, opts) {
profile = profile || {};
var data = {profile: profile};
return this.base.patchJson(profileUrl(id), data, opts);
};
OctoPrintConnectionProfileClient.prototype.delete = function (id, opts) {
return this.base.delete(profileUrl(id), opts);
};
OctoPrintClient.registerComponent(
"connectionprofiles",
OctoPrintConnectionProfileClient
);
return OctoPrintConnectionProfileClient;
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,106 @@
$(function () {
function ConnectionProfilesViewModel(parameters) {
var self = this;
self.connection = parameters[0];
self.requestInProgress = ko.observable(false);
self.profiles = new ItemListHelper(
"connectionProfiles",
{
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.connection.availableConnectionProfiles.subscribe(function () {
var profiles = self.connection.availableConnectionProfiles();
self.profiles.updateItems(profiles);
});
self.connection.preferredConnectionProfile.subscribe(function (profileId) {
self.defaultProfile(profileId);
});
self.connection.selectedConnectionProfile.subscribe(function (profile) {
var profileId = profile ? profile.id : undefined;
self.currentProfile(profileId);
});
self.addProfile = function () {
return self.connection.editor.showAddDialog().done(function () {
self.requestInProgress(true);
self.connection.requestData().always(function () {
self.requestInProgress(false);
});
});
};
self.editProfile = function (data) {
return self.connection.editor.showEditDialog(data).done(function () {
self.requestInProgress(true);
self.connection.requestData().always(function () {
self.requestInProgress(false);
});
});
};
self.canMakeDefault = function (data) {
return !data.isDefault();
};
self.makeDefault = function (data) {
self.requestInProgress(true);
return OctoPrint.connectionprofiles
.update(data.id, {default: true})
.done(function () {
self.connection.requestData().always(function () {
self.requestInProgress(false);
});
});
};
self.canRemove = function (data) {
return !data.isCurrent() && !data.isDefault();
};
self.removeProfile = function (data) {
var proceed = function () {
self.requestInProgress(true);
OctoPrint.connectionprofiles.delete(data.id).done(function () {
self.connection.requestData().always(function () {
self.requestInProgress(false);
});
});
};
showConfirmationDialog({
message: _.sprintf(
gettext(
'You are about to delete the connection profile "%(profile)s".'
),
{profile: data.name}
),
onproceed: proceed
});
};
}
OCTOPRINT_VIEWMODELS.push({
construct: ConnectionProfilesViewModel,
dependencies: ["connectionViewModel"],
elements: ["#settings_connectionProfiles"]
});
});
@@ -8,7 +8,7 @@ $(function () {
self.about = parameters[3];
// TODO: remove in upcoming version, this is only for backwards compatibility
self.users = parameters[4];
self.users = parameters[5];
// use this promise to do certain things once the SettingsViewModel has processed
// its first request
@@ -248,6 +248,9 @@ $(function () {
self.serial_resendRatioThreshold = ko.observable(100);
self.serial_resendRatioStart = ko.observable(100);
self.connection_log_connection = ko.observable(undefined);
self.connection_log_commdebug = ko.observable(undefined);
self.folder_uploads = ko.observable(undefined);
self.folder_timelapse = ko.observable(undefined);
self.folder_timelapseTmp = ko.observable(undefined);
+30
View File
@@ -0,0 +1,30 @@
(function (factory) {
// Module systems magic dance.
if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
// CommonJS or Node: hard-coded dependency on "knockout"
factory(require("knockout"), require("markdown-it"));
} else if (typeof define === "function" && define["amd"]) {
// AMD anonymous module with hard-coded dependency on "knockout"
define(["knockout"], ["markdown-it"], factory);
} else {
// <script> tag: use the global `ko` object, attaching a `mapping` property
factory(ko, markdownit);
}
}(function (ko, markdown) {
ko.markdown = markdown();
ko.bindingHandlers.markdown = {
update: function (element, valueAccessor) {
var markdownData = ko.unwrap(valueAccessor());
if (markdownData) element.innerHTML = ko.markdown.render(markdownData);
}
};
ko.bindingHandlers.markdownInline = {
update: function (element, valueAccessor) {
var markdownData = ko.unwrap(valueAccessor());
if (markdownData) element.innerHTML = ko.markdown.renderInline(markdownData);
}
};
}));
+1
View File
@@ -0,0 +1 @@
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).markdownit=e()}}(function(){return function o(i,a,c){function l(t,e){if(!a[t]){if(!i[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(u)return u(t,!0);var n=new Error("Cannot find module '"+t+"'");throw n.code="MODULE_NOT_FOUND",n}var s=a[t]={exports:{}};i[t][0].call(s.exports,function(e){var r=i[t][1][e];return l(r||e)},s,s.exports,o,i,a,c)}return a[t].exports}for(var u="function"==typeof require&&require,e=0;e<c.length;e++)l(c[e]);return l}({1:[function(e,r,t){"use strict";r.exports=e("entities/maps/entities.json")},{"entities/maps/entities.json":52}],2:[function(e,r,t){"use strict";r.exports=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","meta","nav","noframes","ol","optgroup","option","p","param","section","source","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"]},{}],3:[function(e,r,t){"use strict";var n="<[A-Za-z][A-Za-z0-9\\-]*(?:\\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\\s*=\\s*(?:[^\"'=<>`\\x00-\\x20]+|'[^']*'|\"[^\"]*\"))?)*\\s*\\/?>",s="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",o=new RegExp("^(?:"+n+"|"+s+"|\x3c!----\x3e|\x3c!--(?:-?[^>-])(?:-?[^-])*--\x3e|<[?].*?[?]>|<![A-Z]+\\s+[^>]*>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>)"),i=new RegExp("^(?:"+n+"|"+s+")");r.exports.HTML_TAG_RE=o,r.exports.HTML_OPEN_CLOSE_TAG_RE=i},{}],4:[function(e,r,t){"use strict";var n=Object.prototype.hasOwnProperty;function i(e,r){return n.call(e,r)}function a(e){return!(55296<=e&&e<=57343)&&(!(64976<=e&&e<=65007)&&(65535!=(65535&e)&&65534!=(65535&e)&&(!(0<=e&&e<=8)&&(11!==e&&(!(14<=e&&e<=31)&&(!(127<=e&&e<=159)&&!(1114111<e)))))))}function c(e){if(65535<e){var r=55296+((e-=65536)>>10),t=56320+(1023&e);return String.fromCharCode(r,t)}return String.fromCharCode(e)}var s=/\\([!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])/g,o=new RegExp(s.source+"|"+/&([a-z#][a-z0-9]{1,31});/gi.source,"gi"),l=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i,u=e("./entities");var p=/[&<>"]/,h=/[&<>"]/g,f={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function d(e){return f[e]}var m=/[.?*+^$[\]\\(){}|-]/g;var _=e("uc.micro/categories/P/regex");t.lib={},t.lib.mdurl=e("mdurl"),t.lib.ucmicro=e("uc.micro"),t.assign=function(t){return Array.prototype.slice.call(arguments,1).forEach(function(r){if(r){if("object"!=typeof r)throw new TypeError(r+"must be object");Object.keys(r).forEach(function(e){t[e]=r[e]})}}),t},t.isString=function(e){return"[object String]"===(r=e,Object.prototype.toString.call(r));var r},t.has=i,t.unescapeMd=function(e){return e.indexOf("\\")<0?e:e.replace(s,"$1")},t.unescapeAll=function(e){return e.indexOf("\\")<0&&e.indexOf("&")<0?e:e.replace(o,function(e,r,t){return r||(n=e,o=0,i(u,s=t)?u[s]:35===s.charCodeAt(0)&&l.test(s)&&a(o="x"===s[1].toLowerCase()?parseInt(s.slice(2),16):parseInt(s.slice(1),10))?c(o):n);var n,s,o})},t.isValidEntityCode=a,t.fromCodePoint=c,t.escapeHtml=function(e){return p.test(e)?e.replace(h,d):e},t.arrayReplaceAt=function(e,r,t){return[].concat(e.slice(0,r),t,e.slice(r+1))},t.isSpace=function(e){switch(e){case 9:case 32:return!0}return!1},t.isWhiteSpace=function(e){if(8192<=e&&e<=8202)return!0;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:case 5760:case 8239:case 8287:case 12288:return!0}return!1},t.isMdAsciiPunct=function(e){switch(e){case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:case 58:case 59:case 60:case 61:case 62:case 63:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 124:case 125:case 126:return!0;default:return!1}},t.isPunctChar=function(e){return _.test(e)},t.escapeRE=function(e){return e.replace(m,"\\$&")},t.normalizeReference=function(e){return e.trim().replace(/\s+/g," ").toUpperCase()}},{"./entities":1,mdurl:58,"uc.micro":65,"uc.micro/categories/P/regex":63}],5:[function(e,r,t){"use strict";t.parseLinkLabel=e("./parse_link_label"),t.parseLinkDestination=e("./parse_link_destination"),t.parseLinkTitle=e("./parse_link_title")},{"./parse_link_destination":6,"./parse_link_label":7,"./parse_link_title":8}],6:[function(e,r,t){"use strict";var a=e("../common/utils").isSpace,c=e("../common/utils").unescapeAll;r.exports=function(e,r,t){var n,s,o=r,i={ok:!1,pos:0,lines:0,str:""};if(60===e.charCodeAt(r)){for(r++;r<t;){if(10===(n=e.charCodeAt(r))||a(n))return i;if(62===n)return i.pos=r+1,i.str=c(e.slice(o+1,r)),i.ok=!0,i;92===n&&r+1<t?r+=2:r++}return i}for(s=0;r<t&&32!==(n=e.charCodeAt(r))&&!(n<32||127===n);)if(92===n&&r+1<t)r+=2;else{if(40===nLine truncated
+62 -16
View File
@@ -444,6 +444,40 @@ table {
width: 80px;
.actioncol;
}
// Connection profiles
&.settings_connectionProfiles_profiles_default {
width: 16px;
text-align: center;
}
&.settings_connectionProfiles_profiles_name {
width: 200px;
text-overflow: ellipsis;
text-align: left;
}
&.settings_connectionProfiles_profiles_details {
table.settings_connectionProfiles_profiles_details_table {
font-size: 0.8em;
margin-bottom: 0;
.settings_connectionProfiles_profiles_details_key {
width: 100px;
}
th,
td {
border: 0;
padding: 0;
}
}
}
&.settings_connectionProfiles_profiles_action {
width: 80px;
.actioncol;
}
}
}
@@ -1019,6 +1053,34 @@ ul.dropdown-menu li a {
}
}
#connectionprofiles_editor_dialog,
#connection_protocol_dialog,
#connection_transport_dialog,
#settings_connection {
.control-group {
position: relative;
}
.control-undo {
position: absolute;
top: 5px;
right: 0;
line-height: 20px;
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
.controls {
padding-right: 20px;
}
}
/** Notifications */
.ui-pnotify {
@@ -1384,22 +1446,6 @@ _:future,
width: inherit;
}
}
.btn-group:first-child {
.btn:first-child {
-webkit-border-radius: 4px 0 0 4px;
-moz-border-radius: 4px 0 0 4px;
border-radius: 4px 0 0 4px;
}
}
.btn-group {
.btn:first-child {
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
}
}
// block level inputs with add-ons
@@ -0,0 +1,33 @@
<div id="connection_protocol_dialog" class="modal hide fade-in">
<div class="modal-header">
<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Protocol Parameters') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<!--ko let: { profile: { protocolParameters: protocolParameters, expertProtocolParameters: expertProtocolParameters } }-->
{% include 'snippets/connectionprofiles/protocolEditor.jinja2' %}
<!--/ko-->
</form>
</div>
<div class="modal-footer">
<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</a>
</div>
</div>
<div id="connection_transport_dialog" class="modal hide fade">
<div class="modal-header">
<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Transport Parameters') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" action="javascript:void(0)">
<!--ko let: { profile: { transportParameters: transportParameters, expertTransportParameters: expertTransportParameters } }-->
{% include 'snippets/connectionprofiles/transportEditor.jinja2' %}
<!--/ko-->
</form>
</div>
<div class="modal-footer">
<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</a>
</div>
</div>
@@ -0,0 +1,90 @@
<div id="connectionprofiles_editor_dialog" class="modal hide fade-in">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 data-bind="text: editor.dialogTitle">{{ _('Edit connection profile') }}</h3>
</div>
<div class="modal-body">
<div class="full-sized-box">
<form class="form-horizontal" action="javascript:void(0)">
<ul class="nav nav-pills">
<li class="active"><a href="#connectionprofiles_editor_dialog_general" data-toggle="tab">{{ _('General') }}</a></li>
<li><a href="#connectionprofiles_editor_dialog_printer" data-toggle="tab">{{ _('Printer profile') }}</a></li>
<li><a href="#connectionprofiles_editor_dialog_protocol" data-toggle="tab">{{ _('Protocol') }}</a></li>
<li><a href="#connectionprofiles_editor_dialog_transport" data-toggle="tab">{{ _('Transport') }}</a></li>
</ul>
<div class="tab-content">
<div id="connectionprofiles_editor_dialog_general" class="tab-pane active">
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input class="input-block-level" type="text" data-bind="value: editor.profile.name, valueUpdate: 'afterkeydown'">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input class="input-block-level" type="text" data-bind="value: editor.profile.identifier, attr: {placeholder: editor.profile.identifierPlaceholder}">
</div>
</div>
<div data-bind="visible: editor.showOverwrite" class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: editor.profile.overwrite"> {{ _('Overwrite existing profile') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: editor.profile.autoconnect"> {{ _('Attempt auto connect on server start') }}
</label>
</div>
</div>
<div data-bind="visible: editor.showMakeDefault" class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: editor.profile.makeDefault"> {{ _('Make default') }}
</label>
</div>
</div>
</div>
<div id="connectionprofiles_editor_dialog_printer" class="tab-pane">
<div class="control-group">
<label class="control-label">{{ _('Printer profile') }}</label>
<div class="controls">
<select class="input-block-level" data-bind="options: availablePrinterProfiles, optionsText: 'name', value: editor.profile.printerProfile"></select>
</div>
</div>
</div>
<div id="connectionprofiles_editor_dialog_protocol" class="tab-pane">
<div class="control-group">
<label class="control-label">{{ _('Protocol') }}</label>
<div class="controls">
<select class="input-block-level" data-bind="options: availableProtocols, optionsText: 'name', value: editor.profile.protocol"></select>
</div>
</div>
<!--ko let: { profile: editor.profile }-->
{% include "snippets/connectionprofiles/protocolEditor.jinja2" %}
<!--/ko-->
</div>
<div id="connectionprofiles_editor_dialog_transport" class="tab-pane">
<div class="control-group">
<label class="control-label">{{ _('Transport') }}</label>
<div class="controls">
<select class="input-block-level" data-bind="options: availableTransports, optionsText: 'name', value: editor.profile.transport"></select>
</div>
</div>
<!--ko let: { profile: editor.profile }-->
{% include "snippets/connectionprofiles/transportEditor.jinja2" %}
<!--/ko-->
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</a>
<a href="javascript:void(0)" class="btn" aria-hidden="true" data-bind="text: editor.buttonText, click: editor.confirm">{{ _('Save') }}</a>
</div>
</div>
@@ -0,0 +1,70 @@
<ul class="nav nav-pills">
<li id="settings_accesscontrol_users_link" class="active">
<a href="#settings_connection_general" data-toggle="tab">{{ _('General') }}</a>
</li>
<li id="settings_accesscontrol_groups_link">
<a href="#settings_connection_protocols" data-toggle="tab">{{ _('Protocols') }}</a>
</li>
<li id="settings_accesscontrol_groups_link">
<a href="#settings_connection_transports" data-toggle="tab">{{ _('Transports') }}</a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="settings_connection_general">
<form class="form-horizontal">
<fieldset id="settings_connection_general_logging">
<legend>{{ _('Logging') }}</legend>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.connection_log_connection" id="settings-connectionLogConnection"> {{ _('Log communication to <code>connection.log</code>') }} <span class="label label-important">{{ _('Warning') }}</span>
<span class="help-block">{{ _('While this can negatively impact performance, a <code>connection.log</code> can be incredibly useful for debugging any issues observed in the communication between OctoPrint and your printer.') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.connection_log_commdebug" id="settings-connectionLogCommdebug"> {{ _('Log debug information about communication to <code>commdebug.log</code>') }} <span class="label label-important">{{ _('Warning') }}</span>
</label>
</div>
</div>
</fieldset>
</form>
</div>
<div class="tab-pane" id="settings_connection_protocols">
<form class="form-horizontal">
<!-- ko foreach: availableProtocols -->
<fieldset>
<legend data-bind="text: name"></legend>
<!-- ko if: settings.length -->
<!-- ko foreach: settings -->
<!-- ko template: { name: 'parameter_template_controls_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $root.isErrorOrClosed() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<!-- ko if: settings.length === 0 -->
<p><em>{{ _('There are no overall settings for this transport.') }}</em></p>
<!-- /ko -->
</fieldset>
<!-- /ko -->
</form>
</div>
<div class="tab-pane" id="settings_connection_transports">
<form class="form-horizontal">
<!-- ko foreach: availableTransports -->
<fieldset>
<legend data-bind="text: name"></legend>
<!-- ko if: settings.length -->
<!-- ko foreach: settings -->
<!-- ko template: { name: 'parameter_template_controls_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $root.isErrorOrClosed() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<!-- ko if: settings.length === 0 -->
<p></p><em>{{ _('There are no overall settings for this transport.') }}</em></p>
<!-- /ko -->
</fieldset>
<!-- /ko -->
</form>
</div>
</div>
@@ -0,0 +1,51 @@
<h3>{{ _('Connection Profiles') }}</h3>
<table class="table table-condensed table-hover" id="settings_connectionProfiles_profiles" data-bind="visible: profiles.items().length > 0" style="display: none">
<thead>
<tr>
<th class="settings_connectionProfiles_profiles_default"></th>
<th class="settings_connectionProfiles_profiles_name">{{ _('Name') }}</th>
<th class="settings_connectionProfiles_profiles_details">{{ _('Details') }}</th>
<th class="settings_connectionProfiles_profiles_action">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: profiles.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="settings_connectionProfiles_profiles_default"><span class="fa fa-star" data-bind="invisible: !isDefault()"></span></td>
<td class="settings_connectionProfiles_profiles_name" data-bind="text: $data.name"></td>
<td class="settings_connectionProfiles_profiles_details">
<table class="table settings_connectionProfiles_profiles_details_table">
<tr>
<th class="settings_connectionProfiles_profiles_details_key">{{ _('Printer Profile') }}</th>
<td class="settings_connectionProfiles_profiles_details_value" data-bind="text: $root.connection.lookupPrinterProfileName($data.printer_profile)"></td>
</tr>
<tr>
<th class="settings_connectionProfiles_profiles_details_key">{{ _('Protocol') }}</th>
<td class="settings_connectionProfiles_profiles_details_value" data-bind="text: $root.connection.lookupProtocolName($data.protocol)"></td>
</tr>
<tr>
<th class="settings_connectionProfiles_profiles_details_key">{{ _('Transport') }}</th>
<td class="settings_connectionProfiles_profiles_details_value" data-bind="text: $root.connection.lookupTransportName($data.transport)"></td>
</tr>
</table>
</td>
<td class="settings_connectionProfiles_profiles_action">
&nbsp;<a href="javascript:void(0)" class="fa fa-star" title="{{ _('Set as default profile') }}" data-bind="click: function() { if ($root.canMakeDefault($data) && !$root.requestInProgress()) { $root.makeDefault($data); } }, css: {disabled: !$root.canMakeDefault($data) || $root.requestInProgress()}, enabled: $root.canMakeDefault($data) && !$root.requestInProgress()"></a>&nbsp;|&nbsp;<a href="javascript:void(0)" class="fa fa-pencil" title="{{ _('Edit profile') }}" data-bind="click: function() { if (!$root.requestInProgress()) { $root.editProfile($data); } }, css: {disabled: $root.requestInProgress()}, enabled: !$root.requestInProgress()"></a>&nbsp;|&nbsp;<a href="javascript:void(0)" class="fa fa-trash-o" title="{{ _('Delete Profile') }}" data-bind="click: function() { if ($root.canRemove($data) && !$root.requestInProgress()) { $root.removeProfile($data); } }, css: {disabled: !$root.canRemove($data) || $root.requestInProgress()}, enabled: $root.canRemove($data) && !$root.requestInProgress()"></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.addProfile(); }"><i class="fas fa-plus"></i> {{ _('Add Profile...') }}</button>
@@ -0,0 +1,207 @@
<script type="text/html" id="parameter_template_controls_text">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
<div class="controls">
<input class="input-block-level" type="text" data-bind="value: $data.value, attr: {placeholder: $data.default}, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</div>
</div>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_url">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
<div class="controls">
<input class="input-block-level" type="text" data-bind="value: $data.value, attr: {placeholder: $data.default}, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</div>
</div>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_integer">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
<div class="controls">
<!-- ko if: $data.unit -->
<div class="input-append">
<input class="input-small" type="number" step="1" data-bind="value: $data.value, attr: {placeholder: $data.default, min: $data.min, max: $data.max}, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<span class="add-on" data-bind="text: $data.unit"></span>
</div>
<!-- /ko -->
<!-- ko ifnot: $data.unit -->
<input class="input-small" type="number" step="1" data-bind="value: $data.value, attr: {placeholder: $data.default, min: $data.min, max: $data.max}, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<!-- /ko -->
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</div>
</div>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_float">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
<div class="controls">
<!-- ko if: $data.unit -->
<div class="input-append">
<input class="input-small" type="number" data-bind="value: $data.value, attr: {placeholder: $data.default, min: $data.min, max: $data.max}, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<span class="add-on" data-bind="text: $data.unit"></span>
</div>
<!-- /ko -->
<!-- ko ifnot: $data.unit -->
<input class="input-small" type="number" data-bind="value: $data.value, attr: {placeholder: $data.default, min: $data.min, max: $data.max}, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<!-- /ko -->
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</div>
</div>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_choice">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
<div class="controls">
<select class="input-block-level" data-bind="options: $data.choices, optionsText: 'title', optionsValue: 'value', optionsCaption: $data.caption, value: $data.value, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></select>
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</div>
</div>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_presetchoice">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
<div class="controls">
<select class="input-block-level" data-bind="options: $data.choices, optionsText: 'title', optionsValue: 'value', value: $data.value, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></select>
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</div>
</div>
<!-- ko template: { name: 'parameter_template_controls_group', data: { data: group, enabled: ko.pureComputed(function() { return $parents[1].enabled() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_smallchoice">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
<div class="controls">
<!-- ko foreach: choices -->
<label class="radio">
<input type="radio" data-bind="attr: { name: 'connectionprofile_editor_' + $parent.name + '_group' }, value: $data.value, checked: $parent.value, css: {disabled: !$parents[1].enabled()}, enable: $parents[1].enabled"> <span data-bind="markdownInline: $data.title"></span> <span class="label label-important" data-bind="visible: $data.warning">{{ _('Warning') }}</span> <!-- ko foreach: $data.labels --><span class="label" data-bind="text: $data"></span><!-- /ko -->
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</label>
<!-- /ko -->
</div>
</div>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_boolean">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: $data.value, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"> <span data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></span> <span class="label label-important" data-bind="visible: $data.warning">{{ _('Warning') }}</span> <!-- ko foreach: $data.labels --><span class="label" data-bind="text: $data"></span><!-- /ko -->
</label>
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</div>
</div>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_suggestion">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
<div class="controls">
<select class="input-block-level" data-bind="options: $data.suggestions, optionsText: 'title', optionsValue: 'value', value: $data.value, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></select>
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</div>
</div>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_list">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
<div class="controls">
<textarea data-bind="value: $data.value, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></textarea>
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</div>
</div>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_smalllist">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: $data.value, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</div>
</div>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_group">
<!-- ko with: data -->
<fieldset>
<legend data-bind="markdownInline: $data.title"></legend>
<p data-bind="visible: $data.help, markdownInline: $data.help"></p>
<!-- ko foreach: params -->
<!-- ko if: !expert -->
<!-- ko template: { name: 'parameter_template_controls_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $parents[1].enabled() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<div class="advanced_options" data-bind="visible: expertParameters">
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.advanced_options', container: '.hide' }"><i class="fa fa-caret-right"></i> {{ _('Expert options') }}</a></small></div>
<div class="hide">
<!-- ko foreach: params -->
<!-- ko if: expert -->
<!-- ko template: { name: 'parameter_template_controls_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $parents[1].enabled() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
</div>
</div>
</fieldset>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_controls_conditionalgroup">
<!-- ko with: data -->
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
<div class="controls">
<select class="input-block-level" data-bind="options: $data.choices, optionsText: 'title', optionsValue: 'value', value: $data.value, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></select>
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</div>
</div>
<!-- ko foreach: $data.groups[$data.value()] -->
<!-- ko if: !expert -->
<!-- ko template: { name: 'parameter_template_controls_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $parents[1].enabled() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<div class="advanced_options" data-bind="visible: $data.expertParameters[$data.value]">
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.advanced_options', container: '.hide' }"><i class="fa fa-caret-right"></i> {{ _('Expert options') }}</a></small></div>
<div class="hide">
<!-- ko foreach: $data.groups[$data.value()] -->
<!-- ko if: expert -->
<!-- ko template: { name: 'parameter_template_controls_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $parents[1].enabled() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
</div>
</div>
<!-- /ko -->
</script>
@@ -0,0 +1,124 @@
<script type="text/html" id="parameter_template_form_description">
<!-- ko with: data -->
<p data-bind="markdownInline: $data.value"></p>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_text">
<!-- ko with: data -->
<label data-bind="text: $data.title, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></label>
<input class="input-block-level" type="text" data-bind="value: $data.value, attr: {placeholder: $data.default}, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<small class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></small>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_url">
<!-- ko with: data -->
<label data-bind="text: $data.title, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></label>
<input class="input-block-level" type="text" data-bind="value: $data.value, attr: {placeholder: $data.default}, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<small class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></small>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_integer">
<!-- ko with: data -->
<label data-bind="text: $data.title, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></label>
<input class="input-block-level" type="number" step="1" data-bind="value: $data.value, attr: {placeholder: $data.default, min: $data.min, max: $data.max}, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<small class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></small>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_float">
<!-- ko with: data -->
<label data-bind="text: $data.title, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></label>
<input class="input-block-level" type="number" data-bind="value: $data.value, attr: {placeholder: $data.default, min: $data.min, max: $data.max}, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<small class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></small>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_choice">
<!-- ko with: data -->
<label data-bind="text: $data.title, css: {disabled: !$parent.enabled() }, enable: $parent.enabled"></label>
<select class="input-block-level" data-bind="options: $data.choices, optionsText: 'title', optionsValue: 'value', value: $data.value, optionsCaption: $data.caption, css: {disabled: !$parent.enabled() }, enable: $parent.enabled"></select>
<small class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></small>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_smallchoice">
<!-- ko with: data -->
<label data-bind="text: $data.title, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></label>
<!-- ko foreach: choices -->
<label class="radio">
<input type="radio" data-bind="attr: { name: 'connection_dialog_' + $parent.name + '_group' }, value: $data.value, checked: $parent.value"> <span data-bind="text: $data.title"></span>
<small class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></small>
</label>
<!-- /ko -->
<small class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></small>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_boolean">
<!-- ko with: data -->
<label class="checkbox">
<input type="checkbox" data-bind="checked: $data.value, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"> <span data-bind="text: $data.title"></span>
<span class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></span>
</label>
<small class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></small>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_suggestion">
<!-- ko with: data -->
<label data-bind="text: $data.title, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></label>
<div class="input-append">
<input type="text" data-bind="value: $data.value, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<div class="btn-group">
<button class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
<ul class="dropdown-menu pull-right" data-bind="foreach: $data.suggestions">
<li data-bind="attr: { 'data-value': $data.value }"><a href="javascript:void(0)" data-bind="text: $data.title, click: function() { $parent.value($data.value) }"></a></li>
</ul>
</div>
</div>
<small class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></small>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_list">
<!-- ko with: data -->
<label data-bind="text: $data.title, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></label>
<textarea data-bind="value: $data.value, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></textarea>
<small class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></small>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_smalllist">
<!-- ko with: data -->
<label data-bind="text: $data.title, css: {disabled: !$parent.enabled()}, enable: $parent.enabled"></label>
<input type="text" class="input-block-level" data-bind="value: $data.value, css: {disabled: !$parent.enabled()}, enable: $parent.enabled">
<small class="help-block" data-bind="visible: $data.help, markdownInline: $data.help"></small>
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_group">
<!-- ko with: data -->
<label data-bind="text: $data.title"></label>
<!-- ko foreach: params -->
<!-- ko template: { name: 'parameter_template_form_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $parents[1].enabled() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_presetchoice">
<!-- ko with: data -->
<label data-bind="text: $data.title, css: { disabled: !$parent.enabled() }, enable: $parent.enabled"></label>
<select class="input-block-level" data-bind="options: $data.choices, optionsText: 'title', optionsValue: 'value', value: $data.value, css: { disabled: !$parent.enabled() }, enable: $parent.enabled"></select>
<!-- ko if: !$data.group.advanced -->
<label data-bind="text: $data.group.title"></label>
<!-- ko foreach: $data.group.params -->
<!-- ko if: !advanced -->
<!-- ko template: { name: 'parameter_template_form_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $parents[1].enabled() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<!-- /ko -->
</script>
<script type="text/html" id="parameter_template_form_conditionalgroup">
<!-- ko with: data -->
<label data-bind="text: $data.title, css: { disabled: !$parent.enabled() }, enable: $parent.enabled"></label>
<select class="input-block-level" data-bind="options: $data.choices, optionsText: 'title', optionsValue: 'value', value: $data.value, css: { disabled: !$parent.enabled() }, enable: $parent.enabled"></select>
<!-- ko foreach: $data.groups[$data.value()] -->
<!-- ko if: !advanced -->
<!-- ko template: { name: 'parameter_template_form_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $parents[1].enabled() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<!-- /ko -->
</script>
+10 -3
View File
@@ -164,12 +164,19 @@
{% include 'dialogs/files.jinja2' %}
{% include 'dialogs/temperature.jinja2' %}
{% include 'dialogs/timelapse.jinja2' %}
{% include 'dialogs/connection.jinja2' %}
{% include 'dialogs/connectionprofiles.jinja2' %}
<!-- End of dialogs -->
<!-- Overlays -->
{% include 'overlays/dragndrop.jinja2' %}
{% include 'overlays/offline.jinja2' %}
{% include 'overlays/reloadui.jinja2' %}
{% include 'generic/overlays/dragndrop.jinja2' %}
{% include 'generic/overlays/offline.jinja2' %}
{% include 'generic/overlays/reloadui.jinja2' %}
<!-- End of overlays -->
<!-- Parameters -->
{% include 'generic/parameters/form.jinja2' %}
{% include 'generic/parameters/controls.jinja2' %}
<!-- End of overlays -->
{% include 'stylesheets.jinja2' %}
@@ -1,17 +1,47 @@
<div style="margin-bottom: 10px" class="alert alert-error" data-bind="visible: !validPort()"><small>{% trans link="<a href='https://faq.octoprint.org/no-candidates' target='_blank' rel='noopener noreferer'>", endlink="</a>", refresh="<a href='javascript:void(0)' data-bind='click: $root.requestData'>", endrefresh="</a>" %}
No serial port found, are you sure your printer is physically connected and supported?
Try {{ refresh }}refreshing{{ endrefresh }} and if that doesn't help please see {{ link }}the FAQ{{ endlink }}.
{% endtrans %}</small></div>
<label for="connection_ports" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Serial Port') }}</label>
<select id="connection_ports" data-test-id="connection-ports" data-bind="options: portOptions, optionsCaption: portCaption, value: selectedPort, css: {disabled: !isErrorOrClosed()}, enable: enablePort()"></select>
<label for="connection_baudrates" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Baudrate') }}</label>
<select id="connection_baudrates" data-test-id="connection-baudrates" data-bind="options: baudrateOptions, optionsCaption: 'AUTO', value: selectedBaudrate, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label for="connection_printers" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Printer Profile') }}</label>
<select id="connection_printers" data-test-id="connection-printer-profiles" data-bind="options: printerOptions, optionsText: 'name', optionsValue: 'id', value: selectedPrinter, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label class="checkbox" data-bind="css: {muted: !enableSaveSettings()}">
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, enable: enableSaveSettings()"> {{ _('Save connection settings') }}
</label>
<label class="checkbox" data-bind="css: {muted: !enableAutoConnect()}">
<input type="checkbox" id="connection_autoconnect" data-bind="checked: settings.serial_autoconnect, enable: enableAutoConnect()"> {{ _('Auto-connect on server startup') }}
</label>
<button class="btn btn-block" id="printer_connect" data-test-id="connection-connect" data-bind="click: connect, text: buttonText, enable: enableConnect">{{ _('Connect') }}</button>
<form>
<label data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Connection Profile') }}</label>
<select class="input-block-level" data-test-id="connection-ports" data-bind="options: availableConnectionProfiles, optionsText: 'name', value: selectedConnectionProfile, optionsCaption: 'New...', css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label class="checkbox">
<input type="checkbox" data-bind="checked: adjustConnectionParameters"> {{ _('Adjust connection parameters') }}
</label>
<div style="display: none" data-bind="visible: adjustConnectionParameters">
<hr style="margin: 0">
<label data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Printer Profile') }}</label>
<select class="input-block-level" data-test-id="connection-printer-profiles" data-bind="options: availablePrinterProfiles, optionsText: 'name', value: selectedPrinter, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<hr style="margin: 0">
<label data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Protocol') }}</label>
<select class="input-block-level" data-test-id="connection-protocols" data-bind="options: availableProtocols, optionsText: 'name', value: selectedProtocol, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<!-- ko foreach: protocolParameters -->
<!-- ko if: !advanced -->
<!-- ko template: { name: 'parameter_template_form_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $root.isErrorOrClosed() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<!-- ko if: advancedProtocolParameters -->
<small class="text-block text-right"><a href="javascript:void(0)" data-bind="click: showAdvancedProtocolOptions">{{ _('Advanced...') }}</a></small>
<!-- /ko -->
<hr style="margin: 0">
<label data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Transport') }}</label>
<select class="input-block-level" data-test-id="connection-transports" data-bind="options: availableTransports, optionsText: 'name', value: selectedTransport, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<!-- ko foreach: transportParameters -->
<!-- ko if: !advanced -->
<!-- ko template: { name: 'parameter_template_form_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $root.isErrorOrClosed() && $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<!-- ko if: advancedTransportParameters -->
<small class="text-block text-right"><a href="javascript:void(0)" data-bind="click: showAdvancedTransportOptions">{{ _('Advanced...') }}</a></small>
<!-- /ko -->
<hr style="margin: 0">
</div>
<label class="checkbox">
<input type="checkbox" id="connection_autoconnect" data-bind="checked: settings.serial_autoconnect, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Auto-connect on server startup') }}
</label>
</form>
<button class="btn btn-block" id="printer_connect_and_save" data-bind="click: function() { connect(true) }, visible: isErrorOrClosed() && adjustConnectionParameters()">{{ _('Save & Connect') }}</button>
<button class="btn btn-primary btn-block" id="printer_connect" data-test-id="connection-connect" data-bind="click: function() { connect() }, text: buttonText">{{ _('Connect') }}</button>
@@ -1,5 +1,5 @@
<div class="refresh-trigger accordion-heading-button btn-group" data-bind="visible: $root.refreshVisible">
<a href="#" data-bind="click: function() { $root.requestData(); }" title="{{ _('Refresh connection options')|edq }}">
<a href="javascript:void(0)" data-bind="click: function() { $root.requestData(); }" title="{{ _('Refresh connection options')|edq }}">
<i class="fas fa-sync"></i>
</a>
</div>
@@ -0,0 +1,16 @@
<!-- ko foreach: profile.protocolParameters -->
<!-- ko if: !expert -->
<!-- ko template: { name: 'parameter_template_controls_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<div class="advanced_options" data-bind="visible: profile.expertProtocolParameters">
<div><small><a class="muted" href="javascript:void(0)" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.advanced_options', container: '.hide' }"><i class="fa fa-caret-right"></i> {{ _('Expert options') }}</a></small></div>
<div class="hide">
<!-- ko foreach: profile.protocolParameters -->
<!-- ko if: expert -->
<!-- ko template: { name: 'parameter_template_controls_' + $data.type, data: { data: $data, enabled: ko.pureComputed(function() { return $data.enabled() }) } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
</div>
</div>
@@ -0,0 +1,16 @@
<!-- ko foreach: profile.transportParameters -->
<!-- ko if: !expert -->
<!-- ko template: { name: 'parameter_template_controls_' + $data.type, data: { data: $data, enabled: $data.enabled } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<div class="advanced_options" data-bind="visible: profile.expertTransportParameters">
<div><small><a class="muted" href="javascript:void(0)" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.advanced_options', container: '.hide' }"><i class="fa fa-caret-right"></i> {{ _('Expert options') }}</a></small></div>
<div class="hide">
<!-- ko foreach: profile.transportParameters -->
<!-- ko if: expert -->
<!-- ko template: { name: 'parameter_template_controls_' + $data.type, data: { data: $data, enabled: $data.enabled } } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
</div>
</div>
@@ -1,4 +1,4 @@
<table class="table table-striped table-hover table-condensed table-hover" id="settings_printerProfiles_profiles" data-bind="visible: printerProfiles.profiles.items().length > 0" style="display: none">
<table class="table table-condensed table-hover" id="settings_printerProfiles_profiles" data-bind="visible: printerProfiles.profiles.items().length > 0" style="display: none">
<thead>
<tr>
<th class="settings_printerProfiles_profiles_name">{{ _('Name') }}</th>
+140 -2
View File
@@ -46,6 +46,10 @@ from octoprint.util.net import ( # noqa: F401
logger = logging.getLogger(__name__)
def dummy_gettext(string):
return string
def to_bytes(
s_or_u: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict"
) -> Union[bytes, None]:
@@ -1413,6 +1417,7 @@ class ResettableTimer(threading.Thread):
self.kwargs = kwargs
self.on_cancelled = on_cancelled
self.on_reset = on_reset
self.daemon = daemon
def run(self):
@@ -1503,7 +1508,7 @@ class CountedEvent:
def blocked(self):
return self.counter <= 0
def acquire(self, blocking=1):
def acquire(self, blocking=True):
return self._mutex.acquire(blocking=blocking)
def release(self):
@@ -1549,8 +1554,17 @@ class InvariantContainer:
def __len__(self):
return len(self._data)
def __getitem__(self, item):
with self._mutex:
return self._data[item]
def __setitem__(self, item, value):
with self._mutex:
self._data[item] = value
self._data = self._invariant(self._data)
def __iter__(self):
return self._data.__iter__()
return iter(self._data)
class PrependableQueue(queue.Queue):
@@ -1643,6 +1657,113 @@ class TypeAlreadyInQueue(Exception):
self.type = t
class dictview(collections.Mapping):
"""
>>> my_dict = dict(a="a", b="b", flag=True, value=23)
>>> view = dictview(my_dict)
>>> view["a"] # doctest: +ALLOW_UNICODE
'a'
>>> view["flag"]
True
>>> view["foo"] # doctest: +ALLOW_UNICODE
Traceback (most recent call last):
...
KeyError: 'foo'
>>> my_dict["foo"] = "bar"
>>> view["foo"] # doctest: +ALLOW_UNICODE
'bar'
>>> view["foo"] = "fnord"
Traceback (most recent call last):
...
TypeError: 'dictview' object does not support item assignment
"""
def __init__(self, data, copy=False, deepcopy=False):
self.data = data
self.copy = copy
self.deepcopy = deepcopy
def __len__(self):
return len(self.data)
def __iter__(self):
return iter(self.data)
def __getitem__(self, key):
return self._get_item(key)
def _get_item(self, key):
import copy
value = self.data[key]
if self.deepcopy:
value = copy.deepcopy(value)
elif self.copy:
value = copy.copy(value)
return value
class protectedkeydict(collections.MutableMapping):
"""
>>> my_dict = dict(a="a")
>>> protected = protectedkeydict(my_dict)
>>> protected["a"] # doctest: +ALLOW_UNICODE
'a'
>>> protected["a"] = "b" # doctest: +ALLOW_UNICODE
Traceback (most recent call last):
...
KeyError: "Cannot set protected key 'a'"
>>> protected["b"] = "b"
>>> protected["b"] = "b2"
>>> del protected["a"] # doctest: +ALLOW_UNICODE
Traceback (most recent call last):
...
KeyError: "Cannot delete protected key 'a'"
>>> del protected["b"]
"""
def __init__(self, data, copy=False, deepcopy=False):
self.data = data
self.copy = copy
self.deepcopy = deepcopy
self.protected_keys = list(data.keys())
def __len__(self):
return len(self.data)
def __iter__(self):
return iter(self.data)
def __getitem__(self, key):
return self._get_item(key)
def __setitem__(self, key, value):
if key in self.protected_keys:
raise KeyError(f"Cannot set protected key {key!r}")
self.data[key] = value
def __delitem__(self, key):
if key in self.protected_keys:
raise KeyError(f"Cannot delete protected key {key!r}")
def _get_item(self, key):
if key not in self.protected_keys:
return self.data[key]
else:
import copy
value = self.data[key]
if self.deepcopy:
value = copy.deepcopy(value)
elif self.copy:
value = copy.copy(value)
return value
class CaseInsensitiveSet(Set):
"""
Basic case insensitive set
@@ -1741,3 +1862,20 @@ def generate_api_key():
def map_boolean(value, true_text, false_text):
return true_text if value else false_text
class Timeout:
def __init__(self, duration):
self._duration = duration
self._start = time.monotonic()
@property
def expired(self):
return self.remaining <= 0
@property
def remaining(self):
return self._start + self._duration - time.monotonic()
def reset(self):
self._start = time.monotonic()
+36
View File
@@ -0,0 +1,36 @@
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
class ListenerAware:
def __init__(self):
self._listeners = set()
def register_listener(self, listener):
self._listeners.add(listener)
def unregister_listener(self, listener):
try:
self._listeners.remove(listener)
except KeyError:
pass
def notify_listeners(self, name, *args, **kwargs):
from logging import getLogger
logger = getLogger(__name__)
for listener in self._listeners.copy():
method = getattr(listener, name, None)
if not method:
continue
try:
method(*args, **kwargs)
except Exception:
logger.exception(
"Exception while calling {}(...) on listener {}".format(
name, listener
)
)
+82
View File
@@ -0,0 +1,82 @@
"""
Unit tests for ``octoprint.comm.protocol``.
"""
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import time
from octoprint.comm.transport import Transport
from octoprint.util import monotonic_time, to_bytes
class TestTransport(Transport):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.outgoing = bytearray()
self.incoming = []
@property
def in_waiting(self):
return len(self.outgoing)
def do_read(self, size=None, timeout=None):
if size is None:
result = bytes(self.outgoing)
else:
if timeout is None:
while self.in_waiting < size:
time.sleep(0.1)
else:
start = time.time()
while self.in_waiting < size and time.time() - start < timeout:
time.sleep(0.1)
if size < self.in_waiting:
result = bytes(self.outgoing[0 : size - 1])
del self.outgoing[0 : size - 1]
else:
result = bytes(self.outgoing)
del self.outgoing[:]
return result
def do_write(self, data):
self.incoming.append(data)
def send(self, data):
self.outgoing += bytearray(to_bytes(data))
def expect(self, expected, timeout=10.0):
if timeout is not None:
stop = monotonic_time() + timeout
timed_out = lambda: monotonic_time() >= stop
else:
timed_out = lambda: False
while len(self.incoming) == 0 and not timed_out():
time.sleep(0.1)
try:
actual = self.incoming.pop(0)
except IndexError:
raise ExpectTimeout()
if callable(expected):
expected = expected()
if expected != actual:
raise AssertionError(f"Expected {expected!r}, got {actual!r}")
return actual
def expect_and_send(self, expected, data, timeout=10.0):
self.expect(expected, timeout=timeout)
self.send(data)
class ExpectTimeout(Exception):
pass
+105
View File
@@ -0,0 +1,105 @@
"""
Unit tests for ``octoprint.comm.protocol.reprap``.
"""
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
from unittest import mock
import ddt
import octoprint.comm.protocol.reprap
from octoprint.util import to_bytes
from .. import TestTransport
@ddt.ddt
class RepRapProtocolTest(unittest.TestCase):
def setUp(self):
printer_profile = mock.MagicMock()
plugin_manager = mock.MagicMock()
event_bus = mock.MagicMock()
settings = mock.MagicMock()
self.protocol = octoprint.comm.protocol.reprap.ReprapGcodeProtocol(
printer_profile=printer_profile,
plugin_manager=plugin_manager,
event_bus=event_bus,
settings=settings,
)
self.transport = TestTransport()
def testHandshake(self):
self.protocol.connect(self.transport)
self._perform_and_test_handshake()
def testHandshakeWithTemperatureAutoreport(self):
self.protocol.interval["temperature_autoreport"] = 2.0
self.protocol.connect(self.transport)
self._perform_and_test_handshake(capabilities={"AUTOREPORT_TEMP": True})
self.transport.expect_and_send("M155 S2\n", "ok\n")
def testHandshakeWithTemperatureAutoreportButDisabled(self):
self.protocol._capability_support[
octoprint.comm.protocol.reprap.CAPABILITY_AUTOREPORT_TEMP
] = False
self.protocol.connect(self.transport)
self._perform_and_test_handshake(capabilities={"AUTOREPORT_TEMP": True})
self.transport.expect_and_send("M105\n", "ok T:21.3/0\n")
self.transport.expect_and_send("M105\n", "ok T:21.3/0\n")
def testHandshakeWithSdAutoreport(self):
self.protocol.interval["sd_status_autoreport"] = 2.0
self.protocol.connect(self.transport)
self._perform_and_test_handshake(capabilities={"AUTOREPORT_SD_STATUS": True})
self.transport.expect_and_send("M27 S2\n", "ok\n")
@ddt.data(
# regular notation
("Error:Last Line Number is not Last Line Number+1\n", "Resend: N2\nok\n"),
("Error:Last Line Number is not Last Line Number+1\n", "Resend: 2\nok\n"),
# short hand notation
("!! Last Line Number is not Last Line Number+1\n", "rs N2\nok\n"),
("!! Last Line Number is not Last Line Number+1\n", "rs 2\nok\n"),
# missing ok
("Error:Last Line Number is not Last Line Number+1\n", "Resend: N2\n"),
)
@ddt.unpack
def testResendRequest(self, error, request):
self.protocol.connect(self.transport)
self._perform_and_test_handshake()
self.transport.send(error)
self.transport.send(request)
self.transport.expect_and_send("N2 M105*37\n", "ok T:21.3/0\n")
def _perform_and_test_handshake(self, firmware_name=None, capabilities=None):
if firmware_name is None:
firmware_name = "ProtocolTest"
if capabilities is None:
capabilities = {}
firmware_info = f"FIRMWARE_NAME:{firmware_name}\n"
for cap, enabled in capabilities.items():
firmware_info += "Cap:{}:{}\n".format(cap.upper(), "1" if enabled else "0")
firmware_info += "ok\n"
self.transport.expect_and_send("N0 M110 N0*125\n", "start\n") # tickle 1
self.transport.expect_and_send("N0 M110 N0*125\n", "ok\n") # tickle 2
self.transport.expect_and_send("N0 M110 N0*125\n", "ok\n") # reset line numbers
self.transport.expect_and_send("N1 M115*39\n", firmware_info) # get firmware info
self.transport.expect_and_send(
"N2 M105*37\n", "ok T:21.3/0\n"
) # temperature query
@staticmethod
def _checksummed(line, linenumber):
result = b"N" + str(linenumber).encode("ascii") + b" " + to_bytes(line)
checksum = 0
for c in bytearray(result):
checksum ^= c
return result + b"*" + str(checksum).encode("ascii")
Whitespace-only changes.
@@ -0,0 +1,6 @@
"""
Unit tests for ``octoprint.comm.protocol.reprap.commands.``.
"""
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -0,0 +1,70 @@
"""
Unit tests for ``octoprint.comm.protocol.reprap.commands.gcode.``.
"""
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import ddt
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
@ddt.ddt
class GcodeCommandTest(unittest.TestCase):
@ddt.data(
("M105", {"code": "M105"}),
("M30 some_file.gco", {"code": "M30", "param": "some_file.gco"}),
("G28 X0 Y0", {"code": "G28", "x": 0, "y": 0}),
("G28X0Y0", {"code": "G28", "x": 0, "y": 0}),
("M104 S220.0 T1", {"code": "M104", "s": 220.0, "t": 1}),
(
"M123.456 my parameter is long",
{"code": "M123", "subcode": 456, "param": "my parameter is long"},
),
("M123 Hello there", {"code": "M123", "param": "Hello there"}),
(
"M123 C P1 X0 Y2.3 Z-23.42 E+5",
{"code": "M123", "c": True, "p": 1, "x": 0, "y": 2.3, "z": -23.42, "e": 5},
),
(
"M123 P1 And a parameter too",
{"code": "M123", "p": 1, "param": "And a parameter too"},
),
("T123", {"code": "T", "tool": 123}),
("F200", {"code": "F", "feedrate": 200}),
)
@ddt.unpack
def test_from_line(self, line, expected_args):
actual = GcodeCommand.from_line(line)
for arg, value in expected_args.items():
self.assertEqual(value, getattr(actual, arg))
@ddt.data(
(
"G28 X0 Y0",
"GcodeCommand(u'G28',x=0,y=0,original=u'G28 X0 Y0',type=None,tags=set([]))",
),
(
"M30 some_file.gco",
"GcodeCommand(u'M30',param=u'some_file.gco',original=u'M30 some_file.gco',type=None,tags=set([]))",
),
("T1", "GcodeCommand(u'T',tool=1,original=u'T1',type=None,tags=set([]))"),
(
"F6000",
"GcodeCommand(u'F',feedrate=6000,original=u'F6000',type=None,tags=set([]))",
),
("M27 C", "GcodeCommand(u'M27',c=True,original=u'M27 C',type=None,tags=set([]))"),
)
@ddt.unpack
def test_repr(self, line, expected):
gcode = GcodeCommand.from_line(line)
self.assertEqual(expected, repr(gcode))
@ddt.data(("M104", {"s": 210.0}, "M104 S210.0"))
@ddt.unpack
def test_constructor(self, code, kwargs, expected):
gcode = GcodeCommand(code, **kwargs)
self.assertEqual(expected, str(gcode))
+2 -1
View File
@@ -8,6 +8,7 @@ import unittest
import unittest.mock as mock
import octoprint.filemanager
import octoprint.filemanager.storage.local
import octoprint.filemanager.util
import octoprint.settings
@@ -172,7 +173,7 @@ class FileManagerTest(unittest.TestCase):
)
self.local_storage = mock.MagicMock(
spec=octoprint.filemanager.storage.LocalFileStorage
spec=octoprint.filemanager.storage.local.LocalFileStorage
)
self.local_storage.analysis_backlog = iter([])
+2 -1
View File
@@ -9,7 +9,8 @@ import unittest.mock as mock
from ddt import data, ddt, unpack
from octoprint.filemanager.storage import LocalFileStorage, StorageError
from octoprint.filemanager.storage import StorageError
from octoprint.filemanager.storage.local import LocalFileStorage
class FileWrapper:
-63
View File
@@ -133,37 +133,6 @@ class SettingsTestCase(unittest.TestCase):
forwarded_method = getattr(self.settings, forwarded)
forwarded_method.assert_called_once_with(*getter_args, **getter_kwargs)
@data(
("getInt", "get_int", "getInt"),
("getFloat", "get_float", "getFloat"),
("getBoolean", "get_boolean", "getBoolean"),
)
@unpack
def test_deprecated_forwarded_getter(self, deprecated, current, forwarded):
with warnings.catch_warnings(record=True) as w:
called_method = getattr(self.settings, forwarded)
# further mock out our mocked function so things work as they should
called_method.__name__ = forwarded
called_method.__qualname__ = forwarded
called_method.__annotations__ = {}
method = getattr(self.plugin_settings, deprecated)
self.assertTrue(callable(method))
method(["some_raw_key"])
called_method.assert_called_once_with(
["plugins", self.plugin_key, "some_raw_key"],
defaults={"plugins": {"test_plugin": self.defaults}},
preprocessors={"plugins": {"test_plugin": self.get_preprocessors}},
)
self.assertEqual(1, len(w))
self.assertTrue(issubclass(w[-1].category, DeprecationWarning))
self.assertTrue(
f"{deprecated} has been renamed to {current}" in str(w[-1].message)
)
@data(
(
"set",
@@ -372,38 +341,6 @@ class SettingsTestCase(unittest.TestCase):
forwarded_method = getattr(self.settings, forwarded)
forwarded_method.assert_called_once_with(*setter_args, **setter_kwargs)
@data(
("setInt", "set_int", "setInt", 1),
("setFloat", "set_float", "setFloat", 2.5),
("setBoolean", "set_boolean", "setBoolean", True),
)
@unpack
def test_deprecated_forwarded_setter(self, deprecated, current, forwarded, value):
with warnings.catch_warnings(record=True) as w:
called_method = getattr(self.settings, forwarded)
# further mock out our mocked function so things work as they should
called_method.__name__ = forwarded
called_method.__qualname__ = forwarded
called_method.__annotations__ = {}
method = getattr(self.plugin_settings, deprecated)
self.assertTrue(callable(method))
method(["some_raw_key"], value)
called_method.assert_called_once_with(
["plugins", self.plugin_key, "some_raw_key"],
value,
defaults={"plugins": {"test_plugin": self.defaults}},
preprocessors={"plugins": {"test_plugin": self.set_preprocessors}},
)
self.assertEqual(1, len(w))
self.assertTrue(issubclass(w[-1].category, DeprecationWarning))
self.assertTrue(
f"{deprecated} has been renamed to {current}" in str(w[-1].message)
)
def test_global_get_basefolder(self):
self.plugin_settings.global_get_basefolder("some_folder")
self.settings.getBaseFolder.assert_called_once_with("some_folder")