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 8505a977d6 💚 Fix a unit test that got forgotten to adjust 2021-12-08 13:12:44 +01:00
Gina Häußge c28629bb40 🐛 Fix a merge error 2021-12-08 13:07:09 +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 eb61020395 🐛 Fix blueprint registration
Forgot to commit the file
2021-12-06 17:13:47 +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 8153d70da7 💥 Upgrade Flask & thus Jinja to fix warnings
Also iron out a bunch of other warnings.

Heads-up: This upgrades Jinja, werkzeug and itsdangerous as well!

Jinja 3 is not fully backwards compatible to 2
due to a bug fix we so far pinned to an old
version for. It's time to stop doing that
with OctoPrint 2.0.0. Should only affect plugins that
are still trying to access variables defined in
an outer scope in an inner scope, as deemed
an unintentional behaviour in pallets/jinja#641
and removed in Jinja 2.9. It's easy to solve
by switching to using assignments, see
https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments.
2021-12-06 16:41:32 +01:00
Gina Häußge 0dba51181c Merge branch 'maintenance' into devel 2021-12-06 16:25:53 +01:00
Carey Metcalfe c2842694ce ♻ Provide a content-length for streaming zip downloads (#4313)
This allows browsers and other clients to calculate download progress
and detect if the download fails (they get less data than expected).
This is most useful when downloading multiple timelapses due to their
potential size.

Also fixes an oversight where the printer's firmware wasn't being added
to `systeminfo.txt` when downloading system info.
2021-11-15 16:03:02 +01:00
Gina Häußge 43a62bf6f3 Merge branch 'maintenance' into devel 2021-11-03 10:19:08 +01:00
Gina Häußge bcea4839f6 Merge branch 'maintenance' into devel 2021-11-01 16:34:21 +01:00
Gina Häußge 54454deaf3 🎨 Post-merge pre-commit fixes 2021-10-12 18:27:18 +02:00
Gina Häußge e3df0ea934 Merge branch 'maintenance' into devel 2021-10-12 18:19:59 +02:00
Gina Häußge b3affac9e5 Merge branch 'maintenance' into devel 2021-10-11 16:31:25 +02:00
Gina Häußge 6026f066e0 🐛 Fix merge error 2021-09-13 15:47:09 +02:00
Gina Häußge 6a697e9013 Merge branch 'maintenance' into devel 2021-09-13 14:03:05 +02:00
Gina Häußge 75ec0c887e 🎨 eventmgr: Pyupgrade 2021-08-11 15:01:56 +02:00
Gina Häußge 9b0f60da05 Merge branch 'maintenance' into devel 2021-08-11 14:58:47 +02:00
Gina Häußge 3e6e7d3a6a ⬆️ Some more dependency updates 2021-08-04 16:01:54 +02:00
Gina Häußge 4156ccc08f Merge branch 'maintenance' into devel 2021-08-04 15:55:54 +02: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 28ec474ed4 🐛 Use devel branch of codemods 2021-07-13 17:06:23 +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 7f5700e0f9 Merge branch 'maintenance' into devel 2021-07-13 15:50:19 +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 e41b8e3090 🔀 Fix merge issue 2021-07-02 17:01:56 +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 635156cf7a Merge branch 'maintenance' into devel 2021-07-02 16:32:44 +02:00
Gina Häußge cbe72cc1ec 🎨 Clean up a Py2 leftover 2021-07-02 16:18:15 +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 b202c6db54 🔥 Remove Py2 related code 2021-05-20 15:42:37 +02:00
Gina Häußge 3778bcc423 Merge branch 'maintenance' into devel
# Conflicts:
#	docs/development/environment.rst
2021-05-20 15:34:29 +02:00
Gina Häußge 49621a65b0 Merge branch 'maintenance' into devel 2021-05-20 12:23:26 +02:00
Gina Häußge d80f67df9a Merge branch 'maintenance' into devel 2021-05-10 16:39:21 +02:00
Gina Häußge 6cb550e9f4 Merge branch 'maintenance' into devel 2021-04-27 11:37:24 +02:00
Gina Häußge 55158bdef9 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/printer/standard.py
2021-04-26 14:47:21 +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 a34202fdec 🎨 pyupgrade 2021-04-19 18:06:51 +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 944441ec7d Merge branch 'maintenance' into devel 2021-04-19 17:39:17 +02:00
Gina Häußge beef176ac0 Merge branch 'maintenance' into devel 2021-04-14 15:35:50 +02:00
Gina Häußge f97db4465f Merge branch 'maintenance' into devel 2021-03-30 14:27:32 +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 262983840a Merge branch 'maintenance' into devel 2021-03-16 14:35:40 +01:00
Gina Häußge bb2c3273c0 🔥 Remove deprecated thaw_frozendict 2021-03-15 18:05:34 +01:00
Gina Häußge d8fa8e3029 Merge branch 'maintenance' into devel
# Conflicts:
#	.github/workflows/build.yml
#	.github/workflows/test_install.yml
#	setup.py
#	src/octoprint/printer/standard.py
#	src/octoprint/util/__init__.py
2021-03-15 18:03:51 +01:00
Gina Häußge ed21f75acf ♻️ Remove py2 stuff 2021-03-15 17:14:39 +01:00
Gina Häußge d2452c007e Merge branch 'maintenance' into devel 2021-03-15 17:08:47 +01:00
GitHub Nightly Merge Action 9625695467 Merge branch 'maintenance' into devel 2021-03-11 16:40:10 +00:00
Gina Häußge 7668afcff7 💚 Fix unit tests
io.open is no longer used, mocks needed adjustments
2021-03-11 17:06:04 +01:00
Gina Häußge fd2ece0f13 🎨 pyupgrade --py37-plus 2021-03-11 16:01:02 +01:00
Gina Häußge a71f6fcd40 Merge branch 'maintenance' into devel
# Conflicts:
#	.pre-commit-config.yaml
#	setup.py
#	src/octoprint/plugins/pluginmanager/__init__.py
#	src/octoprint/server/api/printer.py
#	src/octoprint/server/api/printer_profiles.py
#	src/octoprint/server/api/settings.py
#	src/octoprint/util/commandline.py
2021-03-11 15:26:46 +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 ca3b78d140 🎨 Clean up some py2 leftovers & arm more codemods 2021-02-25 14:17:47 +01:00
Gina Häußge 5b7bc6cb91 Merge branch 'maintenance' into devel 2021-02-24 15:04:22 +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 0fd00ef5fc Merge branch 'maintenance' into devel
# Conflicts:
#	docs/development/environment.rst
2021-02-17 15:38:54 +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 2a6f7478c3 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/logging/__init__.py
2021-02-05 13:04:26 +01:00
Gina Häußge 5e620bcdfe Merge pull request #3981 from eumiro/py36plus
🚀 Modernize the code to Python 3.6+
2021-01-26 10:53:45 +01:00
Miroslav Šedivý dcd3592fd4 ✒️ Fix declared encoding of literal strings 2021-01-25 19:00:33 +01:00
Miroslav Šedivý 7f56d47dbc 🐝 Compact yield from generator 2021-01-25 19:00:33 +01:00
Miroslav Šedivý d041e1ce97 👴 Use default super() arguments 2021-01-25 19:00:32 +01:00
Miroslav Šedivý ad0c0ddfe1 👣 Remove __future__ imports and source code encodings 2021-01-25 19:00:32 +01:00
Miroslav Šedivý 0308150048 📗 Compact dict creation 2021-01-25 19:00:28 +01:00
Miroslav Šedivý 35e35d92a6 💥 Use OSError as the general system-related exception
According to PEP 3151, OSError can be used for all system-related exceptions and thus replace IOError, EnvironmentError, socket.error, etc.
2021-01-25 18:04:47 +01:00
Miroslav Šedivý 95441dafd4 📦 Use Python3 default for class inheriting from object 2021-01-25 18:04:40 +01:00
Gina Häußge f7ad7d93a5 Merge branch 'maintenance' into devel 2021-01-25 16:07:48 +01:00
Gina Häußge 9c8691eeb7 Merge pull request #3980 from eumiro/numbers
🦕 Remove the redundant Python2 float conversion relics from the `devel` branch
2021-01-25 15:53:10 +01:00
Miroslav Šedivý a89d03b794 🔪 Compare the difference, not rounded values
round(1.0004, 3) != round(1.0006, 3) but still abs(1.0004 - 1.0006) < 0.001
2021-01-22 13:40:44 +01:00
Miroslav Šedivý 7810a622a9 🦕 Remove redundant float conversions from Python2 2021-01-22 13:40:44 +01:00
Gina Häußge bb8fafaacb 💚 mock => unittest.mock
We don't have the mock package installed here anymore
2021-01-19 11:52:41 +01:00
Gina Häußge 977e021b36 Merge branch 'maintenance' into devel 2021-01-19 11:44:31 +01:00
Gina Häußge 00fb7daecf Merge branch 'maintenance' into devel 2021-01-14 16:12:30 +01:00
Gina Häußge f66b318022 📌 Pin watchdog to 1.0.0
That's the latest Python 3 compatible release. We'll need to pin this
explicitly from now on since it's proven to not adhere to semver.
2020-12-10 14:16:03 +01:00
Gina Häußge 97ec0493d1 Merge branch 'maintenance' into devel 2020-12-10 14:14:22 +01:00
Gina Häußge 669660c2fb Merge branch 'maintenance' into devel 2020-12-04 12:02:29 +01:00
Gina Häußge 1b5d24cb9d Merge branch 'maintenance' into devel 2020-11-30 16:11:38 +01:00
Gina Häußge d60bb43e07 💚 Fix unit tests testing settings init
We now need to explicitly trigger a write to config.yaml to test proper
creation at the right places since we no longer will automatically
generate a global API key - that has been removed.
2020-11-26 12:24:12 +01:00
Gina Häußge 86db7d8ec4 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/static/js/app/viewmodels/printerstate.js
2020-11-25 17:30:31 +01:00
Gina Häußge 43541ceebc 💥 Remove global API key 2020-11-25 17:24:38 +01:00
Gina Häußge 8ef57e2ab7 Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/filemanager/storage.py
#	src/octoprint/plugins/announcements/__init__.py
2020-11-25 13:19:01 +01:00
Gina Häußge 4b0c1fe63c Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/util/commandline.py
2020-11-18 16:32:12 +01:00
Gina Häußge 90c0675234 Merge branch 'maintenance' into devel 2020-11-17 16:23:15 +01:00
Gina Häußge b8bbdbdc64 Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
2020-11-10 16:10:41 +01:00
Gina Häußge 5325b32cf2 Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/server/__init__.py
#	src/octoprint/util/__init__.py
2020-11-06 17:08:58 +01:00
Gina Häußge 29994cd63f 🎨 Some more checks so Py2 stuff doesn't creep back in 2020-10-23 17:03:14 +02:00
Gina Häußge 718f89fdbd Merge branch 'maintenance' into devel 2020-10-23 16:59:02 +02:00
Gina Häußge c02c1452e6 ♻️ Py3: Some more import & compat stragglers 2020-10-22 16:25:47 +02:00
Gina Häußge 55ddfdd314 💚 Fix tests 2020-10-22 16:22:00 +02:00
Gina Häußge d5e4cf3a1a ♻️ Py3: native support for typing annotations 2020-10-22 15:51:26 +02:00
Gina Häußge b73f62b433 ♻️ Py3: get rid of unneeded noinspection comments & imports 2020-10-22 15:50:49 +02:00
Gina Häußge 5102c3b5e0 ♻️ Py3: require Python 3.7 at a minimum 2020-10-22 14:34:04 +02:00
Gina Häußge fe87062768 ♻️ Py3: no more need to patch scandir for watchdog 2020-10-22 14:31:52 +02:00
Gina Häußge 21a30001fa ♻️ Py3: NamedTemporaryFile now DOES support encoding 2020-10-22 14:31:23 +02:00
Gina Häußge e1d55e00af ♻️ Py3: Remove py2 specific sarge patch 2020-10-22 14:30:40 +02:00
Gina Häußge d98a6da7b2 ♻️ Py3: get rid of some py2 import stragglers 2020-10-22 14:29:30 +02:00
Gina Häußge f510cc4218 ♻️ Py3: collections.{Iterable,KeysView} => collections.abc.{...} 2020-10-21 19:06:25 +02:00
Gina Häußge ac347c4e06 ♻️ Py3: Remove use of glob_escape & monotonic_time & mark deprecated
Those are natively available in Python 3.
2020-10-21 19:01:02 +02:00
Gina Häußge d2298a8092 ♻️ Py3: Remove PY3 use 2020-10-21 18:41:53 +02:00
Gina Häußge e45e97f9ac ♻️ Py3: Remove past.builtins and future.utils uses 2020-10-21 18:39:52 +02:00
Gina Häußge 292aa99543 ♻️ Py3: Remove Py2 specific imports 2020-10-21 18:13:39 +02:00
Gina Häußge 61a08d26b2 Merge branch 'maintenance' into devel 2020-10-21 14:35:24 +02:00
Gina Häußge 9f0ae77f95 🎨 pre-commit: add future import check 2020-10-07 22:16:41 +02:00
Gina Häußge 100764b03e 🎨 Remove some left-over pragma headers & future imports 2020-10-07 21:37:22 +02:00
Gina Häußge c715751bc6 Merge branch 'maintenance' into devel 2020-10-07 21:19:05 +02:00
Gina Häußge 18e6bfc7f8 Merge branch 'maintenance' into devel
# Conflicts:
#	.github/workflows/build.yml
#	docs/conf.py
#	docs/development/environment.rst
#	docs/sphinxext/codeblockext.py
#	docs/sphinxext/onlineinclude.py
#	setup.py
#	src/octoprint/access/groups.py
#	src/octoprint/access/permissions.py
#	src/octoprint/access/users.py
#	src/octoprint/cli/__init__.py
#	src/octoprint/cli/analysis.py
#	src/octoprint/cli/client.py
#	src/octoprint/cli/config.py
#	src/octoprint/cli/plugins.py
#	src/octoprint/cli/server.py
#	src/octoprint/cli/user.py
#	src/octoprint/environment.py
#	src/octoprint/events.py
#	src/octoprint/filemanager/__init__.py
#	src/octoprint/filemanager/analysis.py
#	src/octoprint/filemanager/destinations.py
#	src/octoprint/filemanager/storage.py
#	src/octoprint/filemanager/util.py
#	src/octoprint/logging/__init__.py
#	src/octoprint/logging/handlers.py
#	src/octoprint/plugin/__init__.py
#	src/octoprint/plugin/core.py
#	src/octoprint/plugins/action_command_notification/__init__.py
#	src/octoprint/plugins/action_command_prompt/__init__.py
#	src/octoprint/plugins/appkeys/__init__.py
#	src/octoprint/plugins/backup/__init__.py
#	src/octoprint/plugins/corewizard/__init__.py
#	src/octoprint/plugins/corewizard/subwizards.py
#	src/octoprint/plugins/discovery/__init__.py
#	src/octoprint/plugins/errortracking/__init__.py
#	src/octoprint/plugins/gcodeviewer/__init__.py
#	src/octoprint/plugins/logging/__init__.py
#	src/octoprint/plugins/pi_support/__init__.py
#	src/octoprint/plugins/softwareupdate/cli.py
#	src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py
#	src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py
#	src/octoprint/plugins/softwareupdate/version_checks/always_current.py
#	src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py
#	src/octoprint/plugins/softwareupdate/version_checks/github_release.py
#	src/octoprint/plugins/softwareupdate/version_checks/httpheader.py
#	src/octoprint/plugins/softwareupdate/version_checks/jsondata.py
#	src/octoprint/plugins/softwareupdate/version_checks/never_current.py
#	src/octoprint/plugins/softwareupdate/version_checks/pypi_release.py
#	src/octoprint/plugins/tracking/__init__.py
#	src/octoprint/plugins/virtual_printer/virtual.py
#	src/octoprint/printer/__init__.py
#	src/octoprint/printer/estimation.py
#	src/octoprint/printer/profile.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/__init__.py
#	src/octoprint/server/api/system.py
#	src/octoprint/server/api/users.py
#	src/octoprint/server/util/flask.py
#	src/octoprint/server/util/tornado.py
#	src/octoprint/server/util/webassets.py
#	src/octoprint/settings.py
#	src/octoprint/slicing/__init__.py
#	src/octoprint/timelapse.py
#	src/octoprint/util/__init__.py
#	src/octoprint/util/comm.py
#	src/octoprint/util/commandline.py
#	src/octoprint/util/connectivity.py
#	src/octoprint/util/fixes.py
#	src/octoprint/util/gcodeInterpreter.py
#	src/octoprint/util/jinja.py
#	src/octoprint/util/json/__init__.py
#	src/octoprint/util/net.py
#	src/octoprint_client/__init__.py
#	src/octoprint_setuptools/__init__.py
#	tests/filemanager/test_filemanager.py
#	tests/filemanager/test_localstorage.py
#	tests/plugin/test_core.py
#	tests/plugin/test_settings.py
#	tests/plugin/test_types_blueprint.py
#	tests/plugin/test_types_settings.py
#	tests/server/api/test_system.py
#	tests/server/util/test_flask.py
#	tests/server/util/test_tornado.py
#	tests/slicing/test_slicingmanager.py
#	tests/test_daemon.py
#	tests/timelapse/test_timelapse_helpers.py
#	tests/util/test_comm.py
#	tests/util/test_file_helpers.py
#	tests/util/test_pip.py
#	tests/util/test_repeated_timer.py
#	tests/util/test_resettable_timer.py
#	versioneer.py
2020-10-07 21:08:44 +02:00
Gina Häußge 0bdedffac3 Merge pull request #3753 from frenck/frenck-2020-0005
Use py3 style super calls
2020-09-28 15:08:45 +02:00
Franck Nijhof 86e6cd595f Use py3 style super calls 2020-09-28 14:51:09 +02:00
Gina Häußge 5faff84a9d Merge pull request #3752 from frenck/frenck-2020-0004
Use py3 style classes
2020-09-28 13:40:32 +02:00
Franck Nijhof 656b0edb90 Use py3 style classes 2020-09-28 12:53:04 +02:00
Gina Häußge 7f042b1c55 Merge remote-tracking branch 'origin/devel' into devel 2020-09-28 11:49:44 +02:00
Gina Häußge c574947e93 Merge branch 'maintenance' into devel 2020-09-28 11:49:22 +02:00
Gina Häußge 0949975fcd Merge pull request #3750 from frenck/frenck-2020-0003
Cleanup encoding pragma headers and future imports
2020-09-28 11:46:41 +02:00
Gina Häußge a24dad6bdb Merge branch 'maintenance' into devel 2020-09-28 11:43:17 +02:00
Franck Nijhof 025fb23fed Cleanup encoding pragma headers and future imports 2020-09-25 22:56:25 +02:00
Gina Häußge 46beea8972 Merge branch 'maintenance' into devel 2020-09-17 16:44:16 +02:00
Gina Häußge 67378e1d55 Merge branch 'maintenance' into devel 2020-09-17 15:25:59 +02:00
Gina Häußge 95ab458677 📝 Fix docs build 2020-08-12 13:16:07 +02:00
Gina Häußge 49b40a4af3 Merge branch 'maintenance' into devel
# Conflicts:
#	docs/sphinxext/codeblockext.py
2020-08-10 16:36:19 +02:00
Gina Häußge 99293b9ccf Merge branch 'maintenance' into devel
# Conflicts:
#	.versioneer-lookup
2020-08-06 12:43:11 +02:00
Gina Häußge c6155e9279 Merge branch 'maintenance' into devel 2020-08-04 12:03:41 +02:00
Gina Häußge 9897fc2d56 Merge branch 'maintenance' into devel 2020-08-03 10:53:31 +02:00
Gina Häußge 35ae4af868 Merge branch 'maintenance' into devel
# Conflicts:
#	docs/development/environment.rst
#	setup.py
2020-08-03 10:32:57 +02:00
Gina Häußge 95c8902d96 Merge branch 'maintenance' into devel 2020-07-29 12:21:46 +02:00
Gina Häußge 1afd7d532c 💚 Fix a test 2020-07-15 16:18:14 +02:00
Gina Häußge eba336221e 🐛 We need markdown during setup 2020-07-15 16:06:30 +02:00
Gina Häußge 2bb0e0edfc Merge branch 'maintenance' into devel 2020-07-15 14:22:53 +02:00
Gina Häußge 248352ae5c Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
2020-07-08 13:59:57 +02:00
Gina Häußge 7ee8c5d284 Merge branch 'maintenance' into devel 2020-07-06 22:31:19 +02:00
Gina Häußge 54b3d770e7 ♻ mock => unittest.mock 2020-07-06 15:05:33 +02:00
Gina Häußge 288f6ac900 👷‍ devel is Python 3 only 2020-07-06 14:39:09 +02:00
Gina Häußge 08b48e92d3 Merge branch 'maintenance' into devel
# Conflicts:
#	.travis.yml
#	README.md
2020-07-06 14:34:59 +02:00
Gina Häußge fcf60b2a9a ⬆ devel is now 2.0.0.dev & py3 only 2020-06-16 18:12:38 +02: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
276 changed files with 17022 additions and 7750 deletions

No files matched your search

+2 -2
View File
@@ -50,7 +50,7 @@ jobs:
name: 🧪 Unit tests
strategy:
matrix:
python: ["2.7", "3.7", "3.8", "3.9", "3.10"]
python: ["3.7", "3.8", "3.9", "3.10"]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
@@ -70,7 +70,7 @@ jobs:
needs: build
strategy:
matrix:
python: ["2.7", "3.7", "3.8", "3.9", "3.10"]
python: ["3.7", "3.8", "3.9", "3.10"]
installable: ["wheel", "sdist"]
runs-on: ubuntu-latest
steps:
+2 -2
View File
@@ -14,7 +14,7 @@ jobs:
strategy:
matrix:
os: ["ubuntu-latest"]
python: ["2.7", "3.7", "3.8", "3.9", "3.10"]
python: ["3.7", "3.8", "3.9", "3.10"]
branch: ["master"]
runs-on: ${{ matrix.os }}
steps:
@@ -49,7 +49,7 @@ jobs:
strategy:
matrix:
os: ["ubuntu-latest"]
python: ["2.7", "3.7", "3.8", "3.9", "3.10"]
python: ["3.7", "3.8", "3.9", "3.10"]
runs-on: ${{ matrix.os }}
steps:
- name: 👀 Determine latest release
-1
View File
@@ -19,7 +19,6 @@ win32-Cura-*
linux-Cura-*
*.iml
Printrun
=======
.idea
.vscode
.DS_Store
+11 -3
View File
@@ -1,7 +1,7 @@
exclude: ^(src/octoprint/vendor/|src/octoprint/static/js/lib|src/octoprint/static/vendor|tests/static/js/lib|tests/util/_files|docs/|scripts/|translations/|.*\.css|.*\.svg)
exclude: ^(src/octoprint/vendor/|src/octoprint/static/js/lib|src/octoprint/static/vendor|tests/static/js/lib|tests/util/_files|docs/|scripts/|translations/|versioneer.py|.*\.css|.*\.svg)
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
rev: v3.2.0
hooks:
- id: end-of-file-fixer
- id: trailing-whitespace
@@ -11,15 +11,23 @@ repos:
- id: check-toml
- id: check-merge-conflict
- id: fix-encoding-pragma
args: ["--remove"]
- repo: https://github.com/asottile/pyupgrade
rev: v2.10.0
hooks:
- id: pyupgrade
args: ["--py37-plus"]
- repo: https://github.com/OctoPrint/codemods
rev: devel
hooks:
- id: codemod_detect_past_builtins_imports
args: ["--ignore", "src/octoprint/vendor"]
- id: codemod_not_in
args: ["--ignore", "src/octoprint/vendor"]
- id: codemod_remove_float_conversion
args: ["--ignore", "src/octoprint/vendor"]
- id: codemod_remove_future_imports
args: ["--ignore", "src/octoprint/vendor"]
- repo: https://github.com/pre-commit/mirrors-isort
rev: v5.5.4
hooks:
@@ -30,7 +38,7 @@ repos:
- id: black
args: ["--config", "black.toml"]
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.1
rev: 3.8.4
hooks:
- id: flake8
additional_dependencies:
+1
View File
@@ -157,6 +157,7 @@ date of first contribution):
* [Christian Würthner](https://github.com/crysxd)
* [Maciej Urbański](https://github.com/rooterkyberian)
* [Adam Wolf](https://github.com/adamwolf)
* [Carey Metcalfe](https://github.com/pR0Ps)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
+2 -2
View File
@@ -69,7 +69,7 @@ which is a custom SD card image that includes OctoPrint plus dependencies.
The generic steps that should basically be done regardless of operating system
and runtime environment are the following (as *regular
user*, please keep your hands *off* of the `sudo` command here!) - this assumes
you already have Python 2.7, 3.6 or 3.7, pip and virtualenv and their dependencies set up on your system:
you already have Python 3.6, 3.7 or 3.8, pip and virtualenv and their dependencies set up on your system:
1. Create a user-owned virtual environment therein: `virtualenv venv`. If you want to specify a specific python
to use instead of whatever version your system defaults to, you can also explicitly require that via the `--python`
@@ -87,7 +87,7 @@ access control as necessary.
OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing
OctoPrint via `pip`.
OctoPrint currently supports Python 2.7, 3.6 and 3.7.
OctoPrint currently supports Python 3.6, 3.7 and 3.8.
## Usage
+3
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
@@ -74,6 +76,7 @@
* [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0
* [websocket-client](https://github.com/liris/websocket-client): LGPLv3
* [wrapt](http://wrapt.readthedocs.org/): BSD
* [zipstream-ng](https://github.com/pR0Ps/zipstream-ng): LGPLv3
## Development (testing, documentation generation, etc)
+2 -17
View File
@@ -12,11 +12,11 @@ Authorization
=============
If :ref:`Access Control <sec-features-access_control>` is enabled OctoPrint's API expects an API key to be supplied with each request. This API
key can be either the globally configured one, a user specific one or an app and user specific one as generated by the
key can be either a user specific one or an app and user specific one as generated by the
authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
Clients are advised to implement the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` first and
fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used.
fallback on directing the user to manually supply the the user specific API key.
The API key must either be supplied in the custom HTTP header ``X-Api-Key``, e.g.
@@ -52,21 +52,6 @@ will be denied with a :http:statuscode:`403`.
If :ref:`Access Control <sec-features-access_control>` is disabled, OctoPrint will treat any unauthenticated anonymous requests and thus also requests
with an invalid or outright missing API key as requests with full admin rights!
.. note::
The API key requirements changed in 1.3.11. Up to that version, even if Access Control was disabled, all requests needed to
be supplied with an API Key. To make the webinterface work under these circumstances, an unauthenticated anonymous API key was injected into the
HTML page and also available on the :ref:`Push API <sec-api-push>`. The presence and ready availability of this unauthenticated
anonymous "UI API key" caused confusion and false alarm among users and didn't contribute to the security of the platform in a
meaningful way, so it was finally abandoned in 1.3.11.
.. _fig-api-general-globalapikey:
.. figure:: ../images/settings-global-api-key.png
:align: center
:alt: Global API key in the API settings
The global API key can be found in the "API" settings
.. _fig-api-general-userapikey:
.. figure:: ../images/settings-user-api-key.png
:align: center
-17
View File
@@ -71,23 +71,6 @@ Save settings
}
}
.. _sec-api-settings-generateapikey:
Regenerate the system wide API key
==================================
.. http:post:: /api/settings/apikey
Generates a new system wide API key.
Does not expect a body. Will return the generated API key as ``apikey``
property in the JSON object contained in the response body.
Requires admin rights.
:status 200: No error
:status 403: No admin rights
.. _sec-api-settings-fetchtemplaatedata:
Fetch template data
-6
View File
@@ -120,9 +120,6 @@ octoprint.plugin.backup.additional_excludes
.. code-block:: python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import octoprint.plugin
import os
@@ -150,9 +147,6 @@ octoprint.plugin.backup.additional_excludes
.. code-block:: python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import octoprint.plugin
import os
-3
View File
@@ -626,9 +626,6 @@ octoprint.plugin.softwareupdate.check_config
.. code-block:: python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
def get_update_information(*args, **kwargs):
return dict(
updateplugindemo=dict(
+2 -9
View File
@@ -1,7 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
#
# OctoPrint documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 02 17:08:50 2013.
#
@@ -45,11 +41,8 @@ extensions = [
"sphinx.ext.intersphinx",
]
todo_include_todos = True
intersphinx_mapping = {
"python": ("https://docs.python.org/3", None),
"python2": ("https://docs.python.org/2", None),
"pyserial": ("https://pythonhosted.org/pyserial", None),
}
intersphinx_mapping = {'python': ('https://docs.python.org/3', None),
'pyserial': ('https://pythonhosted.org/pyserial', None)}
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
+32 -104
View File
@@ -14,7 +14,7 @@ below.
* Prerequisites:
* `Python 3.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Python 3.8 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Git <https://git-scm.com>`_
* Checkout the OctoPrint sources from their Git repository:
@@ -24,15 +24,17 @@ below.
* Enter the checked out source folder: ``cd OctoPrint``
* Create a virtual environment in the checked out source folder to use for
installing and running OctoPrint and its dependencies. Creating virtual environments avoids potential versioning
issues for the dependencies with system wide installed instances: ``virtualenv --python=python3 venv3``
issues for the dependencies with system wide installed instances:
* ``virtualenv --python=python3 venv``
.. note::
This assumes that the ``python3`` binary is available directly on your ``PATH``. If
it cannot be found on your ``PATH`` like this you'll need to specify the full path here,
e.g. ``virtualenv --python=/path/to/python3/bin/python venv3``
This assumes that `python3` is a binary available directly on your ``PATH``. If your Python 3
binary cannot be found on your ``PATH`` like this you'll need to specify the full path to it here,
e.g. ``virtualenv --python=/path/to/python3/bin/python venv``
* Activate the virtual environment: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
* Activate the virtual environment: ``source venv/bin/activate`` (Linux, macOS) or ``source venv/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment:
@@ -61,31 +63,6 @@ When the virtual environment is activated you can then:
folder -- the documentation will be available in the newly created ``_build``
directory. You can simply browse it locally by opening ``index.html``
If a Python 2 environment is also desired (e.g. for maintenance reasons), also do the following extra steps:
* Prerequisites:
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* Create a virtual environment in the checked out source folder for Python 2: ``virtualenv --python=python2 venv2``
.. note::
This assumes that the ``python2`` binary is available directly on your ``PATH``. If
it cannot be found on your ``PATH`` like this you'll need to specify the full path here,
e.g. ``virtualenv --python=/path/to/python2/bin/python venv2``
* Activate the virtual environment: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment:
* ``pip install --upgrade pip``
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
including its regular *and* development and plugin development dependencies:
* ``pip install -e '.[develop,plugins]'``
.. _sec-development-environment-source-linux:
Linux
@@ -101,7 +78,13 @@ installed:
.. code-block:: none
sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv python3 python3-virtualenv python3-dev git libyaml-dev build-essential
sudo apt-get install python3 python3-pip python3-dev python3-setuptools python3-virtualenv git libyaml-dev build-essential
.. todo::
Using a Linux distribution that doesn't use ``apt``? Please send a
`Pull Request <https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
steps into this guide!
Then:
@@ -110,43 +93,15 @@ Then:
cd ~/devel
git clone https://github.com/OctoPrint/OctoPrint.git
cd OctoPrint
virtualenv --python=python3 venv3
source ./venv3/bin/activate
virtualenv --python=python3 venv
source ./venv/bin/activate
pip install --upgrade pip
pip install -e '.[develop,plugins,docs]'
pre-commit install
git config blame.ignoreRevsFile .git-blame-ignore-revs
.. _sec-development-environment-linux-python2:
Optional Python 2 environment
.............................
If a Python 2 environment is also desired:
* On apt based distributions (e.g. Debian, Ubuntu, ...):
.. code-block:: none
sudo apt-get install python2 python2-dev python-pip python-setuptools python-virtualenv
Then:
.. code-block:: none
virtualenv --python=python2 venv2
source ./venv2/bin/activate
pip install --upgrade pip
pip install -e '.[develop,plugins]'
You can then start OctoPrint via ``octoprint`` after activating one of the two virtual environments.
.. todo::
Using a Linux distribution that doesn't use ``apt``? Please send a
`Pull Request <https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
steps into this guide!
.. _sec-development-environment-windows:
Windows
@@ -157,20 +112,19 @@ location, please substitute accordingly.
First download & install:
* `Git for Windows <https://git-for-windows.github.io/>`_
* `Latest *stable* Python 3 release from python.org <https://www.python.org/downloads/windows/>`_
* `The current Python 3.8 Windows x86 executable installer <https://www.python.org/downloads/windows/>`_
* make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
* it's recommended to install Python 3 into ``C:\Python3`` - if you select
different install locations please substitute accordingly
* it's also recommended to install for all users
* `Build Tools For Visual Studio 2019 <https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019>`_
* `Build Tools for Visual Studio 2019 <https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019>`_
* install "C++ build tools" and ensure the latest versions of "MSVCv142 - VS 2019 C++ x64/x86 build tools" and
"Windows 10 SDK" are checked under individual components.
"Windows 10 SDK" are checked.
* `Git for Windows <https://git-scm.com/downloads>`_
Open the Git Bash you just installed and in that:
@@ -181,37 +135,12 @@ Open the Git Bash you just installed and in that:
git clone https://github.com/OctoPrint/OctoPrint.git
cd OctoPrint
virtualenv --python=C:/Python3/python.exe venv3
source ./venv3/Scripts/activate
pip install --upgrade pip
source ./venv/Scripts/activate
python -m pip install --upgrade pip
python -m pip install -e '.[develop,plugins,docs]'
pre-commit install
git config blame.ignoreRevsFile .git-blame-ignore-revs
.. _sec-development-environment-windows-python2:
Optional Python 2 environment
.............................
If a Python 2 environment is also desired, then also download and install
* `Python 2.7.18 MSI installer <https://octoprint.org/files/python-2.7.18.msi>`_ (mirrored on octoprint.org)
* it's recommended to install Python 2.7 into ``C:\Python27`` - if you select
different install locations please substitute accordingly
* it's also recommended to install for all users
* `Microsoft Visual C++ Compiler for Python 2.7 <https://octoprint.org/files/VCForPython27.msi>`_ (mirrored on octoprint.org)
Then:
.. code-block:: none
cd /c/Devel/OctoPrint
virtualenv --python=C:/Python27/python.exe venv2
source ./venv2/Scripts/activate
python -m pip install --upgrade pip
pip install -e '.[develop,plugins]'
.. _sec-development-environment-windows-optional:
Optional but recommended tools
@@ -220,7 +149,6 @@ Optional but recommended tools
These are some tools that are recommended but not required to have on hand:
* `Visual Studio Code <https://code.visualstudio.com/download>`_
* `Windows Terminal <https://github.com/microsoft/terminal>`_
Add the following profile to ``profiles.list`` in the settings, that will allow you to
@@ -313,11 +241,11 @@ PyCharm
- Register virtual environments:
- **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...",
select OctoPrint ``venv3`` folder (e.g. ``~/devel/OctoPrint/venv3`` or ``C:\Devel\OctoPrint\venv3``).
select OctoPrint ``venv`` folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``).
- **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." >
"Virtualenv Environment > "Existing Environment", select OctoPrint ``venv3`` folder (e.g. ``~/devel/OctoPrint/venv3``).
"Virtualenv Environment > "Existing Environment", select OctoPrint ``venv`` folder (e.g. ``~/devel/OctoPrint/venv``).
If desired, repeat for the ``venv2`` folder, or any other additional Python venvs.
If desired, repeat for any other additional Python venvs (e.g. different versions).
- Right click "src" in project tree, mark as source folder
- Add Run/Debug Configuration, select "Python":
@@ -362,7 +290,7 @@ PyCharm
* Module name: ``sphinx.cmd.build``
* Parameters: ``-v -T -E ./docs ./docs/_build -b html``
* Project: ``OctoPrint``
* Python interpreter: ``venv3`` environment (the docs build requires Python 3)
* Python interpreter: ``venv`` environment
* Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
* Just like with the run configuration for the server you can also have the dependencies auto-update when building
the documentation, see above on how to set this up.
@@ -375,14 +303,14 @@ PyCharm
* Name: pre-commit
* File type: Python
* Scope: Module 'OctoPrint'
* Program: ``<OctoPrint venv3 folder>/bin/pre-commit`` (Linux) or ``<OctoPrint venv3 folder>/Scripts/pre-commit`` (Windows)
* Program: ``$PyInterpreterDirectory$/bin/pre-commit`` (Linux) or ``$PyInterpreterDirectory$/Scripts/pre-commit`` (Windows)
* Arguments: ``run --hook-stage manual --files $FilePath$``
* Output paths to refresh: ``$FilePath$``
* Working directory: ``$ProjectFileDir$``
* disable "Auto-save edited files to trigger the watched"
* enable "Trigger the watched on external changes"
To switch between virtual environments (e.g. Python 3 and 2), all you need to do now is change the Project Default Interpreter and restart
To switch between virtual environments (e.g. various Python 3 versions), all you need to do now is change the Project Default Interpreter and restart
OctoPrint. On current PyCharm versions you can do that right from a small selection field in the footer of the IDE.
Otherwise go through Settings.
@@ -466,7 +394,7 @@ Visual Studio Code (vscode)
}
]
}
In the terminal install the python extension by running this command:
.. code-block:: bash
@@ -486,7 +414,7 @@ Visual Studio Code (vscode)
* Your terminal inside vscode uses the virtual python environment
* Saving a file will run an auto formatter and import sort
* ``Ctrl+Shift+B`` can be used to run the ``build docs`` task to rebuild the documentation
+4 -4
View File
@@ -24,7 +24,7 @@ The following example defines a control for enabling the cooling fan with a vari
feedback evaluation for the result of the M114 "Get Position" gcode inside a section named "Reporting" and finally
a GCODE script including user input.
.. code-block-ext:: yaml
.. code-block:: yaml
controls:
- name: Fan
@@ -181,7 +181,7 @@ Controls
additional input fields. ``command``/``commands`` may contain placeholders to be replaced by the values obtained
from the user for the defined input fields:
.. code-block-ext:: yaml
.. code-block:: yaml
name: Enable Fan
command: M106 S%(speed)s
@@ -253,7 +253,7 @@ Examples
Parameterized GCODE Script
..........................
.. code-block-ext:: yaml
.. code-block:: yaml
:caption: Control definition in ~/.octoprint/config.yaml
:name: code-features-custom_controls-example-gcode_script-config_yaml
@@ -268,7 +268,7 @@ Parameterized GCODE Script
min: 1
step: 1
.. code-block-ext:: jinja
.. code-block:: jinja
:caption: ~/.octoprint/scripts/gcode/custom/dance.gco
:name: code-features-custom_controls-example-gcode_script-dance_gco
+4 -7
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "The MIT License <http://opensource.org/licenses/MIT>"
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
@@ -110,7 +107,7 @@ class CodeBlockExt(CodeBlock):
return literal
class PygmentsBridgeExt(object):
class PygmentsBridgeExt:
"""
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
which calls the parent implementation for lexer selection, then
@@ -136,7 +133,7 @@ class PygmentsBridgeExt(object):
# For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to
# include the whitespace filter.
class whitespace(object):
class whitespace:
def __init__(self, lexer):
self._lexer = lexer
self._orig_filters = lexer.filters
@@ -232,7 +229,7 @@ class PygmentsBridgeExt(object):
return hlsource
class whitespace_highlighter(object):
class whitespace_highlighter:
"""
Context manager for adapting the used highlighter on a translator for a given node's whitespace properties.
"""
@@ -278,6 +275,6 @@ def setup(app):
# custom node type
handler = (visit_literal_block_ext, depart_literal_block_ext)
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
app.add_node(literal_block_ext, html=handler)
return {"version": "0.1"}
+1 -4
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "The MIT License <http://opensource.org/licenses/MIT>"
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
@@ -124,4 +121,4 @@ def setup(app):
app.add_directive("onlineinclude", OnlineIncludeDirective)
handler = (visit_onlineinclude, depart_onlineinclude)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
app.add_node(OnlineIncludeDirective, html=handler)
-3
View File
@@ -1,7 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import sys
+38 -101
View File
@@ -1,8 +1,4 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import os
import re
import sys
from distutils.command.build_py import build_py as _build_py
@@ -16,11 +12,12 @@ import octoprint_setuptools # noqa: F401,E402
# ----------------------------------------------------------------------------------------
# Supported python versions
# we test against 2.7, 3.6 and 3.7, so that's what we'll mark as supported
PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
PYTHON_REQUIRES = ">=3.7,<4"
# Requirements for setup.py
SETUP_REQUIRES = ["markdown>=3.1,<3.2"] # newer versions require Python 3
SETUP_REQUIRES = [
"markdown>=3.2.2,<4",
]
# Requirements for our application
INSTALL_REQUIRES = [
@@ -31,82 +28,52 @@ INSTALL_REQUIRES = [
# the following dependencies are non trivial to update since later versions
# introduce backwards incompatible changes that might affect plugins, or due to
# other observed problems
"markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3
"markdown>=3.1,<3.2", # newer versions require Python 3
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
"wrapt>=1.12.1,<1.13", # newer versions fail to build on OctoPi 0.15
# anything below this should be checked on releases for new versions
"flask>=1.1.4,<2", # newer versions require Python 3
"Jinja2>=2.11.3,<3", # newer versions require Python 3
"tornado>=6.0.4,<7",
"markdown>=3.2.2,<4",
"flask>=2,<3",
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
"Flask-Babel>=1.0,<2", # newer versions require Python 3
"Flask-Babel>=2.0,<3",
"Flask-Assets>=2.0,<3",
"werkzeug>=1.0.1,<2", # newer versions require Python 3
"itsdangerous>=1.1.0,<2", # newer versions require Python 3
"cachelib>=0.1,<0.2", # newer versions require Python 3
"cachelib>=0.2,<0.3",
"PyYAML>=5.4.1,<6",
"pyserial>=3.4,<4",
"netaddr>=0.8,<0.9", # changelog hints at breaking changes on minor version increases
"watchdog==0.10.4", # newer versions require Python 3
"sarge==0.1.6",
"netifaces>=0.11,<1",
"netaddr>=0.7.19,<1",
"watchdog==1.0.0",
"sarge==0.1.5post0",
"netifaces>=0.10.9,<1",
"pylru>=1.2,<2",
"pkginfo>=1.7.1,<2",
"requests>=2.26.0,<3",
"rsa>=4.0,<5",
"pkginfo>=1.5.0.1,<2",
"requests>=2.23.0,<3",
"semantic_version>=2.8.5,<3",
"psutil>=5.8,<6",
"Click>=7.1.2,<8", # newer versions require Python 3
"future>=0.18.2,<1",
"websocket-client>=0.59,<1", # newer versions require Python 3
"emoji>=1.4.2,<2",
"sentry-sdk>=1.3.1,<2",
"filetype>=1.0.7,<2",
"zipstream-new>=1.1.8,<1.2",
# vendor bundled dependencies
"blinker>=1.4,<2", # dependency of flask_principal
]
# Python 2 specific requirements
INSTALL_REQUIRES_PYTHON2 = [
"feedparser>=5.2.1,<6", # newer versions require Python 3
"tornado==5.1.1", # newer versions require Python 3
"futures>=3.3,<4",
"monotonic>=1.6,<2",
"scandir>=1.10,<2",
"chainmap>=1.0.3,<2",
"typing>=3.10.0.0,<4",
"enum34>=1.1.10,<1.2",
"frozendict==1.2", # newer versions require Python 3
"colorlog<5", # newer versions require Python 3
# vendor bundled dependencies
"unidecode<1.3", # dependency of awesome-slugify, newer versions require Python 3
]
# Python 3 specific requirements
INSTALL_REQUIRES_PYTHON3 = [
"Click>=8.0.3,<9",
"feedparser>=6.0.8,<7",
"tornado>=6,<7", # tornado < 6 is incompatible with Python 3.10
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
"future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins
"websocket-client>=1.2.1,<2",
"wrapt>=1.12.1,<2",
"emoji>=1.4.2,<2",
"sentry-sdk>=1.5.0,<2",
"filetype>=1.0.7,<2",
"frozendict>=2.0,<3",
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
"zipstream-ng>=1.3.1,<2.0.0",
"pathvalidate>=2.4.1,<3",
"colorlog>=5.0.1,<6",
# vendor bundled dependencies
"blinker>=1.4,<2", # dependency of flask_principal
"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": [
# Testing dependencies
"mock>=3.0.5,<4 ; python_version < '3'",
"pytest==4.6.10 ; python_version < '3'",
"mock>=4,<5 ; python_version >= '3'",
"pytest>=6.2.5,<7 ; python_version >= '3'",
"mock>=4,<5",
"pytest>=6.2.5,<7",
"pytest-doctest-custom>=1.0.0,<2",
"ddt",
# pre-commit
@@ -116,7 +83,7 @@ EXTRA_REQUIRES = {
],
# Dependencies for developing OctoPrint plugins
"plugins": ["cookiecutter>=1.7.2,<1.8"],
# Dependencies for building the documentation - Python 3 required!
# Dependencies for building the documentation
"docs": [
"sphinx>=3,<4",
"sphinxcontrib-httpdomain",
@@ -124,47 +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 = []
# adapted from https://hynek.me/articles/conditional-python-dependencies/
if int(setuptools.__version__.split(".", 1)[0]) < 18:
# no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies
# would get lost there
assert "bdist_wheel" not in sys.argv
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
def _filter_by_python_version_marker(requirements):
for requirement in requirements:
req_match = re.match(
r"^(?P<req>.+);\s*(?P<marker>python_version.+)$", requirement
)
if not req_match:
yield requirement
else:
if eval(req_match.group("marker"), {}, {"python_version": sys.version}):
yield req_match.group("req")
EXTRA_REQUIRES = {
extra: list(_filter_by_python_version_marker(extra_requirements))
for extra, extra_requirements in EXTRA_REQUIRES.items()
}
if sys.version_info[0] < 3:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
else:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON3
if sys.platform == "darwin":
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
else:
# environment markers supported
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
EXTRA_REQUIRES[":python_version >= '3'"] = INSTALL_REQUIRES_PYTHON3
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
# -----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
@@ -198,7 +137,7 @@ def md_to_html_build_py_factory(files, baseclass):
source = entry
dest = os.path.join(target_dir, source + ".html")
print("Rendering markdown from {} to {}".format(source, dest))
print(f"Rendering markdown from {source} to {dest}")
from markdown import markdownFromFile
@@ -286,8 +225,6 @@ def params():
"Natural Language :: German",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
+32 -47
View File
@@ -1,7 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import logging as log
import os
import sys
@@ -30,30 +27,7 @@ urllib3_ssl = True
a sound SSL environment or not."""
version_info = sys.version_info
if version_info.major == 2 and version_info.minor <= 7 and version_info.micro < 9:
try:
# make sure our requests version of urllib3 is properly patched (if possible)
import requests.packages.urllib3.contrib.pyopenssl
requests.packages.urllib3.contrib.pyopenssl.inject_into_urllib3()
except ImportError:
urllib3_ssl = False
try:
import urllib3
# only proceed if urllib3 is even installed on its own
try:
# urllib3 is there, let's patch that too
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
except ImportError:
urllib3_ssl = False
except ImportError:
pass
elif version_info.major == 3 and version_info.minor >= 8 and sys.platform == "win32":
if version_info.major == 3 and version_info.minor >= 8 and sys.platform == "win32":
# Python 3.8 makes proactor event loop the default on Windows, Tornado doesn't like that
#
# see https://github.com/tornadoweb/tornado/issues/2608
@@ -306,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": {
@@ -324,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,
},
@@ -356,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": {
@@ -421,7 +412,7 @@ def octoprint_plugin_inject_factory(settings, components):
def wrapper(*args, **kwargs):
tags = kwargs.get("tags", set()) | {
"source:plugin",
"plugin:{}".format(name),
f"plugin:{name}",
}
kwargs["tags"] = tags
return f(*args, **kwargs)
@@ -431,9 +422,7 @@ def octoprint_plugin_inject_factory(settings, components):
class TaggedFuncsPrinter(wrapt.ObjectProxy):
def __getattribute__(self, attr):
__wrapped__ = super(TaggedFuncsPrinter, self).__getattribute__(
"__wrapped__"
)
__wrapped__ = super().__getattribute__("__wrapped__")
if attr == "__wrapped__":
return __wrapped__
@@ -548,7 +537,7 @@ def init_custom_events(plugin_manager):
if isinstance(result, (list, tuple)):
for event in result:
constant, value = octoprint.events.Events.register_event(
event, prefix="plugin_{}_".format(name)
event, prefix=f"plugin_{name}_"
)
logger.debug(
'Registered event {} of plugin {} as Events.{} = "{}"'.format(
@@ -557,7 +546,7 @@ def init_custom_events(plugin_manager):
)
except Exception:
logger.exception(
"Error while retrieving custom event list from plugin {}".format(name),
f"Error while retrieving custom event list from plugin {name}",
extra={"plugin": name},
)
@@ -684,7 +673,7 @@ def init_pluginsystem(
disabled_from_overlays[name] = (disabled_plugins, order)
settings_overlays[name] = overlay
logger.debug("Found settings overlay on plugin {}".format(name))
logger.debug(f"Found settings overlay on plugin {name}")
def handle_plugins_loaded(
startup=False, initialize_implementations=True, force_reload=None
@@ -726,7 +715,7 @@ def init_pluginsystem(
def handle_plugin_enabled(name, plugin):
if name in settings_overlays:
settings.add_overlay(settings_overlays[name])
logger.info("Added settings overlay from plugin {}".format(name))
logger.info(f"Added settings overlay from plugin {name}")
pm.on_plugin_loaded = handle_plugin_loaded
pm.on_plugins_loaded = handle_plugins_loaded
@@ -753,7 +742,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
format_entry = (
lambda x: "{} ({})".format(x[0], x[1])
if isinstance(x, (list, tuple)) and len(x) == 2
else "{} (any)".format(x)
else f"{x} (any)"
)
return ", ".join(map(format_entry, entries))
@@ -792,7 +781,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
)
)
for version in entry["versions"]:
result.append((entry["plugin"], "=={}".format(version)))
result.append((entry["plugin"], f"=={version}"))
else:
logger.debug("Blacklisted plugin: {}".format(entry["plugin"]))
result.append(entry["plugin"])
@@ -954,10 +943,6 @@ def main():
# cut off stuff from the beginning
args = args[-1 * sys_args_length :] if sys_args_length else []
from octoprint.util.fixes import patch_sarge_async_on_py2
patch_sarge_async_on_py2()
from octoprint.cli import octo
octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
-3
View File
@@ -1,7 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
if __name__ == "__main__":
import octoprint
+5 -9
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
@@ -13,7 +10,6 @@ from __future__ import absolute_import, division, print_function, unicode_litera
"""Git implementation of _version.py."""
import errno
import io
import logging
import os
import re
@@ -90,7 +86,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
stderr=(subprocess.PIPE if hide_stderr else None),
)
break
except EnvironmentError:
except OSError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
@@ -100,7 +96,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
return None
else:
if verbose:
print("unable to find command, tried {}".format(commands))
print(f"unable to find command, tried {commands}")
return None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
@@ -143,7 +139,7 @@ def git_get_keywords(versionfile_abs):
# _version.py.
keywords = {}
try:
f = io.open(versionfile_abs, "rt", encoding="utf-8")
f = open(versionfile_abs, encoding="utf-8")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
@@ -154,7 +150,7 @@ def git_get_keywords(versionfile_abs):
if mo:
keywords["full"] = mo.group(1)
f.close()
except EnvironmentError:
except OSError:
pass
return keywords
@@ -337,7 +333,7 @@ def git_parse_lookup_file(path):
import re
lookup = []
with io.open(path, "rt", encoding="utf-8") as f:
with open(path, encoding="utf-8") as f:
for line in f:
if "#" in line:
line = line[: line.index("#")]
-3
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
ADMIN_GROUP = "admins"
USER_GROUP = "users"
GUEST_GROUP = "guests"
+8 -14
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Marc Hannappel <salandora@gmail.com>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -9,8 +6,6 @@ import logging
import os
from functools import partial
from past.builtins import basestring
from octoprint.access import ADMIN_GROUP, GUEST_GROUP, READONLY_GROUP, USER_GROUP
from octoprint.access.permissions import OctoPrintPermission, Permissions
from octoprint.settings import settings
@@ -24,10 +19,10 @@ GroupNeed.__doc__ = """A need with the method preset to `"group"`."""
class GroupPermission(Permission):
def __init__(self, key):
need = GroupNeed(key)
super(GroupPermission, self).__init__(need)
super().__init__(need)
class GroupManager(object):
class GroupManager:
@classmethod
def default_permissions_for_group(cls, group):
result = []
@@ -175,10 +170,9 @@ class GroupManager(object):
return list(filter(lambda x: x is not None, [self._to_group(g) for g in groups]))
def _to_group(self, group):
# noinspection PyCompatibility
if isinstance(group, Group):
return group
elif isinstance(group, basestring):
elif isinstance(group, str):
return self.find_group(group)
elif isinstance(group, dict):
return self.find_group(group.get("key"))
@@ -186,17 +180,17 @@ class GroupManager(object):
return None
def _notify_listeners(self, action, group, *args, **kwargs):
method = "on_group_{}".format(action)
method = f"on_group_{action}"
for listener in self._group_change_listeners:
try:
getattr(listener, method)(group, *args, **kwargs)
except Exception:
self._logger.exception(
"Error notifying listener {!r} via {}".format(listener, method)
f"Error notifying listener {listener!r} via {method}"
)
class GroupChangeListener(object):
class GroupChangeListener:
def on_group_added(self, group):
pass
@@ -318,7 +312,7 @@ class FilebasedGroupManager(GroupManager):
except Exception:
self._logger.exception(
"Error while loading groups from file {}".format(self._groupfile)
f"Error while loading groups from file {self._groupfile}"
)
def _save(self, force=False):
@@ -522,7 +516,7 @@ class GroupCantBeChanged(Exception):
Exception.__init__(self, "Group can't be changed: %s" % key)
class Group(object):
class Group:
def __init__(
self,
key,
+4 -12
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Marc Hannappel <salandora@gmail.com>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -10,10 +7,6 @@ from functools import wraps
from flask import abort, g
from flask_babel import gettext
from future.utils import with_metaclass
# noinspection PyCompatibility
from past.builtins import basestring
from octoprint.access import ADMIN_GROUP, READONLY_GROUP, USER_GROUP
from octoprint.vendor.flask_principal import Need, Permission, PermissionDenied, RoleNeed
@@ -32,12 +25,11 @@ class OctoPrintPermission(Permission):
def convert_to_needs(cls, needs):
result = []
for need in needs:
# noinspection PyCompatibility
if isinstance(need, Need):
result.append(need)
elif isinstance(need, Permission):
result += need.needs
elif isinstance(need, basestring):
elif isinstance(need, str):
result.append(RoleNeed(need))
return result
@@ -149,7 +141,7 @@ class PluginOctoPrintPermission(OctoPrintPermission):
return result
class PluginIdentityContext(object):
class PluginIdentityContext:
"""Identity context for not initialized Permissions
Needed to support @Permissions.PLUGIN_X_Y.require()
@@ -254,7 +246,7 @@ class PermissionsMetaClass(type):
key = p.key
elif isinstance(p, dict):
key = p.get("key")
elif isinstance(p, basestring):
elif isinstance(p, str):
key = p
if key is None:
@@ -275,7 +267,7 @@ class PermissionsMetaClass(type):
return None
class Permissions(with_metaclass(PermissionsMetaClass)):
class Permissions(metaclass=PermissionsMetaClass):
# Special permission
ADMIN = OctoPrintPermission(
+27 -38
View File
@@ -1,20 +1,14 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import hashlib
import logging
import os
import time
import uuid
# noinspection PyCompatibility
from builtins import bytes, range
import wrapt
from flask_login import AnonymousUserMixin, UserMixin
from past.builtins import basestring
from werkzeug.local import LocalProxy
from octoprint.access.groups import Group, GroupChangeListener
@@ -22,10 +16,10 @@ from octoprint.access.permissions import OctoPrintPermission, Permissions
from octoprint.settings import settings as s
from octoprint.util import atomic_write, deprecated, generate_api_key
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util import monotonic_time, to_bytes, yaml
from octoprint.util import to_bytes, yaml
class UserManager(GroupChangeListener, object):
class UserManager(GroupChangeListener):
def __init__(self, group_manager, settings=None):
self._group_manager = group_manager
self._group_manager.register_listener(self)
@@ -49,8 +43,10 @@ class UserManager(GroupChangeListener, object):
def anonymous_user_factory(self):
return AnonymousUser([self._group_manager.guest_group])
def api_user_factory(self):
return ApiUser([self._group_manager.admin_group, self._group_manager.user_group])
def cli_user_factory(self):
return LocalCliUser(
[self._group_manager.admin_group, self._group_manager.user_group]
)
@property
def enabled(self):
@@ -85,11 +81,11 @@ class UserManager(GroupChangeListener, object):
listener.on_user_logged_in(user)
except Exception:
self._logger.exception(
"Error in on_user_logged_in on {!r}".format(listener),
f"Error in on_user_logged_in on {listener!r}",
extra={"callback": fqcn(listener)},
)
self._logger.info("Logged in user: {}".format(user.get_id()))
self._logger.info(f"Logged in user: {user.get_id()}")
return user
@@ -123,17 +119,17 @@ class UserManager(GroupChangeListener, object):
listener.on_user_logged_out(user, stale=stale)
except Exception:
self._logger.exception(
"Error in on_user_logged_out on {!r}".format(listener),
f"Error in on_user_logged_out on {listener!r}",
extra={"callback": fqcn(listener)},
)
self._logger.info("Logged out user: {}".format(user.get_id()))
self._logger.info(f"Logged out user: {user.get_id()}")
def _cleanup_sessions(self):
for session, user in list(self._session_users_by_session.items()):
if not isinstance(user, SessionUser):
continue
if user.created + (24 * 60 * 60) < monotonic_time():
if user.created + (24 * 60 * 60) < time.monotonic():
self._logger.info(
"Cleaning up user session {} for user {}".format(
session, user.get_id()
@@ -271,9 +267,7 @@ class UserManager(GroupChangeListener, object):
return False
def on_group_removed(self, group):
self._logger.debug(
"Group {} got removed, removing from all users".format(group.key)
)
self._logger.debug(f"Group {group.key} got removed, removing from all users")
self.remove_groups_from_users([group])
def on_group_permissions_changed(self, group, added=None, removed=None):
@@ -284,7 +278,7 @@ class UserManager(GroupChangeListener, object):
listener.on_user_modified(user)
except Exception:
self._logger.exception(
"Error in on_user_modified on {!r}".format(listener),
f"Error in on_user_modified on {listener!r}",
extra={"callback": fqcn(listener)},
)
@@ -297,12 +291,12 @@ class UserManager(GroupChangeListener, object):
listener.on_user_modified(user)
except Exception:
self._logger.exception(
"Error in on_user_modified on {!r}".format(listener),
f"Error in on_user_modified on {listener!r}",
extra={"callback": fqcn(listener)},
)
def _trigger_on_user_modified(self, user):
if isinstance(user, basestring):
if isinstance(user, str):
# user id
users = []
try:
@@ -329,7 +323,7 @@ class UserManager(GroupChangeListener, object):
listener.on_user_modified(user)
except Exception:
self._logger.exception(
"Error in on_user_modified on {!r}".format(listener),
f"Error in on_user_modified on {listener!r}",
extra={"callback": fqcn(listener)},
)
@@ -339,7 +333,7 @@ class UserManager(GroupChangeListener, object):
listener.on_user_removed(username)
except Exception:
self._logger.exception(
"Error in on_user_removed on {!r}".format(listener),
f"Error in on_user_removed on {listener!r}",
extra={"callback": fqcn(listener)},
)
@@ -479,7 +473,7 @@ class UserManager(GroupChangeListener, object):
)(has_been_customized)
class LoginStatusListener(object):
class LoginStatusListener:
def on_user_logged_in(self, user):
pass
@@ -544,7 +538,7 @@ class FilebasedUserManager(UserManager):
# migrate from roles to permissions
if "roles" in attributes and "permissions" not in attributes:
self._logger.info(
"Migrating user {} to new granular permission system".format(name)
f"Migrating user {name} to new granular permission system"
)
groups |= set(self._migrate_roles_to_groups(attributes["roles"]))
@@ -1023,7 +1017,7 @@ class CorruptUserStorage(Exception):
##~~ Refactoring helpers
class MethodReplacedByBooleanProperty(object):
class MethodReplacedByBooleanProperty:
def __init__(self, name, message, getter):
self._name = name
self._message = message
@@ -1046,11 +1040,6 @@ class MethodReplacedByBooleanProperty(object):
return self._attr != other
def __bool__(self):
# Python 3
return self._attr
def __nonzero__(self):
# Python 2
return self._attr
def __hash__(self):
@@ -1391,8 +1380,8 @@ class SessionUser(wrapt.ObjectProxy):
wrapt.ObjectProxy.__init__(self, user)
self._self_session = "".join("%02X" % z for z in bytes(uuid.uuid4().bytes))
self._self_created = monotonic_time()
self._self_touched = monotonic_time()
self._self_created = time.monotonic()
self._self_touched = time.monotonic()
@property
def session(self):
@@ -1407,7 +1396,7 @@ class SessionUser(wrapt.ObjectProxy):
return self._self_touched
def touch(self):
self._self_touched = monotonic_time()
self._self_touched = time.monotonic()
@deprecated(
"SessionUser.get_session() has been deprecated, use SessionUser.session instead",
@@ -1430,9 +1419,9 @@ class SessionUser(wrapt.ObjectProxy):
)
##~~ User object to use when global api key is used to access the API
##~~ User object to use when CLI key is used
class ApiUser(User):
class LocalCliUser(User):
def __init__(self, groups):
User.__init__(self, "_api", "", True, [], groups)
User.__init__(self, "_cli", "", True, [], groups)
+1 -4
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -17,7 +14,7 @@ click.disable_unicode_literals_warning = True
# ~~ click context
class OctoPrintContext(object):
class OctoPrintContext:
"""Custom context wrapping the standard options."""
def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False):
+3 -8
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -99,7 +96,6 @@ def gcode_command(
import time
from octoprint.util import monotonic_time
from octoprint.util.gcodeInterpreter import gcode
throttle_callback = None
@@ -119,13 +115,13 @@ def gcode_command(
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
start_time = monotonic_time()
start_time = time.monotonic()
progress_callback = None
if progress:
def progress_callback(percentage):
click.echo("PROGRESS:{}".format(percentage))
click.echo(f"PROGRESS:{percentage}")
interpreter = gcode(progress_callback=progress_callback, incl_layers=layers)
@@ -140,7 +136,7 @@ def gcode_command(
bed_z=bedz,
)
click.echo("DONE:{}s".format(monotonic_time() - start_time))
click.echo("DONE:{}s".format(time.monotonic() - start_time))
result = interpreter.get_result()
if empty_result(result):
@@ -154,7 +150,6 @@ def gcode_command(
"happened"
)
sys.exit(-1)
click.echo("RESULTS:")
click.echo(yaml.dump(interpreter.get_result(), pretty=True))
+21 -20
View File
@@ -1,14 +1,10 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import io
import json
import os
import click
from past.builtins import unicode
import octoprint_client
from octoprint import FatalStartupError, init_settings
@@ -38,18 +34,23 @@ def create_client(
https=False,
prefix=None,
):
assert host is not None or settings is not None
assert port is not None or settings is not None
assert apikey is not None or settings is not None
if not host:
host = settings.get(["server", "host"])
host = host if host != "0.0.0.0" else "127.0.0.1"
host = "127.0.0.1"
if not port:
port = settings.getInt(["server", "port"])
if not apikey:
apikey = settings.get(["api", "key"])
cli_key_file = os.path.join(settings.getBaseFolder("generated"), "cli.key")
try:
with open(cli_key_file, encoding="utf8") as f:
apikey = f.readline()
except Exception:
raise FatalStartupError(
f"Can not authenticate with server at {host}:{port}, no key"
)
baseurl = octoprint_client.build_base_url(
https=https,
@@ -89,7 +90,7 @@ def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
"""Basic API client."""
try:
settings = None
if not host or not port or not apikey:
if not port or not apikey:
settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
@@ -114,10 +115,10 @@ def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
def log_response(response, status_code=True, body=True, headers=False):
if status_code:
click.echo("Status Code: {}".format(response.status_code))
click.echo(f"Status Code: {response.status_code}")
if headers:
for header, value in response.headers.items():
click.echo("{}: {}".format(header, value))
click.echo(f"{header}: {value}")
click.echo()
if body:
click.echo(response.text)
@@ -168,14 +169,14 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
if json_flag or yaml_flag:
if json_flag:
with io.open(file_path, "rt") as fp:
with open(file_path) as fp:
data = json.load(fp)
else:
data = yaml.load_from_file(path=file_path)
r = ctx.obj.client.post_json(path, data, timeout=timeout)
else:
with io.open(file_path, "rb") as fp:
with open(file_path, "rb") as fp:
data = fp.read()
r = ctx.obj.client.post(path, data, timeout=timeout)
@@ -192,10 +193,10 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
"str_params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, unicode]),
type=click.Tuple([str, str]),
)
@click.option(
"--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int])
"--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([str, int])
)
@click.option(
"--float",
@@ -203,7 +204,7 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
"float_params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, float]),
type=click.Tuple([str, float]),
)
@click.option(
"--bool",
@@ -211,7 +212,7 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
"bool_params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, bool]),
type=click.Tuple([str, bool]),
)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
@@ -238,7 +239,7 @@ def command(
"params",
multiple=True,
nargs=2,
type=click.Tuple([unicode, unicode]),
type=click.Tuple([str, str]),
)
@click.option("--file-name", type=click.STRING)
@click.option("--content-type", type=click.STRING)
@@ -281,7 +282,7 @@ def listen(ctx):
click.echo("--- Connection closed!")
def on_error(ws, error):
click.echo("!!! Error: {}".format(error))
click.echo(f"!!! Error: {error}")
def on_sent(ws, data):
click.echo(">>> {}".format(json.dumps(data)))
-3
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
+3 -10
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -10,8 +7,6 @@ import click
click.disable_unicode_literals_warning = True
from past.builtins import basestring
class OctoPrintDevelCommands(click.MultiCommand):
"""
@@ -38,9 +33,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
return log
self.command_caller = CommandlineCaller()
self.command_caller.on_log_call = log_util(
lambda x: click.echo(">> {}".format(x))
)
self.command_caller.on_log_call = log_util(lambda x: click.echo(f">> {x}"))
self.command_caller.on_log_stdout = log_util(click.echo)
self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True))
@@ -58,7 +51,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
def _get_commands(self):
result = {}
for group in self.groups:
for command in self._get_commands_from_prefix_methods("{}_".format(group)):
for command in self._get_commands_from_prefix_methods(f"{group}_"):
result[group + self.sep + command.name] = command
return result
@@ -125,7 +118,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
if key in options:
val = options[key]
else:
if not isinstance(raw, basestring):
if not isinstance(raw, str):
raw = str(raw)
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
+1 -4
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -134,7 +131,7 @@ class OctoPrintPluginCommands(click.MultiCommand):
result[name + self.sep + command.name] = command
except Exception:
self._logger.exception(
"Error while retrieving cli commands for plugin {}".format(name),
f"Error while retrieving cli commands for plugin {name}",
extra={"plugin": name},
)
+4 -7
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -44,10 +41,10 @@ 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("Starting OctoPrint {}".format(__display_version__))
logger.info(f"Starting OctoPrint {__display_version__}")
if safe_mode:
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
if safe_mode == "flag":
@@ -58,7 +55,7 @@ def run_server(
reason = "problem during last startup"
else:
reason = "unknown"
logger.info("Reason for safe mode: {}".format(reason))
logger.info(f"Reason for safe mode: {reason}")
if recorder and len(recorder):
logger.info(get_divider_line("-", "Logged during platform initialization:"))
@@ -101,7 +98,7 @@ def run_server(
log_to_handler(logger, handler, level, message)
_log(get_divider_line("-", "Log roll over detected"))
_log("OctoPrint {}".format(__display_version__))
_log(f"OctoPrint {__display_version__}")
if safe_mode:
_log("SAFE MODE is active. Third party plugins are disabled!")
plugin_manager.log_all_plugins(only_to_handler=handler)
+18 -36
View File
@@ -1,17 +1,13 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import datetime
import io
import logging
import os
import click
import zipstream
from zipstream.ng import ZIP_DEFLATED, ZipStream
from octoprint.cli import init_platform_for_cli, standard_options
@@ -33,7 +29,7 @@ def get_systeminfo(
last_safe_mode = {"date": "unknown", "reason": "unknown"}
try:
if os.path.exists(safe_mode_file):
with io.open(safe_mode_file, "r") as f:
with open(safe_mode_file) as f:
last_safe_mode["reason"] = f.readline().strip()
last_safe_mode["date"] = (
datetime.datetime.utcfromtimestamp(
@@ -69,39 +65,28 @@ def get_systeminfo(
def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None):
from octoprint.util import to_bytes
terminaltxt = None
try:
z = ZipStream(compress_type=ZIP_DEFLATED)
except RuntimeError:
# no zlib support
z = ZipStream(sized=True)
if printer and printer.is_operational():
firmware_info = printer.firmware_info
if firmware_info:
# add firmware to systeminfo so it's included in systeminfo.txt
systeminfo["printer.firmware"] = firmware_info["name"]
# Add printer log, if available
if hasattr(printer, "_log"):
terminaltxt = list(printer._log)
try:
import zlib # noqa: F401
compress_type = zipstream.ZIP_DEFLATED
except ImportError:
# no zlib, no compression
compress_type = zipstream.ZIP_STORED
z = zipstream.ZipFile()
z.add(to_bytes("\n".join(printer._log)), "terminal.txt")
# add systeminfo
systeminfotxt = []
for k in sorted(systeminfo.keys()):
systeminfotxt.append("{}: {}".format(k, systeminfo[k]))
z.writestr(
"systeminfo.txt", to_bytes("\n".join(systeminfotxt)), compress_type=compress_type
)
# add terminal.txt, if available
if terminaltxt:
z.writestr(
"terminal.txt", to_bytes("\n".join(terminaltxt)), compress_type=compress_type
)
z.add(to_bytes("\n".join(systeminfotxt)), arcname="systeminfo.txt")
# add logs
for log in (
@@ -110,7 +95,7 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None
):
logpath = os.path.join(logbase, log)
if os.path.exists(logpath):
z.write(logpath, arcname=log, compress_type=compress_type)
z.add_path(logpath, arcname=log)
# add additional bundle contents from bundled plugins
if plugin_manager:
@@ -130,10 +115,10 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None
if isinstance(content, str):
# log path
if os.path.exists(content) and os.access(content, os.R_OK):
z.write(content, arcname=log, compress_type=compress_type)
z.add_path(content, arcname=log)
elif callable(content):
# content generating callable
z.writestr(log, to_bytes(content()), compress_type=compress_type)
z.add(to_bytes(content()), arcname=log)
except Exception:
logging.getLogger(__name__).exception(
"Error while retrieving additional bundle contents for plugin {}".format(
@@ -190,20 +175,17 @@ def systeminfo_command(ctx, path, **kwargs):
if path:
# create zip at path
zipfilename = os.path.join(path, get_systeminfo_bundle_name())
click.echo("Writing systeminfo bundle to {}...".format(zipfilename))
click.echo(f"Writing systeminfo bundle to {zipfilename}...")
z = get_systeminfo_bundle(
systeminfo, settings.getBaseFolder("logs"), plugin_manager=plugin_manager
)
try:
with open(zipfilename, "wb") as f:
for data in z:
f.write(data)
f.writelines(z)
except Exception as e:
click.echo(str(e), err=True)
click.echo(
"There was an error writing to {}.".format(zipfilename), err=True
)
click.echo(f"There was an error writing to {zipfilename}.", err=True)
ctx.exit(-1)
click.echo("Done!")
+9 -14
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__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"
@@ -133,9 +130,7 @@ def add_user_command(ctx, username, password, groups, permissions, is_admin):
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.as_dict())))
except UserAlreadyExists:
click.echo(
"A user with the name {} does already exist!".format(username), err=True
)
click.echo(f"A user with the name {username} does already exist!", err=True)
@user.command(name="remove")
@@ -150,9 +145,9 @@ def remove_user_command(ctx, username):
if confirm.lower() == "yes":
ctx.obj.user_manager.remove_user(username)
click.echo("User {} removed.".format(username))
click.echo(f"User {username} removed.")
else:
click.echo("User {} not removed.".format(username))
click.echo(f"User {username} not removed.")
@user.command(name="password")
@@ -163,9 +158,9 @@ def change_password_command(ctx, username, password):
"""Change an existing user's password."""
try:
ctx.obj.user_manager.change_user_password(username, password)
click.echo("Password changed for user {}.".format(username))
click.echo(f"Password changed for user {username}.")
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
click.echo(f"User {username} does not exist!", err=True)
@user.command(name="activate")
@@ -175,14 +170,14 @@ def activate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, True)
click.echo("User {} activated.".format(username))
click.echo(f"User {username} activated.")
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
click.echo(f"User {username} does not exist!", err=True)
@user.command(name="deactivate")
@@ -192,14 +187,14 @@ def deactivate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, False)
click.echo("User {} activated.".format(username))
click.echo(f"User {username} activated.")
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
click.echo(f"User {username} does not exist!", err=True)
def _print_list(users):
+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()
+6 -10
View File
@@ -1,13 +1,9 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
Generic linux daemon base class
Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35
"""
import io
import os
import signal
import sys
@@ -66,9 +62,9 @@ class Daemon:
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = io.open(os.devnull, "rt", encoding="utf-8")
so = io.open(os.devnull, "at+", encoding="utf-8")
se = io.open(os.devnull, "at+", encoding="utf-8")
si = open(os.devnull, encoding="utf-8")
so = open(os.devnull, "at+", encoding="utf-8")
se = open(os.devnull, "at+", encoding="utf-8")
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
@@ -156,15 +152,15 @@ class Daemon:
def get_pid(self):
"""Get the pid from the pidfile."""
try:
with io.open(self.pidfile, "rt", encoding="utf-8") as pf:
with open(self.pidfile, encoding="utf-8") as pf:
pid = int(pf.read().strip())
except (IOError, ValueError):
except (OSError, ValueError):
pid = None
return pid
def set_pid(self, pid):
"""Write the pid to the pidfile."""
with io.open(self.pidfile, "wt+", encoding="utf-8") as f:
with open(self.pidfile, "wt+", encoding="utf-8") as f:
f.write(str(pid) + "\n")
def remove_pidfile(self):
+2 -5
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -18,7 +15,7 @@ from octoprint.util.platform import get_os
from octoprint.util.version import get_python_version_string
class EnvironmentDetector(object):
class EnvironmentDetector:
def __init__(self, plugin_manager):
self._plugin_manager = plugin_manager
@@ -170,7 +167,7 @@ class EnvironmentDetector(object):
dumped_environment = yaml.dump(environment, pretty=True).strip()
environment_lines = "\n".join(
map(lambda l: "| {}".format(l), dumped_environment.split("\n"))
map(lambda l: f"| {l}", dumped_environment.split("\n"))
)
return "Detected environment is Python {} under {} ({}). Details:\n{}".format(
environment["python"]["version"],
+13 -25
View File
@@ -1,21 +1,13 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import collections
import datetime
import logging
import subprocess
try:
import queue
except ImportError:
import Queue as queue
import collections
import queue
import re
import subprocess
import threading
import octoprint.plugin
@@ -33,7 +25,7 @@ def all_events():
]
class Events(object):
class Events:
# server
STARTUP = "Startup"
SHUTDOWN = "Shutdown"
@@ -161,7 +153,7 @@ def eventManager():
return _instance
class EventManager(object):
class EventManager:
"""
Handles receiving events and dispatching them to subscribers
"""
@@ -169,7 +161,7 @@ class EventManager(object):
def __init__(self):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
self._logger_fire = logging.getLogger(f"{__name__}.fire")
self._startup_signaled = False
self._shutdown_signaled = False
@@ -193,12 +185,10 @@ class EventManager(object):
self._shutdown_signaled = True
eventListeners = self._registeredListeners[event]
self._logger_fire.debug(
"Firing event: {} (Payload: {!r})".format(event, payload)
)
self._logger_fire.debug(f"Firing event: {event} (Payload: {payload!r})")
for listener in eventListeners:
self._logger.debug("Sending action to {!r}".format(listener))
self._logger.debug(f"Sending action to {listener!r}")
try:
listener(event, payload)
except Exception:
@@ -265,9 +255,7 @@ class EventManager(object):
return
self._registeredListeners[event].append(callback)
self._logger.debug(
"Subscribed listener {!r} for event {}".format(callback, event)
)
self._logger.debug(f"Subscribed listener {callback!r} for event {event}")
def unsubscribe(self, event, callback):
"""
@@ -285,7 +273,7 @@ class EventManager(object):
return self._worker.is_alive()
class GenericEventListener(object):
class GenericEventListener:
"""
The GenericEventListener can be subclassed to easily create custom event listeners.
"""
@@ -326,7 +314,7 @@ class DebugEventListener(GenericEventListener):
def eventCallback(self, event, payload):
GenericEventListener.eventCallback(self, event, payload)
self._logger.debug("Received event: {} (Payload: {!r})".format(event, payload))
self._logger.debug(f"Received event: {event} (Payload: {payload!r})")
class CommandTrigger(GenericEventListener):
@@ -373,7 +361,7 @@ class CommandTrigger(GenericEventListener):
continue
if "enabled" in subscription and not subscription["enabled"]:
self._logger.info("Disabled command trigger: {!r}".format(subscription))
self._logger.info(f"Disabled command trigger: {subscription!r}")
continue
events = subscription["event"]
@@ -432,7 +420,7 @@ class CommandTrigger(GenericEventListener):
def _executeSystemCommand(self, command, debug=False):
def commandExecutioner(cmd):
if debug:
self._logger.info("Executing system command: {}".format(cmd))
self._logger.info(f"Executing system command: {cmd}")
else:
self._logger.info("Executing a system command")
# we run this with shell=True since we have to trust whatever
+35 -34
View File
@@ -1,16 +1,13 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import io
import logging
import os
import time
from collections import namedtuple
from past.builtins import basestring
import octoprint.plugin
import octoprint.util
from octoprint.events import Events, eventManager
@@ -19,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")
@@ -223,7 +220,7 @@ class NoSuchStorage(Exception):
pass
class FileManager(object):
class FileManager:
def __init__(
self,
analysis_queue,
@@ -449,8 +446,6 @@ class FileManager(object):
source_meta = self.get_metadata(source_location, source_path)
hash = source_meta.get("hash", "n/a")
import io
links = [("model", {"name": source_path})]
_, stl_name = self.split_path(source_location, source_path)
file_obj = StreamWrapper(
@@ -477,7 +472,7 @@ class FileManager(object):
analysis=_analysis,
)
end_time = octoprint.util.monotonic_time()
end_time = time.monotonic()
eventManager().fire(
Events.SLICING_DONE,
{
@@ -508,7 +503,7 @@ class FileManager(object):
slicer = self._slicing_manager.get_slicer(slicer_name)
start_time = octoprint.util.monotonic_time()
start_time = time.monotonic()
eventManager().fire(
Events.SLICING_STARTED,
{
@@ -680,7 +675,7 @@ class FileManager(object):
):
if not destinations:
destinations = list(self._storage_managers.keys())
if isinstance(destinations, basestring):
if isinstance(destinations, str):
destinations = [destinations]
result = {}
@@ -896,6 +891,9 @@ class FileManager(object):
)
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)
@@ -912,25 +910,28 @@ class FileManager(object):
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}
)
@@ -954,7 +955,7 @@ class FileManager(object):
yaml.save_to_file(data, file=f, pretty=True)
except Exception:
self._logger.exception(
"Could not write recovery data to file {}".format(self._recovery_file)
f"Could not write recovery data to file {self._recovery_file}"
)
def delete_recovery_data(self):
@@ -965,7 +966,7 @@ class FileManager(object):
os.remove(self._recovery_file)
except Exception:
self._logger.exception(
"Error deleting recovery data file {}".format(self._recovery_file)
f"Error deleting recovery data file {self._recovery_file}"
)
def get_recovery_data(self):
@@ -982,7 +983,7 @@ class FileManager(object):
return data
except Exception:
self._logger.exception(
"Could not read recovery data from file {}".format(self._recovery_file)
f"Could not read recovery data from file {self._recovery_file}"
)
self.delete_recovery_data()
+21 -33
View File
@@ -1,20 +1,12 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import collections
import copy
import logging
try:
import queue
except ImportError:
import Queue as queue
import collections
import os
import queue
import threading
import time
@@ -22,7 +14,7 @@ from octoprint.events import Events, eventManager
from octoprint.settings import settings
from octoprint.util import dict_merge
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util import monotonic_time, yaml
from octoprint.util import yaml
from octoprint.util.platform import CLOSE_FDS
EMPTY_RESULT = {
@@ -62,7 +54,7 @@ class QueueEntry(
"""
def __str__(self):
return "{location}:{path}".format(location=self.location, path=self.path)
return f"{self.location}:{self.path}"
class AnalysisAborted(Exception):
@@ -71,7 +63,7 @@ class AnalysisAborted(Exception):
self.reenqueue = reenqueue
class AnalysisQueue(object):
class AnalysisQueue:
"""
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
by their machine code type.
@@ -137,7 +129,7 @@ class AnalysisQueue(object):
callback(entry, result)
except Exception:
self._logger.exception(
"Error while pushing analysis data to callback {}".format(callback),
f"Error while pushing analysis data to callback {callback}",
extra={"callback": fqcn(callback)},
)
eventManager().fire(
@@ -151,7 +143,7 @@ class AnalysisQueue(object):
)
class AbstractAnalysisQueue(object):
class AbstractAnalysisQueue:
"""
The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the
:class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis
@@ -208,9 +200,7 @@ class AbstractAnalysisQueue(object):
"""
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
self._logger.debug(
"Ignoring entry {entry} for analysis queue".format(entry=entry)
)
self._logger.debug(f"Ignoring entry {entry} for analysis queue")
return
elif high_priority:
self._logger.debug(
@@ -277,7 +267,7 @@ class AbstractAnalysisQueue(object):
while True:
(priority, entry, high_priority) = self._queue.get()
self._logger.debug(
"Processing entry {} from queue (priority {})".format(entry, priority)
f"Processing entry {entry} from queue (priority {priority})"
)
self._active.wait()
@@ -296,7 +286,7 @@ class AbstractAnalysisQueue(object):
high_priority,
)
)
self._logger.debug("Running analysis of entry {} aborted".format(entry))
self._logger.debug(f"Running analysis of entry {entry} aborted")
self._queue.task_done()
self._done.set()
else:
@@ -312,8 +302,8 @@ class AbstractAnalysisQueue(object):
self._current_progress = 0
try:
start_time = monotonic_time()
self._logger.info("Starting analysis of {}".format(entry))
start_time = time.monotonic()
self._logger.info(f"Starting analysis of {entry}")
eventManager().fire(
Events.METADATA_ANALYSIS_STARTED,
{
@@ -329,14 +319,12 @@ class AbstractAnalysisQueue(object):
result = self._do_analysis()
self._logger.info(
"Analysis of entry {} finished, needed {:.2f}s".format(
entry, monotonic_time() - start_time
entry, time.monotonic() - start_time
)
)
self._finished_callback(self._current, result)
except RuntimeError as exc:
self._logger.error(
"Analysis for {} ran into error: {}".format(self._current, exc)
)
self._logger.error(f"Analysis for {self._current} ran into error: {exc}")
finally:
self._current = None
self._current_progress = None
@@ -443,12 +431,12 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
"octoprint",
"analysis",
"gcode",
"--speed-x={}".format(speedx),
"--speed-y={}".format(speedy),
"--max-t={}".format(max_extruders),
"--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines),
"--bed-z={}".format(bed_z),
f"--speed-x={speedx}",
f"--speed-y={speedy}",
f"--max-t={max_extruders}",
f"--throttle={throttle}",
f"--throttle-lines={throttle_lines}",
f"--bed-z={bed_z}",
]
for offset in offsets[1:]:
command += ["--offset", str(offset[0]), str(offset[1])]
@@ -494,7 +482,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
p.close()
output = p.stdout.text
self._logger.debug("Got output: {!r}".format(output))
self._logger.debug(f"Got output: {output!r}")
result = {}
if "ERROR:" in output:
+1 -4
View File
@@ -1,10 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
class FileDestinations(object):
class FileDestinations:
SDCARD = "sdcard"
LOCAL = "local"
@@ -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
@@ -1,27 +1,16 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
import io
import logging
import os
import shutil
from contextlib import contextmanager
from os import scandir, walk
import pylru
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
from contextlib import contextmanager
from past.builtins import basestring
import octoprint.filemanager
from octoprint.util import (
atomic_write,
@@ -33,439 +22,10 @@ from octoprint.util import (
)
from octoprint.util.files import sanitize_filename
from . import Storage, StorageError
class StorageInterface(object):
"""
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.
@@ -475,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``.
@@ -512,9 +72,7 @@ class LocalFileStorage(StorageInterface):
self._initialize_metadata()
def _initialize_metadata(self):
self._logger.info(
"Initializing the file metadata for {}...".format(self.basefolder)
)
self._logger.info(f"Initializing the file metadata for {self.basefolder}...")
old_metadata_path = os.path.join(self.basefolder, "metadata.yaml")
backup_path = os.path.join(self.basefolder, "metadata.yaml.backup")
@@ -543,7 +101,7 @@ class LocalFileStorage(StorageInterface):
self._list_folder(self.basefolder)
self._logger.info(
"... file metadata for {} initialized successfully.".format(self.basefolder)
f"... file metadata for {self.basefolder} initialized successfully."
)
@property
@@ -554,8 +112,7 @@ class LocalFileStorage(StorageInterface):
if path:
path = self.sanitize_path(path)
for entry in self._analysis_backlog_generator(path):
yield entry
yield from self._analysis_backlog_generator(path)
def _analysis_backlog_generator(self, path=None):
if path is None:
@@ -737,7 +294,7 @@ class LocalFileStorage(StorageInterface):
if not os.path.exists(source_fullpath):
raise StorageError(
"{} in {} does not exist".format(source_name, source_path),
f"{source_name} in {source_path} does not exist",
code=StorageError.INVALID_SOURCE,
)
@@ -753,7 +310,7 @@ class LocalFileStorage(StorageInterface):
and source_fullpath != destination_fullpath
):
raise StorageError(
"{} does already exist in {}".format(destination_name, destination_path),
f"{destination_name} does already exist in {destination_path}",
code=StorageError.INVALID_DESTINATION,
)
@@ -1037,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)
@@ -1151,7 +724,7 @@ class LocalFileStorage(StorageInterface):
def canonicalize(self, path):
name = None
if isinstance(path, basestring):
if isinstance(path, str):
path = to_unicode(path)
if path.startswith(self.basefolder):
path = path[len(self.basefolder) :]
@@ -1217,16 +790,14 @@ class LocalFileStorage(StorageInterface):
while os.path.exists(sanitized_path):
counter += 1
sanitized = self.sanitize_name(
"{}_({}){}".format(sanitized_name, counter, sanitized_ext)
f"{sanitized_name}_({counter}){sanitized_ext}"
)
sanitized_path = os.path.join(path, sanitized)
try:
shutil.move(entry_path, sanitized_path)
self._logger.info(
'Sanitized "{}" to "{}"'.format(entry_path, sanitized_path)
)
self._logger.info(f'Sanitized "{entry_path}" to "{sanitized_path}"')
return sanitized, sanitized_path
except Exception:
self._logger.exception(
@@ -1241,7 +812,7 @@ class LocalFileStorage(StorageInterface):
def path_in_storage(self, path):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
if isinstance(path, basestring):
if isinstance(path, str):
path = to_unicode(path)
if path.startswith(self.basefolder):
path = path[len(self.basefolder) :]
@@ -1671,7 +1242,7 @@ class LocalFileStorage(StorageInterface):
except Exception:
# So something went wrong somewhere while processing this file entry - log that and continue
self._logger.exception(
"Error while processing entry {}".format(entry_path)
f"Error while processing entry {entry_path}"
)
continue
@@ -1741,7 +1312,7 @@ class LocalFileStorage(StorageInterface):
blocksize = 65536
hash = hashlib.sha1()
with io.open(path, "rb") as f:
with open(path, "rb") as f:
buffer = f.read(blocksize)
while len(buffer) > 0:
hash.update(buffer)
@@ -1822,7 +1393,7 @@ class LocalFileStorage(StorageInterface):
metadata = None
with self._get_persisted_metadata_lock(path):
if os.path.exists(metadata_path):
with io.open(metadata_path, "rt", encoding="utf-8") as f:
with open(metadata_path, encoding="utf-8") as f:
try:
metadata = json.load(f)
except Exception:
@@ -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)
+3 -7
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -12,7 +9,7 @@ from octoprint import UMASK
from octoprint.util import atomic_write
class AbstractFileWrapper(object):
class AbstractFileWrapper:
"""
Wrapper for file representations to save to storages.
@@ -75,7 +72,7 @@ class DiskFileWrapper(AbstractFileWrapper):
os.chmod(path, permissions)
def stream(self):
return io.open(self.path, "rb")
return open(self.path, "rb")
class StreamWrapper(AbstractFileWrapper):
@@ -242,8 +239,7 @@ class LineProcessorStream(io.RawIOBase):
wrapper `input_stream`.
Arguments:
line (bytes): The line as read from `self.input_stream` in byte representation (str under Python 2 and
bytes under Python 3)
line (bytes): The line as read from `self.input_stream` in byte representation
Returns:
bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be
+3 -9
View File
@@ -1,10 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from typing import Union
from past.builtins import basestring, unicode
from octoprint.logging import filters # noqa: F401
from octoprint.logging import handlers # noqa: F401
@@ -132,7 +127,7 @@ def get_divider_line(c, message=None, length=78, indent=3):
formatted divider line
"""
assert isinstance(c, basestring), "c is not text"
assert isinstance(c, str), "c is not text"
assert len(c) == 1, "c is not a single character"
assert isinstance(length, int), "length is not an int"
assert isinstance(indent, int), "indent is not an int"
@@ -140,7 +135,7 @@ def get_divider_line(c, message=None, length=78, indent=3):
if message is None:
return c * length
assert isinstance(message, basestring), "message is not text"
assert isinstance(message, str), "message is not text"
space = length - 2 * (indent + 1)
if space >= len(message):
@@ -149,8 +144,7 @@ def get_divider_line(c, message=None, length=78, indent=3):
return c * indent + " " + message
def prefix_multilines(text, prefix=": "):
# type: (Union[unicode, bytes], unicode) -> unicode
def prefix_multilines(text: Union[str, bytes], prefix: str = ": ") -> str:
from octoprint.util import to_unicode
lines = text.splitlines()
+2 -9
View File
@@ -1,12 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
try:
from urllib import parse as urlparse
except ImportError:
import urlparse
from urllib import parse as urlparse
class TornadoAccessFilter(logging.Filter):
@@ -23,7 +16,7 @@ class TornadoAccessFilter(logging.Filter):
record.levelname = logging.getLevelName(record.levelno)
except Exception:
logging.getLogger(__name__).exception(
"Error while filtering log record {!r}".format(record)
f"Error while filtering log record {record!r}"
)
return logging.Filter.filter(self, record)
+13 -19
View File
@@ -1,7 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
# noinspection PyCompatibility
import concurrent.futures
import logging.handlers
import os
@@ -12,7 +8,7 @@ import time
class AsyncLogHandlerMixin(logging.Handler):
def __init__(self, *args, **kwargs):
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
def emit(self, record):
if getattr(self._executor, "_shutdown", False):
@@ -25,18 +21,18 @@ class AsyncLogHandlerMixin(logging.Handler):
def _emit(self, record):
# noinspection PyUnresolvedReferences
super(AsyncLogHandlerMixin, self).emit(record)
super().emit(record)
def close(self):
self._executor.shutdown(wait=True)
super(AsyncLogHandlerMixin, self).close()
super().close()
class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
# clean up old files on handler start
if self.backupCount > 0:
@@ -49,14 +45,14 @@ class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(OctoPrintLogHandler, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
@classmethod
def registerRolloverCallback(cls, callback, *args, **kwargs):
cls.rollover_callbacks.append((callback, args, kwargs))
def doRollover(self):
super(OctoPrintLogHandler, self).doRollover()
super().doRollover()
for rcb in self.rollover_callbacks:
callback, args, kwargs = rcb
@@ -71,21 +67,21 @@ 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")
super(TriggeredRolloverLogHandler, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.cleanupFiles()
def shouldRollover(self, record):
return self.do_rollover
return self.do_rollover.pop(record.name, False)
def getFilesToDelete(self):
"""
@@ -114,8 +110,6 @@ class TriggeredRolloverLogHandler(
os.remove(path)
def doRollover(self):
self.do_rollover = False
if self.stream:
self.stream.close()
self.stream = None
@@ -133,7 +127,7 @@ class TriggeredRolloverLogHandler(
self.stream = self._open()
class SerialLogHandler(TriggeredRolloverLogHandler):
class CommunicationLogHandler(TriggeredRolloverLogHandler):
pass
@@ -143,7 +137,7 @@ class PluginTimingsLogHandler(TriggeredRolloverLogHandler):
class RecordingLogHandler(logging.Handler):
def __init__(self, target=None, *args, **kwargs):
super(RecordingLogHandler, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self._buffer = []
self._target = target
+20 -148
View File
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the
registered plugin types.
@@ -12,7 +11,6 @@ registered plugin types.
.. autoclass:: PluginSettings
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
@@ -24,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, to_native_str
# singleton
_instance = None
@@ -167,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.
@@ -175,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
@@ -189,12 +190,13 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
get_preprocessors, set_preprocessors = instance.get_settings_preprocessors()
except Exception:
logging.getLogger(__name__).exception(
"Error while retrieving preprocessors for plugin {}".format(plugin_key)
f"Error while retrieving preprocessors for plugin {plugin_key}"
)
return None
return plugin_settings(
plugin_key,
defaults=defaults,
get_preprocessors=get_preprocessors,
set_preprocessors=set_preprocessors,
settings=settings,
@@ -266,7 +268,7 @@ def call_plugin(
continue
if hasattr(plugin, method):
logger.debug("Calling {} on {}".format(method, plugin._identifier))
logger.debug(f"Calling {method} on {plugin._identifier}")
try:
result = getattr(plugin, method)(*args, **kwargs)
if callback:
@@ -280,7 +282,7 @@ def call_plugin(
error_callback(plugin._identifier, plugin, exc)
class PluginSettings(object):
class PluginSettings(SubSettings):
"""
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
@@ -393,86 +395,19 @@ class PluginSettings(object):
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)
@@ -563,66 +498,3 @@ class PluginSettings(object):
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(
"{old} has been renamed to {new}".format(old=item, new=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__ = to_native_str(item)
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
return _func
return getattr(self.settings, item)
+23 -39
View File
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
In this module resides the core data structures and logic of the plugin system.
@@ -18,7 +17,6 @@ In this module resides the core data structures and logic of the plugin system.
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__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"
@@ -26,32 +24,18 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import fnmatch
import inspect
import io
import logging
import os
import sys
from collections import OrderedDict, defaultdict, namedtuple
from os import scandir
import pkg_resources
import pkginfo
from past.builtins import unicode
import octoprint.vendor.imp as imp
from octoprint.util import sv, time_this, to_unicode
from octoprint.util.version import get_python_version_string, is_python_compatible
try:
from os import scandir
except ImportError:
from scandir import scandir
if sys.version_info[0] == 2:
# noinspection PyDeprecation
import imp
else:
# deprecated in Python 3.4+ and hence vendored for now
import octoprint.vendor.imp as imp
# noinspection PyDeprecation
def _find_module(name, path=None):
@@ -85,12 +69,12 @@ def parse_plugin_metadata(path):
# we only support parsing plain text source files
return result
logger.debug("Parsing plugin metadata from AST of {}".format(path))
logger.debug(f"Parsing plugin metadata from AST of {path}".format(path))
try:
import ast
with io.open(path, "rb") as f:
with open(path, "rb") as f:
root = ast.parse(f.read(), filename=path)
assignments = list(
@@ -166,12 +150,12 @@ def parse_plugin_metadata(path):
except SyntaxError:
raise
except Exception:
logger.exception("Error while parsing AST from {}".format(path))
logger.exception(f"Error while parsing AST from {path}")
return result
class ControlProperties(object):
class ControlProperties:
attr_name = "__plugin_name__"
""" Module attribute from which to retrieve the plugin's human readable name. """
@@ -313,7 +297,7 @@ class ModuleOrigin(_ModuleOrigin):
"""
class PluginInfo(object):
class PluginInfo:
"""
The :class:`PluginInfo` class wraps all available information about a registered plugin.
@@ -432,7 +416,7 @@ class PluginInfo(object):
def __str__(self):
if self.version:
return "{name} ({version})".format(name=self.name, version=self.version)
return f"{self.name} ({self.version})"
else:
return to_unicode(self.name)
@@ -485,7 +469,7 @@ class PluginInfo(object):
else:
ret = ""
ret += unicode(self)
ret += str(self)
if show_bundled:
ret += (
@@ -798,13 +782,13 @@ class PluginInfo(object):
return parse_plugin_metadata(self.location)
except SyntaxError:
self._logger.exception(
"Invalid syntax in plugin file of plugin {}".format(self.key)
f"Invalid syntax in plugin file of plugin {self.key}".format(self.key)
)
self.invalid_syntax = True
return {}
class PluginManager(object):
class PluginManager:
"""
The :class:`PluginManager` is the central component for finding, loading and accessing plugins provided to the
system.
@@ -1044,7 +1028,7 @@ class PluginManager(object):
module_name = None
if package:
module_name = "{}.{}".format(package, key)
module_name = f"{package}.{key}"
plugin = self._import_plugin_from_module(
key, module_name=module_name, folder=folder, bundled=bundled
@@ -1068,7 +1052,7 @@ class PluginManager(object):
)
)
except Exception:
self.logger.exception("Error processing folder {}".format(folder))
self.logger.exception(f"Error processing folder {folder}")
return added, found
@@ -1206,7 +1190,7 @@ class PluginManager(object):
else:
return None
except Exception:
self.logger.exception("Could not locate plugin {key}".format(key=key))
self.logger.exception(f"Could not locate plugin {key}")
return None
# Create a simple dummy entry first ...
@@ -1224,14 +1208,14 @@ class PluginManager(object):
plugin.bundled = bundled
if self._is_plugin_disabled(key):
self.logger.info("Plugin {} is disabled.".format(plugin))
self.logger.info(f"Plugin {plugin} is disabled.")
plugin.forced_disabled = True
if self._is_plugin_blacklisted(key) or (
plugin.version is not None
and self._is_plugin_version_blacklisted(key, plugin.version)
):
self.logger.warning("Plugin {} is blacklisted.".format(plugin))
self.logger.warning(f"Plugin {plugin} is blacklisted.")
plugin.blacklisted = True
python_version = get_python_version_string()
@@ -1307,7 +1291,7 @@ class PluginManager(object):
plugin.bundled = bundled
except Exception:
self.logger.exception("Error loading plugin {key}".format(key=key))
self.logger.exception(f"Error loading plugin {key}")
return None
if plugin.check():
@@ -1429,7 +1413,7 @@ class PluginManager(object):
):
if plugin.blacklisted:
self.logger.warning(
"Plugin {} is blacklisted. Not enabling it.".format(plugin)
f"Plugin {plugin} is blacklisted. Not enabling it."
)
continue
self.enable_plugin(
@@ -2046,7 +2030,7 @@ class PluginManager(object):
show_enabled=show_enabled,
enabled_strs=enabled_str,
),
sorted(self.plugins.values(), key=lambda x: unicode(x).lower()),
sorted(self.plugins.values(), key=lambda x: str(x).lower()),
)
)
legend = "Prefix legend: {1} = disabled, {2} = blacklisted, {3} = incompatible".format(
@@ -2315,11 +2299,11 @@ def is_sub_path_of(path, parent):
def is_editable_install(install_dir, package, module, location):
package_link = os.path.join(install_dir, "{}.egg-link".format(package))
package_link = os.path.join(install_dir, f"{package}.egg-link")
if os.path.isfile(package_link):
expected_target = os.path.normcase(os.path.realpath(location))
try:
with io.open(package_link, "rt", encoding="utf-8") as f:
with open(package_link, encoding="utf-8") as f:
contents = f.readlines()
for line in contents:
target = os.path.normcase(
@@ -2347,7 +2331,7 @@ class EntryPointMetadata(pkginfo.Distribution):
for metadata_file in metadata_files:
try:
return self.entry_point.dist.get_metadata(metadata_file)
except (IOError, OSError): # noqa: B014
except OSError: # noqa: B014
# file not found, metadata file might be missing, ignore
# IOError: file not found in Py2
# OSError (specifically FileNotFoundError): file not found in Py3
@@ -2360,7 +2344,7 @@ class EntryPointMetadata(pkginfo.Distribution):
)
class Plugin(object):
class Plugin:
"""
The parent class of all plugin implementations.
+4 -15
View File
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent
class, :class:`OctoPrintPlugin`.
@@ -15,7 +14,6 @@ Please note that the plugin implementation types are documented in the section
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
@@ -402,7 +400,7 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
@property
def template_folder_key(self):
return "plugin_{}".format(self._identifier)
return f"plugin_{self._identifier}"
def get_template_configs(self):
"""
@@ -1425,9 +1423,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
import flask
kwargs = self.get_blueprint_kwargs()
blueprint = flask.Blueprint(
"plugin." + self._identifier, self._identifier, **kwargs
)
blueprint = flask.Blueprint(self._identifier, self._identifier, **kwargs)
# we now iterate over all members of ourselves and look if we find an attribute
# that has data originating from one of our decorators - we ignore anything
@@ -2055,10 +2051,7 @@ class SlicerPlugin(OctoPrintPlugin):
.. versionadded:: 1.3.7
"""
try:
from os import scandir
except ImportError:
from scandir import scandir
from os import scandir
import octoprint.util
@@ -2080,11 +2073,7 @@ class SlicerPlugin(OctoPrintPlugin):
.. versionadded:: 1.3.0
"""
import os
try:
from os import scandir
except ImportError:
from scandir import scandir
from os import scandir
lms = [os.stat(profile_path).st_mtime]
lms += [
-2
View File
@@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -126,7 +123,7 @@ class ActionCommandNotificationPlugin(
self._notifications.append((time.time(), message))
self._plugin_manager.send_plugin_message(self._identifier, {"message": message})
self._logger.info("Got a notification: {}".format(message))
self._logger.info(f"Got a notification: {message}")
def _clear_notifications(self):
self._notifications = []
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__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"
@@ -13,7 +10,7 @@ from octoprint.access.permissions import Permissions
from octoprint.events import Events
class Prompt(object):
class Prompt:
def __init__(self, text):
self.text = text
self.choices = []
@@ -93,7 +90,7 @@ class ActionCommandPromptPlugin(
and self._enable == "always"
and self._enable_signal_support
):
self._printer.commands(["{command} P1".format(command=self._command)])
self._printer.commands([f"{self._command} P1"])
elif event == Events.DISCONNECTED:
self._close_prompt()
@@ -133,9 +130,7 @@ class ActionCommandPromptPlugin(
choice = data["choice"]
if not isinstance(choice, int) or not self._prompt.validate_choice(choice):
return flask.abort(
400, "{!r} is not a valid value for choice".format(choice)
)
return flask.abort(400, f"{choice!r} is not a valid value for choice")
self._answer_prompt(choice)
@@ -211,7 +206,7 @@ class ActionCommandPromptPlugin(
subcode=None,
tags=None,
*args,
**kwargs
**kwargs,
):
if gcode != self._command:
return
@@ -229,7 +224,7 @@ class ActionCommandPromptPlugin(
# noinspection PyProtectedMember
return comm_instance._emergency_force_send(
cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode
cmd, f"Force-sending {self._command} to the printer", gcode=gcode
)
# ~ capability reporting
@@ -240,7 +235,7 @@ class ActionCommandPromptPlugin(
if capability == self.CAP_PROMPT_SUPPORT and enabled:
self._cap_prompt_support = True
if self._enable == "detected" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
self._printer.commands([f"{self._command} P1"])
# ~ prompt handling
@@ -280,7 +275,7 @@ class ActionCommandPromptPlugin(
self._printer.commands([self._command.format(choice=choice)], force=True)
else:
self._printer.commands(
["{command} S{choice}".format(command=self._command, choice=choice)],
[f"{self._command} S{choice}"],
force=True,
)
+10 -21
View File
@@ -1,13 +1,9 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__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"
import calendar
import io
import os
import re
import sys
@@ -28,7 +24,7 @@ from octoprint.server.util.flask import (
no_firstrun_access,
with_revalidation_checking,
)
from octoprint.util import count, monotonic_time, utmify
from octoprint.util import count, utmify
from octoprint.util.text import sanitize
PY2 = sys.version_info[0] < 3
@@ -437,9 +433,7 @@ class AnnouncementPlugin(
now = time.time()
if os.stat(channel_path).st_mtime + ttl > now:
d = feedparser.parse(channel_path)
self._logger.debug(
"Loaded channel {} from cache at {}".format(key, channel_path)
)
self._logger.debug(f"Loaded channel {key} from cache at {channel_path}")
return d
return None
@@ -451,12 +445,12 @@ class AnnouncementPlugin(
url = config["url"]
try:
start = monotonic_time()
start = time.monotonic()
r = requests.get(url, timeout=30)
r.raise_for_status()
self._logger.info(
"Loaded channel {} from {} in {:.2}s".format(
key, config["url"], monotonic_time() - start
key, config["url"], time.monotonic() - start
)
)
except Exception:
@@ -467,7 +461,7 @@ class AnnouncementPlugin(
response = r.text
channel_path = self._get_channel_cache_path(key)
with io.open(channel_path, mode="wt", encoding="utf-8") as f:
with open(channel_path, mode="wt", encoding="utf-8") as f:
f.write(response)
return feedparser.parse(response)
@@ -521,7 +515,7 @@ class AnnouncementPlugin(
"""Retrieve cache path for channel key."""
safe_key = sanitize(key)
return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key))
return os.path.join(self.get_plugin_data_folder(), f"{safe_key}.cache")
_image_tag_re = re.compile(r"<img.*?/?>")
@@ -580,7 +574,7 @@ def _lazy_images(text, placeholder=None):
quote = match.group("quote")
quoted_src = quote + src + quote
img_tag = img_tag.replace(
match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src)
match.group(0), f'src="{placeholder}" data-src={quoted_src}'
)
return img_tag
@@ -594,12 +588,7 @@ def _strip_tags(text):
>>> _strip_tags("&#62; &#x3E; Foo") # doctest: +ALLOW_UNICODE
'&#62; &#x3E; Foo'
"""
try:
# noinspection PyCompatibility
from html.parser import HTMLParser
except ImportError:
# noinspection PyCompatibility
from HTMLParser import HTMLParser
from html.parser import HTMLParser
class TagStripper(HTMLParser):
def __init__(self, **kw):
@@ -610,10 +599,10 @@ def _strip_tags(text):
self._fed.append(data)
def handle_entityref(self, ref):
self._fed.append("&{};".format(ref))
self._fed.append(f"&{ref};")
def handle_charref(self, ref):
self._fed.append("&#{};".format(ref))
self._fed.append(f"&#{ref};")
def get_data(self):
return "".join(self._fed)
+10 -18
View File
@@ -1,8 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
import threading
import time
from collections import defaultdict
import flask
@@ -19,13 +17,7 @@ from octoprint.server.util.flask import (
restricted_access,
)
from octoprint.settings import valid_boolean_trues
from octoprint.util import (
ResettableTimer,
atomic_write,
generate_api_key,
monotonic_time,
yaml,
)
from octoprint.util import ResettableTimer, atomic_write, generate_api_key, yaml
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
@@ -35,13 +27,13 @@ class AppAlreadyExists(Exception):
pass
class PendingDecision(object):
class PendingDecision:
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
self.user_token = user_token
self.created = monotonic_time()
self.created = time.monotonic()
if callable(timeout_callback):
self.poll_timeout = ResettableTimer(
@@ -62,7 +54,7 @@ class PendingDecision(object):
)
class ReadyDecision(object):
class ReadyDecision:
def __init__(self, app_id, app_token, user_id):
self.app_id = app_id
self.app_token = app_token
@@ -78,7 +70,7 @@ class ReadyDecision(object):
)
class ActiveKey(object):
class ActiveKey:
def __init__(self, app_id, api_key, user_id):
self.app_id = app_id
self.api_key = api_key
@@ -186,7 +178,7 @@ class AppKeysPlugin(
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
auth_dialog = flask.url_for(
"plugin.appkeys.handle_auth_dialog", app_token=app_token, _external=True
) + ("?user={}".format(user_id) if user_id else "")
) + (f"?user={user_id}" if user_id else "")
self._plugin_manager.send_plugin_message(
self._identifier,
@@ -407,7 +399,7 @@ class AppKeysPlugin(
def _remove_stale_pending(self):
with self._pending_lock:
cutoff = monotonic_time() - CUTOFF_TIME
cutoff = time.monotonic() - CUTOFF_TIME
len_before = len(self._pending_decisions)
self._pending_decisions = list(
filter(lambda x: x.created >= cutoff, self._pending_decisions)
@@ -510,7 +502,7 @@ class AppKeysPlugin(
persisted = yaml.load_from_file(path=self._key_path)
except Exception:
self._logger.exception(
"Could not load application keys from {}".format(self._key_path)
f"Could not load application keys from {self._key_path}"
)
return
@@ -535,7 +527,7 @@ class AppKeysPlugin(
yaml.save_to_file(to_persist, file=f)
except Exception:
self._logger.exception(
"Could not write application keys to {}".format(self._key_path)
f"Could not write application keys to {self._key_path}"
)
+18 -29
View File
@@ -1,9 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__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 os import scandir
import octoprint.plugin
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
@@ -21,18 +20,12 @@ from octoprint.util.version import (
is_octoprint_compatible,
)
try:
from os import scandir
except ImportError:
from scandir import scandir
try:
import zlib # check if zlib is available
except ImportError:
zlib = None
import io
import json
import logging
import os
@@ -512,7 +505,7 @@ class BackupPlugin(
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
click.echo("Creating backup at {}, please wait...".format(filename))
click.echo(f"Creating backup at {filename}, please wait...")
self._create_backup(
filename,
exclude=exclude,
@@ -556,7 +549,7 @@ class BackupPlugin(
path = os.path.join(datafolder, path)
if not os.path.exists(path):
click.echo("Backup {} does not exist".format(path), err=True)
click.echo(f"Backup {path} does not exist", err=True)
sys.exit(-1)
archive = tempfile.NamedTemporaryFile(delete=False)
@@ -574,7 +567,7 @@ class BackupPlugin(
pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"])
def log(line):
click.echo("\t{}".format(line))
click.echo(f"\t{line}")
for plugin in plugins:
octoprint_compatible = is_octoprint_compatible(
@@ -650,9 +643,9 @@ class BackupPlugin(
on_log_error=on_log_error,
on_invalid_backup=on_log_error,
):
click.echo("Restored from {}".format(path))
click.echo(f"Restored from {path}")
else:
click.echo("Restoring from {} failed".format(path), err=True)
click.echo(f"Restoring from {path} failed", err=True)
return [backup_command, restore_command]
@@ -731,7 +724,7 @@ class BackupPlugin(
try:
os.remove(full_path)
except Exception:
self._logger.exception("Could not delete {}".format(filename))
self._logger.exception(f"Could not delete {filename}")
raise
def _get_backups(self):
@@ -760,7 +753,7 @@ class BackupPlugin(
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
if os.path.exists(data_file):
try:
with io.open(data_file, mode="rt", encoding="utf-8") as f:
with open(data_file, mode="rt", encoding="utf-8") as f:
unknown_plugins = json.load(f)
assert isinstance(unknown_plugins, list)
@@ -858,7 +851,7 @@ class BackupPlugin(
r.raise_for_status()
except Exception:
logger.exception(
"Error while fetching the plugin repository data from {}".format(url)
f"Error while fetching the plugin repository data from {url}"
)
return {}
@@ -879,7 +872,7 @@ class BackupPlugin(
# prepare pip caller
def log(prefix, *lines):
for line in lines:
on_log("{} {}".format(prefix, line.rstrip()))
on_log(f"{prefix} {line.rstrip()}")
def log_call(*lines):
log(">", *lines)
@@ -973,7 +966,7 @@ class BackupPlugin(
configfile = settings._configfile
basedir = settings._basedir
temporary_path = os.path.join(datafolder, ".{}".format(name))
temporary_path = os.path.join(datafolder, f".{name}")
final_path = os.path.join(datafolder, name)
own_folder = datafolder
@@ -1168,7 +1161,7 @@ class BackupPlugin(
temp = tempfile.mkdtemp()
try:
if callable(on_log_progress):
on_log_progress("Unpacking backup to {}...".format(temp))
on_log_progress(f"Unpacking backup to {temp}...")
abstemp = os.path.abspath(temp)
dirs = {}
@@ -1214,7 +1207,7 @@ class BackupPlugin(
plugins = []
plugin_list_file = os.path.join(temp, "plugin_list.json")
if os.path.exists(plugin_list_file):
with io.open(os.path.join(temp, "plugin_list.json"), "rb") as f:
with open(os.path.join(temp, "plugin_list.json"), "rb") as f:
plugins = json.load(f)
known_plugins = []
@@ -1264,16 +1257,12 @@ class BackupPlugin(
basedir_extracted = os.path.join(temp, "basedir")
if callable(on_log_progress):
on_log_progress(
"Renaming {} to {}...".format(basedir, basedir_backup)
)
on_log_progress(f"Renaming {basedir} to {basedir_backup}...")
shutil.move(basedir, basedir_backup)
try:
if callable(on_log_progress):
on_log_progress(
"Moving {} to {}...".format(basedir_extracted, basedir)
)
on_log_progress(f"Moving {basedir_extracted} to {basedir}...")
shutil.move(basedir_extracted, basedir)
except Exception:
if callable(on_log_error):
@@ -1300,7 +1289,7 @@ class BackupPlugin(
datafolder, UNKNOWN_PLUGINS_FILE
)
try:
with io.open(unknown_plugins_path, mode="wb") as f:
with open(unknown_plugins_path, mode="wb") as f:
f.write(to_bytes(json.dumps(unknown_plugins)))
except Exception:
if callable(on_log_error):
@@ -1354,7 +1343,7 @@ class BackupPlugin(
except Exception:
if callable(on_log_error):
on_log_error(
"Error while restarting via command {}".format(restart_command),
f"Error while restarting via command {restart_command}",
exc_info=sys.exc_info(),
)
on_log_error("Please restart OctoPrint manually")
+3 -6
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -57,9 +54,9 @@ class CoreWizardPlugin(
config = {
"type": "wizard",
"name": name,
"template": "corewizard_{}_wizard.jinja2".format(key),
"div": "wizard_plugin_corewizard_{}".format(key),
"suffix": "_{}".format(key),
"template": f"corewizard_{key}_wizard.jinja2",
"div": f"wizard_plugin_corewizard_{key}",
"suffix": f"_{key}",
}
if key in additional:
additional_result = additional[key]()
+7 -11
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -11,11 +8,10 @@ from flask_babel import gettext
import octoprint.plugin
from octoprint.access import ADMIN_GROUP, USER_GROUP
from octoprint.util import to_native_str
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class ServerCommandsSubwizard(object):
class ServerCommandsSubwizard:
def _is_servercommands_wizard_firstrunonly(self):
return True
@@ -42,7 +38,7 @@ class ServerCommandsSubwizard(object):
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class WebcamSubwizard(object):
class WebcamSubwizard:
def _is_webcam_wizard_firstrunonly(self):
return True
@@ -61,7 +57,7 @@ class WebcamSubwizard(object):
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class AclSubwizard(object):
class AclSubwizard:
def _is_acl_wizard_firstrunonly(self):
return False
@@ -113,7 +109,7 @@ class AclSubwizard(object):
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class OnlineCheckSubwizard(object):
class OnlineCheckSubwizard:
def _is_onlinecheck_wizard_firstrunonly(self):
return False
@@ -131,7 +127,7 @@ class OnlineCheckSubwizard(object):
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class PluginBlacklistSubwizard(object):
class PluginBlacklistSubwizard:
def _is_pluginblacklist_wizard_firstrunonly(self):
return False
@@ -149,7 +145,7 @@ class PluginBlacklistSubwizard(object):
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class PrinterProfileSubwizard(object):
class PrinterProfileSubwizard:
def _is_printerprofile_wizard_firstrunonly(self):
return True
@@ -167,7 +163,7 @@ class PrinterProfileSubwizard(object):
Subwizards = type(
to_native_str("Subwizards"),
"Subwizards",
tuple(
cls
for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
+27 -60
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__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"
@@ -11,28 +8,18 @@ The SSDP/UPNP implementations has been largely inspired by https://gist.github.c
For a spec see http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0.pdf
"""
# noinspection PyCompatibility
from builtins import range
import flask
from flask_babel import gettext
import octoprint.plugin
import octoprint.util
try:
# python 3
import zeroconf
except ImportError:
# python 2: vendored version with some backported fixes
import octoprint.vendor.zeroconf as zeroconf
import collections
import platform
import socket
import time
import flask
import zeroconf
from flask_babel import gettext
import octoprint.plugin
import octoprint.util
def __plugin_load__():
plugin = DiscoveryPlugin()
@@ -192,20 +179,15 @@ class DiscoveryPlugin(
# ZeroConf
def _format_zeroconf_service_type(self, service_type):
service_type = octoprint.util.to_native_str(service_type)
if not service_type.endswith(octoprint.util.to_native_str(".")):
service_type += octoprint.util.to_native_str(".")
if not service_type.endswith(octoprint.util.to_native_str("local.")):
service_type += octoprint.util.to_native_str("local.")
if not service_type.endswith("."):
service_type += "."
if not service_type.endswith("local."):
service_type += "local."
return service_type
def _format_zeroconf_name(self, name, service_type):
service_type = self._format_zeroconf_service_type(service_type)
return (
octoprint.util.to_native_str(name)
+ octoprint.util.to_native_str(".")
+ service_type
)
return name + "." + service_type
def _format_zeroconf_txt(self, record):
result = {}
@@ -246,15 +228,15 @@ class DiscoveryPlugin(
name,
addresses=addresses,
port=port,
server="{}.local.".format(socket.gethostname()),
server=f"{socket.gethostname()}.local.",
properties=txt_record,
)
self._zeroconf.register_service(info, allow_name_change=True)
self._zeroconf_registrations[key].append(info)
self._logger.info("Registered '{}' for {}".format(name, reg_type))
self._logger.info(f"Registered '{name}' for {reg_type}")
except Exception:
self._logger.exception(
"Could not register {} for {} on port {}".format(name, reg_type, port)
f"Could not register {name} for {reg_type} on port {port}"
)
def zeroconf_unregister(self, reg_type, port=None):
@@ -278,10 +260,10 @@ class DiscoveryPlugin(
try:
for info in infos:
self._zeroconf.unregister_service(info)
self._logger.debug("Unregistered {} on port {}".format(reg_type, port))
self._logger.debug(f"Unregistered {reg_type} on port {port}")
except Exception:
self._logger.exception(
"Could not (fully) unregister {} on port {}".format(reg_type, port)
f"Could not (fully) unregister {reg_type} on port {port}"
)
def zeroconf_browse(
@@ -332,7 +314,7 @@ class DiscoveryPlugin(
result_available = threading.Event()
result_available.clear()
class ZeroconfListener(object):
class ZeroconfListener:
def __init__(self, logger):
self._logger = logger
@@ -367,9 +349,7 @@ class DiscoveryPlugin(
for address in map(lambda x: socket.inet_ntoa(x), info.addresses):
result.append(to_result(info, address))
self._logger.debug(
"Browsing Zeroconf for {service_type}".format(service_type=service_type)
)
self._logger.debug(f"Browsing Zeroconf for {service_type}")
def browse():
listener = ZeroconfListener(self._logger)
@@ -424,13 +404,7 @@ class DiscoveryPlugin(
import io
import threading
try:
# noinspection PyCompatibility
from http.client import HTTPResponse # py3
except ImportError:
# noinspection PyCompatibility
from httplib import HTTPResponse # py2
from http.client import HTTPResponse
class Response(HTTPResponse):
def __init__(self, response_text):
@@ -613,8 +587,7 @@ class DiscoveryPlugin(
if (
alive
and self._ssdp_last_notify + self._ssdp_notify_timeout
> octoprint.util.monotonic_time()
and self._ssdp_last_notify + self._ssdp_notify_timeout > time.monotonic()
):
# we just sent an alive, no need to send another one now
return
@@ -681,7 +654,7 @@ class DiscoveryPlugin(
except Exception:
pass
self._ssdp_last_notify = octoprint.util.monotonic_time()
self._ssdp_last_notify = time.monotonic()
def _ssdp_monitor(self, timeout=5):
"""
@@ -691,13 +664,7 @@ class DiscoveryPlugin(
alive message
"""
try:
# noinspection PyCompatibility
from http.server import BaseHTTPRequestHandler
except ImportError:
# noinspection PyCompatibility
from BaseHTTPServer import BaseHTTPRequestHandler
from http.server import BaseHTTPRequestHandler
from io import BytesIO
socket.setdefaulttimeout(timeout)
@@ -737,7 +704,7 @@ class DiscoveryPlugin(
+ socket.inet_aton("0.0.0.0"),
)
self._logger.info("Registered {} for SSDP".format(self.get_instance_name()))
self._logger.info(f"Registered {self.get_instance_name()} for SSDP")
self._ssdp_notify(alive=True)
@@ -759,7 +726,7 @@ class DiscoveryPlugin(
interface_address = octoprint.util.address_for_client(
*address,
addresses=self._settings.get(["addresses"]),
interfaces=self._settings.get(["interfaces"])
interfaces=self._settings.get(["interfaces"]),
)
if not interface_address:
continue
@@ -803,9 +770,9 @@ class DiscoveryPlugin(
def get_instance_name(self):
name = self._settings.global_get(["appearance", "name"])
if name:
return 'OctoPrint instance "{}"'.format(name)
return f'OctoPrint instance "{name}"'
else:
return "OctoPrint instance on {}".format(socket.gethostname())
return f"OctoPrint instance on {socket.gethostname()}"
def get_interface_addresses(self):
addresses = self._settings.get(["addresses"])
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__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"
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
from flask_babel import gettext
import octoprint.events
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
+2 -9
View File
@@ -1,10 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__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 os
from os import scandir
from flask import abort, jsonify, request, url_for
from flask_babel import gettext
@@ -19,11 +17,6 @@ from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado
from octoprint.settings import settings
from octoprint.util import is_hidden_path, yaml
try:
from os import scandir
except ImportError:
from scandir import scandir
class LoggingPlugin(
octoprint.plugin.AssetPlugin,
@@ -242,7 +235,7 @@ class LoggingPlugin(
for logger, level in new_levels.items():
level = logging.getLevelName(level)
self._logger.info("Setting logger {} level to {}".format(logger, level))
self._logger.info(f"Setting logger {logger} level to {level}")
self._logger.manager.loggerDict[logger].setLevel(level)
def _is_managed_logger(self, logger):
+33 -67
View File
@@ -1,12 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
import io
import logging
import os
import re
@@ -16,6 +12,7 @@ import tempfile
import threading
import time
from datetime import datetime
from os import scandir
import filetype
import pkg_resources
@@ -23,7 +20,6 @@ import requests
import sarge
from flask import Response, abort, jsonify, request
from flask_babel import gettext
from past.builtins import basestring
import octoprint.plugin
import octoprint.plugin.core
@@ -37,7 +33,7 @@ from octoprint.server.util.flask import (
with_revalidation_checking,
)
from octoprint.settings import valid_boolean_trues
from octoprint.util import TemporaryDirectory, deprecated, to_bytes, to_native_str
from octoprint.util import TemporaryDirectory, deprecated, to_bytes
from octoprint.util.net import download_file
from octoprint.util.pip import create_pip_caller
from octoprint.util.platform import get_os, is_os_compatible
@@ -50,11 +46,6 @@ from octoprint.util.version import (
from . import exceptions
try:
from os import scandir
except ImportError:
from scandir import scandir
_DATA_FORMAT_VERSION = "v3"
DEFAULT_PLUGIN_REPOSITORY = "https://plugins.octoprint.org/plugins.json"
@@ -94,7 +85,7 @@ def map_repository_entry(entry):
if (
"python" in entry["compatibility"]
and entry["compatibility"]["python"] is not None
and isinstance(entry["compatibility"]["python"], basestring)
and isinstance(entry["compatibility"]["python"], str)
):
result["is_compatible"]["python"] = is_python_compatible(
entry["compatibility"]["python"]
@@ -718,9 +709,9 @@ class PluginManagerPlugin(
if ext in PluginManagerPlugin.ARCHIVE_EXTENSIONS:
return True
kind = filetype.guess(to_native_str(path))
kind = filetype.guess(path)
if kind:
return ".{}".format(kind.extension) in PluginManagerPlugin.ARCHIVE_EXTENSIONS
return f".{kind.extension}" in PluginManagerPlugin.ARCHIVE_EXTENSIONS
return False
def _is_pythonfile(self, path):
@@ -729,13 +720,11 @@ class PluginManagerPlugin(
import ast
try:
with io.open(path, "rb") as f:
with open(path, "rb") as f:
ast.parse(f.read(), filename=path)
return True
except Exception as exc:
self._logger.exception(
"Could not parse {} as python file: {}".format(path, exc)
)
self._logger.exception(f"Could not parse {path} as python file: {exc}")
return False
@@ -782,12 +771,12 @@ class PluginManagerPlugin(
raise exceptions.InvalidPackageFormat()
except requests.exceptions.HTTPError as e:
self._logger.error("Could not fetch plugin from server, got {}".format(e))
self._logger.error(f"Could not fetch plugin from server, got {e}")
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Could not fetch plugin from server, got {}".format(e),
"reason": f"Could not fetch plugin from server, got {e}",
}
self._send_result_notification("install", result)
@@ -860,12 +849,7 @@ class PluginManagerPlugin(
self._send_result_notification("install", result)
return result
try:
# Py3
from urllib.parse import quote as url_quote
except ImportError:
# Py2
from urllib import quote as url_quote
from urllib.parse import quote as url_quote
path = os.path.abspath(path)
if os.sep != "/":
@@ -883,7 +867,7 @@ class PluginManagerPlugin(
lambda line: path_url in line.lower()
) # lower case in case of windows
self._logger.info("Installing plugin from {}".format(source))
self._logger.info(f"Installing plugin from {source}")
pip_args = [
"--disable-pip-version-check",
"install",
@@ -929,7 +913,7 @@ class PluginManagerPlugin(
)
force = True
except Exception as e:
self._logger.exception("Could not install plugin from {}".format(source))
self._logger.exception(f"Could not install plugin from {source}")
self._logger.exception("Reason: {}".format(repr(e)))
result = {
"result": False,
@@ -950,9 +934,7 @@ class PluginManagerPlugin(
try:
returncode, stdout, stderr = self._call_pip(pip_args)
except Exception as e:
self._logger.exception(
"Could not install plugin from {}".format(source)
)
self._logger.exception(f"Could not install plugin from {source}")
self._logger.exception("Reason: {}".format(repr(e)))
result = {
"result": False,
@@ -1128,7 +1110,7 @@ class PluginManagerPlugin(
if name is None:
name = os.path.basename(path)
self._logger.info("Installing single file plugin {} from {}".format(name, source))
self._logger.info(f"Installing single file plugin {name} from {source}")
all_plugins_before = self._plugin_manager.find_plugins(existing={})
@@ -1172,10 +1154,10 @@ class PluginManagerPlugin(
# copy plugin
try:
self._log_call("cp {} {}".format(path, destination))
self._log_call(f"cp {path} {destination}")
shutil.copy(path, destination)
except Exception:
self._logger.exception("Installing plugin from {} failed".format(source))
self._logger.exception(f"Installing plugin from {source} failed")
result = {
"result": False,
"source": source,
@@ -1301,22 +1283,16 @@ class PluginManagerPlugin(
if os.path.isdir(full_path):
# plugin is installed via a plugin folder, need to use rmtree to get rid of it
self._log_stdout(
"Deleting plugin from {folder}".format(folder=plugin.location)
)
self._log_stdout(f"Deleting plugin from {plugin.location}")
shutil.rmtree(full_path)
elif os.path.isfile(full_path):
self._log_stdout(
"Deleting plugin from {file}".format(file=plugin.location)
)
self._log_stdout(f"Deleting plugin from {plugin.location}")
os.remove(full_path)
if full_path.endswith(".py"):
pyc_file = "{full_path}c".format(**locals())
if os.path.isfile(pyc_file):
self._log_stdout(
"Deleting plugin from {file}".format(file=pyc_file)
)
self._log_stdout(f"Deleting plugin from {pyc_file}")
os.remove(pyc_file)
else:
@@ -1350,9 +1326,7 @@ class PluginManagerPlugin(
if plugin.enabled:
self._plugin_manager.disable_plugin(plugin.key, plugin=plugin)
except octoprint.plugin.core.PluginLifecycleException as e:
self._logger.exception(
"Problem disabling plugin {name}".format(name=plugin.key)
)
self._logger.exception(f"Problem disabling plugin {plugin.key}")
result = {
"result": False,
"uninstalled": True,
@@ -1367,9 +1341,7 @@ class PluginManagerPlugin(
if plugin.loaded:
self._plugin_manager.unload_plugin(plugin.key)
except octoprint.plugin.core.PluginLifecycleException as e:
self._logger.exception(
"Problem unloading plugin {name}".format(name=plugin.key)
)
self._logger.exception(f"Problem unloading plugin {plugin.key}")
result = {
"result": False,
"uninstalled": True,
@@ -1396,7 +1368,7 @@ class PluginManagerPlugin(
"plugin": self._to_external_plugin(plugin),
}
self._send_result_notification("uninstall", result)
self._logger.info("Plugin {} uninstalled".format(plugin.key))
self._logger.info(f"Plugin {plugin.key} uninstalled")
self._cleanup_disabled(plugin.key)
if cleanup:
@@ -1411,13 +1383,13 @@ class PluginManagerPlugin(
result_notifications=True,
settings_save=True,
):
if isinstance(plugin, basestring):
if isinstance(plugin, str):
key = result_value = plugin
else:
key = plugin.key
result_value = self._to_external_plugin(plugin)
message = "Cleaning up plugin {}...".format(key)
message = f"Cleaning up plugin {key}..."
self._logger.info(message)
self._log_stdout(message)
@@ -1431,7 +1403,7 @@ class PluginManagerPlugin(
# delete plugin data folder
result_data = True
if not self._cleanup_data(key):
message = "Could not delete data folder of plugin {}".format(key)
message = f"Could not delete data folder of plugin {key}"
self._logger.exception(message)
self._log_stderr(message)
result_data = False
@@ -1505,7 +1477,7 @@ class PluginManagerPlugin(
return True
except Exception:
self._logger.exception(
"Could not delete plugin data folder at {}".format(data_folder)
f"Could not delete plugin data folder at {data_folder}"
)
return False
else:
@@ -1759,9 +1731,7 @@ class PluginManagerPlugin(
try:
import json
with io.open(
self._repository_cache_path, "rt", encoding="utf-8"
) as f:
with open(self._repository_cache_path, encoding="utf-8") as f:
repo_data = json.load(f)
self._repository_mtime = mtime
self._logger.info(
@@ -1787,9 +1757,7 @@ class PluginManagerPlugin(
try:
r = requests.get(repository_url, timeout=30)
r.raise_for_status()
self._logger.info(
"Loaded plugin repository data from {}".format(repository_url)
)
self._logger.info(f"Loaded plugin repository data from {repository_url}")
except Exception as e:
self._logger.exception(
"Could not fetch plugins from repository at {repository_url}: {message}".format(
@@ -1801,13 +1769,13 @@ class PluginManagerPlugin(
try:
repo_data = r.json()
except Exception as e:
self._logger.exception("Error while reading repository data: {}".format(e))
self._logger.exception(f"Error while reading repository data: {e}")
return None
# validation
if not isinstance(repo_data, (list, tuple)):
self._logger.warning(
"Invalid repository data: expected a list, got {!r}".format(repo_data)
f"Invalid repository data: expected a list, got {repo_data!r}"
)
return None
@@ -1854,7 +1822,7 @@ class PluginManagerPlugin(
try:
import json
with io.open(self._notices_cache_path, "rt", encoding="utf-8") as f:
with open(self._notices_cache_path, encoding="utf-8") as f:
notice_data = json.load(f)
self._notices_mtime = mtime
self._logger.info("Loaded notice data from disk, was still valid")
@@ -1878,7 +1846,7 @@ class PluginManagerPlugin(
try:
r = requests.get(notices_url, timeout=30)
r.raise_for_status()
self._logger.info("Loaded plugin notices data from {}".format(notices_url))
self._logger.info(f"Loaded plugin notices data from {notices_url}")
except Exception as e:
self._logger.exception(
"Could not fetch notices from {notices_url}: {message}".format(
@@ -1988,9 +1956,7 @@ class PluginManagerPlugin(
try:
result = hook()
if isinstance(result, (list, tuple)):
reconnect_hooks.extend(
filter(lambda x: isinstance(x, basestring), result)
)
reconnect_hooks.extend(filter(lambda x: isinstance(x, str), result))
except Exception:
self._logger.exception(
"Error while retrieving additional hooks for which a "
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -1,22 +1,16 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import datetime
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
import datetime
import hashlib
import logging
import logging.handlers
import os
import threading
import time
# noinspection PyCompatibility
from concurrent import futures
import flask
@@ -389,9 +383,7 @@ class SoftwareUpdatePlugin(
data = psutil.disk_usage(path)
info["free"] = data.free
except Exception:
self._logger.exception(
"Error while determining disk usage of {}".format(path)
)
self._logger.exception(f"Error while determining disk usage of {path}")
continue
storage_info[key] = info
@@ -427,15 +419,13 @@ class SoftwareUpdatePlugin(
)
def _get_check_overlay(self, url):
self._logger.info("Fetching check overlays from {}".format(url))
self._logger.info(f"Fetching check overlays from {url}")
try:
r = requests.get(url, timeout=3.1)
r.raise_for_status()
data = r.json()
except Exception as exc:
self._logger.error(
"Could not fetch check overlay from {}: {}".format(url, exc)
)
self._logger.error(f"Could not fetch check overlay from {url}: {exc}")
return {}
else:
return data
@@ -565,9 +555,7 @@ class SoftwareUpdatePlugin(
)
cleaned_up = len(data) - before_cleanup
if cleaned_up:
self._logger.info(
"Cleaned up {} old update log entries".format(cleaned_up)
)
self._logger.info(f"Cleaned up {cleaned_up} old update log entries")
with self._update_log_mutex:
self._update_log = data
@@ -1352,9 +1340,7 @@ class SoftwareUpdatePlugin(
try:
populated_check = self._populated_check(target, checks[target])
except exceptions.UnknownCheckType:
self._logger.debug(
"Ignoring unknown check type for target {}".format(target)
)
self._logger.debug(f"Ignoring unknown check type for target {target}")
continue
except Exception:
self._logger.exception(
@@ -1568,7 +1554,7 @@ class SoftwareUpdatePlugin(
continue
except Exception:
self._logger.exception(
"Could not check {} for updates".format(target)
f"Could not check {target} for updates"
)
continue
@@ -1718,7 +1704,7 @@ class SoftwareUpdatePlugin(
if isinstance(value, dict):
lines.append("{!r}: {}".format(key, dict_to_sorted_repr(value)))
else:
lines.append("{!r}: {!r}".format(key, value))
lines.append(f"{key!r}: {value!r}")
return "{" + ", ".join(lines) + "}"
@@ -1795,7 +1781,7 @@ class SoftwareUpdatePlugin(
error = "unknown_check"
except exceptions.NetworkError:
self._logger.warning(
"Could not check {} for updates due to a network error".format(target)
f"Could not check {target} for updates due to a network error"
)
update_possible = False
error = "network"
@@ -1809,12 +1795,12 @@ class SoftwareUpdatePlugin(
error = "ratelimit"
except exceptions.CheckError:
self._logger.warning(
"Could not check {} for updates due to a check error".format(target)
f"Could not check {target} for updates due to a check error"
)
update_possible = False
error = "check"
except Exception:
self._logger.exception("Could not check {} for updates".format(target))
self._logger.exception(f"Could not check {target} for updates")
update_possible = False
error = "unknown"
else:
@@ -1824,9 +1810,7 @@ class SoftwareUpdatePlugin(
target, check, online=online
)
except Exception:
self._logger.exception(
"Error while checking if {} can be updated".format(target)
)
self._logger.exception(f"Error while checking if {target} can be updated")
update_possible = False
self._version_cache[target] = {
@@ -1866,9 +1850,7 @@ class SoftwareUpdatePlugin(
try:
populated_checks[target] = self._populated_check(target, check)
except exceptions.UnknownCheckType:
self._logger.debug(
"Ignoring unknown check type for target {}".format(target)
)
self._logger.debug(f"Ignoring unknown check type for target {target}")
except Exception:
self._logger.exception(
"Error while populating check prior to update for target {}".format(
@@ -2058,9 +2040,7 @@ class SoftwareUpdatePlugin(
### The actual update procedure starts here...
try:
self._logger.info(
"Starting update of {} to {}...".format(target, target_version)
)
self._logger.info(f"Starting update of {target} to {target_version}...")
self._send_client_message(
"updating",
{
@@ -2077,9 +2057,7 @@ class SoftwareUpdatePlugin(
target, populated_check, target_version, log_cb=self._log, online=online
)
target_result = ("success", update_result)
self._logger.info(
"Update of {} to {} successful!".format(target, target_version)
)
self._logger.info(f"Update of {target} to {target_version} successful!")
trigger_event(True)
except exceptions.UnknownUpdateType:
@@ -2190,10 +2168,10 @@ class SoftwareUpdatePlugin(
util.execute(restart_command, evaluate_returncode=False, do_async=True)
except exceptions.ScriptError as e:
self._logger.exception(
"Error while restarting via command {}".format(restart_command)
f"Error while restarting via command {restart_command}"
)
self._logger.warning("Restart stdout:\n{}".format(e.stdout))
self._logger.warning("Restart stderr:\n{}".format(e.stderr))
self._logger.warning(f"Restart stdout:\n{e.stdout}")
self._logger.warning(f"Restart stderr:\n{e.stderr}")
raise exceptions.RestartFailed()
def _populated_check(self, target, check):
@@ -2322,7 +2300,7 @@ class SoftwareUpdatePlugin(
data={"loglines": [{"line": line, "stream": stream} for line in lines]},
)
for line in lines:
self._console_logger.debug("{} {}".format(prefix, line))
self._console_logger.debug(f"{prefix} {line}")
def _send_client_message(self, message_type, data=None):
self._plugin_manager.send_plugin_message(
+2 -5
View File
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -65,7 +62,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
click.echo(f"Could not get update information from server, got {e}")
sys.exit(1)
data = r.json()
@@ -233,7 +230,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
click.echo(f"Could not get update information from server, got {e}")
sys.exit(1)
data = r.json()
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__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"
@@ -32,7 +29,7 @@ class NetworkError(Exception):
if self.message is not None:
return self.message
elif self.cause is not None:
return "NetworkError caused by {}".format(self.cause)
return f"NetworkError caused by {self.cause}"
else:
return "NetworkError"
@@ -47,7 +44,7 @@ class CheckError(Exception):
class RateLimitCheckError(CheckError):
def __init__(self, message, remaining=None, limit=None, reset=None):
super(RateLimitCheckError, self).__init__(message)
super().__init__(message)
self.remaining = remaining
self.limit = limit
self.reset = reset
@@ -1,7 +1,4 @@
#!/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Haeussge <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"
@@ -12,8 +9,6 @@ import sys
import time
import traceback
from past.builtins import unicode
# default close_fds settings
if sys.platform == "win32" and sys.version_info < (3, 7):
CLOSE_FDS = False
@@ -56,7 +51,7 @@ def _to_unicode(s_or_u, encoding="utf-8", errors="strict"):
def _to_bytes(s_or_u, encoding="utf-8", errors="strict"):
"""Make sure ``s_or_u`` is a str."""
if isinstance(s_or_u, unicode):
if isinstance(s_or_u, (str, bytes)):
return s_or_u.encode(encoding, errors=errors)
else:
return s_or_u
@@ -96,14 +91,12 @@ def _execute(command, **kwargs):
if not p.commands[0].process:
# the process might have been set to None in case of any exception
print(
"Error while trying to run command {}".format(joined_command),
f"Error while trying to run command {joined_command}",
file=sys.stderr,
)
return None, [], []
except Exception:
print(
"Error while trying to run command {}".format(joined_command), file=sys.stderr
)
print(f"Error while trying to run command {joined_command}", file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
@@ -158,7 +151,7 @@ def _git(args, cwd, git_executable=None):
command = [c] + args
try:
return _execute(command, cwd=cwd)
except EnvironmentError:
except OSError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
@@ -205,7 +198,7 @@ def _to_error(*lines):
if len(lines) == 1:
if isinstance(lines[0], (list, tuple)):
lines = lines[0]
elif not isinstance(lines[0], (str, unicode)):
elif not isinstance(lines[0], (str, bytes)):
lines = [
repr(lines[0]),
]
@@ -219,7 +212,7 @@ def _rescue_changes(git_executable, folder):
)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git diff" failed with returncode {}'.format(returncode)
f'Could not update, "git diff" failed with returncode {returncode}'
)
if stdout and "".join(stdout).strip():
# we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch
@@ -227,9 +220,9 @@ def _rescue_changes(git_executable, folder):
import time
timestamp = time.strftime("%Y%m%d%H%M")
patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp))
patch = os.path.join(folder, f"{timestamp}-preupdate.patch")
print(">>> Running: git diff and saving output to {}".format(patch))
print(f">>> Running: git diff and saving output to {patch}")
returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
@@ -238,9 +231,7 @@ def _rescue_changes(git_executable, folder):
)
)
import io
with io.open(patch, "wt", encoding="utf-8", errors="replace") as f:
with open(patch, "wt", encoding="utf-8", errors="replace") as f:
for line in stdout:
f.write(line)
@@ -279,11 +270,11 @@ def update_source(git_executable, folder, target, force=False, branch=None):
returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git fetch" failed with returncode {}'.format(returncode)
f'Could not update, "git fetch" failed with returncode {returncode}'
)
if branch is not None and branch.strip() != "":
print(">>> Running: git checkout {}".format(branch))
print(f">>> Running: git checkout {branch}")
returncode, stdout, stderr = _git(
["checkout", branch], folder, git_executable=git_executable
)
@@ -298,7 +289,7 @@ def update_source(git_executable, folder, target, force=False, branch=None):
returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git pull" failed with returncode {}'.format(returncode)
f'Could not update, "git pull" failed with returncode {returncode}'
)
if force:
@@ -321,7 +312,7 @@ def install_source(python_executable, folder, user=False, sudo=False):
print(">>> Running: python setup.py clean")
returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable)
if returncode is None or returncode != 0:
print('"python setup.py clean" failed with returncode {}'.format(returncode))
print(f'"python setup.py clean" failed with returncode {returncode}')
print("Continuing anyways")
print(">>> Running: python setup.py install")
@@ -412,7 +403,7 @@ def main():
if python_executable.endswith('"'):
python_executable = python_executable[:-1]
print("Python executable: {!r}".format(python_executable))
print(f"Python executable: {python_executable!r}")
folder = args.folder
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__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"
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__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"
@@ -101,7 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
target_version=target_version, target=target_version
)
logger.debug("Target: {}, executing pip install {}".format(target, install_arg))
logger.debug(f"Target: {target}, executing pip install {install_arg}")
pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"]
pip_kwargs = {
"env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"}
Loaded 100 of 276 files, more files were not shown because too many files have changed in this diff. Show more