742 Commits
Author SHA1 Message Date
Eric Callahan d60b852b27 docs: add documentation for latest changes to the update manager
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-08 10:52:56 -04:00
Eric Callahan dacd9f7565 update_manager: report detected_type and configured_type for applications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-08 09:02:08 -04:00
Eric Callahan d76abe019f update_manager: return True when on update success
All calls to update now return a boolean value.  When performing a full upate this return value is used to
check if Moonraker should wait for Klippy to reconnect.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-08 07:55:50 -04:00
Eric Callahan b6cd19d6ef update_manager: make application package updates generic
This ignores an attempt to update packages if system updates are disabled and opens the possibility for supporting updates for other linux distributions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-07 18:27:12 -04:00
Eric Callahan 74630f933a update_manager: use asyncio locks
Transion away from Tornado's wrappers, as their implementation of
"wait()" can be confusing.  Some of tornado's methods require that
you specify a delay in seconds, others requrire that you specify a
timeout relative to the Unix epoch.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-07 18:27:07 -04:00
Eric Callahan 9133b59dbf update_manager: add "full" update endpoint
This endpoint will perform a full system update.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-07 18:26:30 -04:00
Eric Callahan 10da7b714f update_manager: add support for zip deployment
This adds support for updating packaged applications from GitHub.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 908501cbc8 update_manager: remove unnecessary Is_refreshing check
The underlying deployment implementations use locks to prevent concurrent attempts at refeshing state, thus the "is_refreshing" check is redundant.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 5d35cc0d10 update_manager: Implement async streaming downloads
This allows Moonraker to report download progress.  This also resolves potential issues with I/O blocking the event loop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan f2b48d0f1a update_manager: refactor github API requests
Save a request cache in the CommandHelper that stores the etag and value for each URL requested.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 88ee83c7d8 update_manager: use pathlib to represent file system paths
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan d3ec2dbae2 update_manager: refactor application deployment
This is the first step toward creating mutliple methods for deployment.  This patch creates a base class for all deployment objects and a base class for application deployment.  The git functionality has moved to its own module.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 78edcab86e confighelper: don't add supplemental configs to the original
Create a new ConfigParser that reads the supplemental and return a new ConfigWrapper.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 627db24c63 update_manager: make system updates optional
Remove the "distro" config option as it is not necessary.  If there is a need to identify the linux distribution that can now be done through the distro dependency.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 7c56a8fa74 utils: add method to validate packaged applications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 0527904c48 moonraker: remove references to "system_args"
Rather than add these arguments to the config, use a method to access them from the server object.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 3642003dd2 workflows: add workflow to publish assets for a new release
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 2c47064d79 scripts: add release build scripts
Add a script that can build zipped releases to be distributed by Moonraker's Update Manager.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 39a532cf87 utils: move git version parsing into its own method
This creates a generic utility for retreiving the git version.  Moonraker will now attempt to parse basic version info from a ".version" file if git describe fails.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan ebaac290e7 utils: add a method to calculate the hash of a directory
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 5379e4b4bd scripts: remove version.txt
This file is no longer required for moonraker, the version info will either be stored in the pex file or retreived from git.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 6b03c4600d scripts: minor install script fixes
Fix the systemd unit description.  Make the launch command variable.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 7ed54a166b scripts: provide a log path option in install-moonraker.sh
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 2ab63d75fc moonraker: fix imports for type checking
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 1c248d1de8 moonraker: remove check for component existence in "load_component()"
The importlib module will raise an exception if the component does not exist, so the check is redundant.  This allow allows packages to be loaded.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 261fbbc867 file_manager: move modules to its own package
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 346015e528 update_manager: move the "rebuild env" functionality
Initially rebuilding the venv was required to change env options to include dist packages.  This is no longer necessary so we can remove detection for it.  Building a venv could still be necessary, so move this functionality to its own method.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 8b8d538a9c update_manager: remove dist package options
These options are no longer necessary, as we now apply the dist path before the import in modules that require dist packages.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 5b260a5ba6 update_manager: correct relative paths
Update the paths to Moonraker and the supplemental configuration file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>

Update update_manager.py
2021-07-06 19:25:10 -04:00
Arksine 03892a517e update_manger: move module into its own package
This includes its specific configuration file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 30155c4a8c power: add special handling for gpiod import
Rather than symlink the gpiod dependency in a virtualenv, temporarily add the dist-package to sys.path then import gpiod.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine bfef2eb98e file_manager: update location of metadata script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 7ccb455174 metadata: move extract_metadata.py to components
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 80df137437 websockets: fix call to wait() in WebsocketHandler.close()
The wait timeout must be relative to the current time.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:24:52 -04:00
Eric Callahan a605cd3048 file_manager: NotifySyncLock bugfix
The time() method must be called on the current IOLoop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:22:46 -04:00
Eric Callahan c7f8689bfe docs: fix incorrect documentation on eventtime
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 15:54:29 -04:00
Eric Callahan 12a7f957c3 docs: note addition of the "eventtime" param to "notify_status_update"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 15:43:02 -04:00
Eric Callahan c6fee3c1f4 moonraker: send status eventtime as a second parameter to "notify_status_update"
This resolves a potential issue where clients could anticipate that all items in the status parameter are objects.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 14:56:18 -04:00
Eric Callahan 81854d1daf moonraker: report Klipper event time with status subscriptions
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-06 14:35:09 -04:00
Eric Callahan 4836f52a5d shell_command: ignore utf8 decode errors
Also catch a potential KeyError when removing running commands.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 07:26:09 -04:00
Eric Callahan 5c05afae42 docs: Update mkdocs version
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-28 20:27:40 -04:00
Eric Callahan 77052e15b0 docs: update MQTT documentation
Reflect the new behavior of wait_connection()

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-28 20:27:40 -04:00
Eric Callahan ecc0fbdae9 mqtt: return a boolean in the wait_connection method
Rather than require consumers handle the TimeoutError, handle it directly and return the connection state.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-28 12:45:50 -04:00
Eric Callahan 00f4bd594f app: prevent static file reads from blocking the event loop
Perform reads in a thread so File I/O does not block.

This patch also disables ETags for static files.  Tornado's default behavior of caching file hashes will not work as many of Moonraker's can be updated.  The previous workaround to this was to recalculate the checksum if the modified date changed.  This is inefficient  as its behavior is not much different than using "If-Modified-Since".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-28 07:31:40 -04:00
Eric Callahan 3529acfeec proc_stats: report a blocked event loop
Use the PeriodicCallback in proc_stats to check if the event loop was blocked for a More than 5 seconds.  If this is detected, log
Moonraker's CPU usage over that time.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-27 17:10:49 -04:00
Eric Callahan 1510f66121 app: Process file uploads in a thread pool executor
This should prevent large file uploads from blocking the asyncio event loop for a long period of time.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-27 12:33:52 -04:00
Eric Callahan c22dcc18dc docs: Remove unreferenced macro
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-26 20:12:10 -04:00
Eric Callahan b6f9769488 websockets: refactor message handling
Implement a write buffer so that all calls to "write_message" are awaited.  This allows for more graceful shutdown if the websocket is closed.

When Moonraker shuts down, attempt to wait for all websockets to close before exiting.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-26 15:33:35 -04:00
Eric Callahan 188dc4c782 docs: add MQTT documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-26 11:44:29 -04:00
Eric Callahan 0126aa794f mqtt: initial support for mqtt connections
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-26 08:10:32 -04:00
Eric Callahan 2bc7efd20e octoprint_compat: only register endpoints with the http transport
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-25 17:46:43 -04:00
Eric Callahan 566df69ca5 moonraker: expose additional app methods
Add references to the application's "get_websocket_manager" and "register_api_transport" methods.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-25 17:46:43 -04:00
Eric Callahan 40f21b10cd app: allow transport registration
This allows eligible components to register themselves as API transports.  By default the WebsocketManager is registered.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-25 17:46:43 -04:00
Eric Callahan a7801db6e7 websockets: Make the JsonRPC class more generic
Allow JsonRPC to be used with transports other than the websocket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-25 17:46:43 -04:00
Eric Callahan 06bbca7ae3 moonraker: add method to set a component as failed
Some components require post-load initialization after the IOLoop has started.  Provide a method for these components to register a failure with the server.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-22 19:38:09 -04:00
Eric Callahan 331be63c9e scripts: add paho-mqtt dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-22 08:21:26 -04:00
Eric Callahan d3df568aec extract_metadata: don't remove ufp files after failed extraction
Cura writes ufp files in chunks, closing the file after each chunk is written.  This will result in a failed extraction, and removing the file will result in corruption.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-18 06:15:54 -04:00
Eric Callahan 9e909e8532 docs: add "cancelled" state to print_stats documentation
Refactor the available values so that they are more readable.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-16 15:50:04 -04:00
Eric Callahan 1b2fa4924b docs: fix typo in metadata return value
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-15 15:25:40 -04:00
Kamil Trzcinski 20673b9edd pause_resume: Make Moonraker to use pause_resume/* API
This switches Moonraker from calling `CANCEL_PRINT` and alikes
to rather use `pause_resume/` API that underneath calls
the relevant G-Codes.

This done, this way, allows Klipper to be able to interrupt
blocking operations gracefully.

Signed-off-by: Kamil Trzcinski <ayufan@ayufan.eu>
2021-06-15 12:22:43 -04:00
Rafael Schridi 3b4bfba85e Add variable domain support for Home Assistant
Defaults to the hard-coded "switch" domain used before

Signed-off-by:  Rafael Schridi <r.schridi@gmail.com>
2021-06-13 18:17:08 -04:00
Eric Callahan 42bdb42573 database: read out all namespaces on init
If a namespace contains an invalid key reading out the namespace should correct the issue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-13 11:04:44 -04:00
Eric Callahan c9a958f861 database: track unsafe shutdowns
Keep track of the number of unsafe shutdowns a machine experiences.  This data is useful in diagnosing potential file system issues and issues with the datbase itself.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-13 09:15:09 -04:00
Eric Callahan 9a316fe84a database: check for invalid keys
It is invalid for a namespace to contain a top level key represented as an empty bytestring.  If this is detected, log the result and drop the invalid key.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-13 08:18:12 -04:00
Eric Callahan 92423911a9 file_manager: upload request fix
Make sure that inotify watches are added for new directories created via the upload endpoint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-12 17:22:01 -04:00
Kamil Trzcinski 6770a965a6 history: add support for cancelled state
Signed-off-by: Kamil Trzcinski <ayufan@ayufan.eu>
2021-06-12 11:35:35 -04:00
Eric Callahan 33cb18517a docs: update response to "/machine/system_info"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-10 19:58:11 -04:00
Eric Callahan 9ea91f4f5d machine: report total memory from /proc/meminfo
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-10 19:58:11 -04:00
dependabot[bot] d9d3739118 build(deps): bump pillow from 8.1.2 to 8.2.0 in /scripts
Bumps [pillow](https://github.com/python-pillow/Pillow) from 8.1.2 to 8.2.0.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/master/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/8.1.2...8.2.0)

---
updated-dependencies:
- dependency-name: pillow
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-08 19:20:15 -04:00
Eric Callahan 0b885ec5ec file_manager: scan metadata for renamed gcode files
Some slicers create a temporary file during export, then rename the file with gcode extension after completion.  If file metadata does not exist during an attempt to move metadata, scan the file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-08 16:55:04 -04:00
Eric Callahan b16110bcd0 mooraker: refactor stop_server()
Shutdown the websocket and http server before doing final component cleanup.  This prevents clients from making a request after components have been closed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-07 11:17:52 -04:00
Eric Callahan 936d766cae authorization: correctly handle the transition from a deprecated signature algorithm
SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-04 14:48:21 -04:00
Eric Callahan 108d0578a2 scripts: update moonraker python requirements
Remove python jose and cryptography.  Add pynacl.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-03 05:46:14 -04:00
Eric Callahan 39343f984a authorization: switch to EdDSA signatures
This removes the cryptography dependency in favor of libsodium.  Also removed is python-jose, as we must generate our own JWTs for use with EdDSA.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>

use libnacl instead of pynacl
2021-06-03 05:45:56 -04:00
Eric Callahan 628c0193f3 machine: extend allowed services
Allow all services that start with a match.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-02 17:46:34 -04:00
Eric Callahan def6b365fa machine: fix service case sensitivity bug
Systemd units are case sensitive, do not convert the "name" argument for service requests to lower case.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-31 07:34:16 -04:00
Eric Callahan 0ab9ffdc93 docs: add machine API changes
MoonCord and KlipperScreen have been added to supported services.  The "/machine/system_info" endpoint now returns a list of available services that moonraker may control.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-30 14:36:28 -04:00
Eric Callahan 1b3efb1a78 machine: add support for controlling MoonCord and KlipperScreen services
Provide a list of available services in the `/machine/system_info` endpoint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-30 14:21:07 -04:00
Alan Harper d6156dee68 power: Fix Home Assistant exception
Home Assistant returns an empty response when switching a switch
on or off. Will now requery the switch status and return it's result

Signed-off-by:  Alan Harper <alan@aussiegeek.net>
2021-05-29 14:12:20 -04:00
Alan Harper 541f5e54dc power: Add https support for Home Assistant
Signed-off-by:  Alan Harper <alan@aussiegeek.net>
2021-05-29 14:12:20 -04:00
Eric Callahan 793ab6b24b app: add a redirect endpoint
Clients can use this in situations where a browser may
prompt the user to take action prior to sending the
request.  After the user accepts, Moonraker will redirect the user to the url provided in the request.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-28 21:03:03 -04:00
Eric Callahan 082134b9a0 authorization: raise a 401 error in the event that a JWT failes decoding
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-28 18:26:32 -04:00
Arksine 2db727e40f file_manager: handle situations where file transfer is corrupt
The addition of inotify can introduce scenarios where file transfers complete abruptly, resulting in a corrupt/incomplete file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-26 06:41:59 -04:00
Arksine fc5420db27 file_manager: filter out websocket notifcations in the gcodes root
Only push notifications for files with valid gcode extensions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-26 06:32:31 -04:00
Arksine aeb24dabdb file_manager: add watches for hidden directories
The logic used to sync requests to modify contents in hidden directories is no longer necessary, thus removed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-26 06:32:31 -04:00
Arksine 3d0d1e1dcb file_manager: disallow requests for paths outside of a root
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-26 06:31:47 -04:00
Arksine 5f7cff9af8 authorization: attempt to resolve cryptography import issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-24 07:25:31 -04:00
Arksine d7c367f095 update_manager: update pip before installing new python deps
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-24 06:38:10 -04:00
Arksine aa9641024a authorization: restrict CORS headers on non-options requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 20:36:26 -04:00
Arksine 60d6c748ef moonraker: rename deprecated "logging.warn"
Python uses "logging.warning" to log warning level methods.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 14:46:46 -04:00
Arksine dc4da6087f authorization: rename the oneshot request handler
Naming the method "_handle_oneshot_request" is less ambiguous than "_handle_token_request".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 14:46:46 -04:00
Arksine 8a3b885eca authorization: use ES256 algorithm for JWT signatures
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 14:46:46 -04:00
Arksine ce7f659a32 authorization: use python_jose dependency for jwt management
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 09:09:53 -04:00
Arksine e4e58f6d97 scripts: add python-jose python dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 09:09:53 -04:00
Arksine a18987aa59 app: raise an exception if configured ssl cert or key files do not exist
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-22 08:22:46 -04:00
Arksine 5db74b724e docs: document https configuration options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 20:00:41 -04:00
Arksine aba3e374c3 test client: fix mixed content issues with https
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 15:25:26 -04:00
Arksine dcf1cdf526 moonraker: add support for serving https with self signed certs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 12:45:45 -04:00
Arksine 68b9a073af update_manager: compare file hashes rather than modified times
The metadata won't always depict an actual change to the content of a file.  Compare a hash of the file content rather than retrieve modified times to determine if it is necessary to install dependencies.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:58:40 -04:00
Arksine f1ba8e3d9b shell_command: Use a lock to prevent re-entrant calls
Re-entrant calls to "run" and "run_with_response" would poison the process state resulting in unexpected behavior.  Use a lock to prevent this.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine e7193dbb5f shell_command: track running commands and cancel them prior to moonraker exit
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine e15ef345bc shell_command: run_with_response fixes
Reset the command tracking data before each retry.  If the command is cancelled by the user immediately break.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine 564e33bc18 update_manager: enhance attempt to recover from loose object errors
Attempt to recover from "loose object" error in git status and git fetch commands.   It is no longer necessary to run git fsck on every refresh attempt, only run it after a recovery attempt.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine daa7b5edd4 update_manager: allow the remote method to run a generic command
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine a012c4b772 update_manager: remove unused rsync methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine 58f7aa0a57 update_manager: Implement clone method for GitRepo class
Replace the existing rsync "hard" recovery method with a call to git clone.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine 81f2393b46 update_manager: Don't set the std_err_callback for async git commands
When no callback is set for stderr, the outputfrom stderr is piped to stdout.  This makes setting the callback redundant.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine 5d783a743a app: re-enable authorization checks on static files
Image files (.png) are still granted unauthorized access, however all other files require that the request be authorized.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-20 17:07:48 -04:00
Arksine c335b62d26 file_manager: fix sync issues with hidden directories
While inotify watches are not applied to hidden directories it is still valid to use Moonraker's endpoints to perform operations on them.  When performing an operation on an item within a hidden directory, or on a hidden directory itself,  do not sync the request with inotify.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-20 08:35:26 -04:00
Arksine e7ca2d6adc docs: add 'warnings' field to "/server/info" response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 20:42:44 -04:00
Arksine ceae5bb88b moonraker: report a 'warnings' field in "/server/info"
This allows clients to display a list of warnings that Moonraker detects.   Previously this info was only logged.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 20:37:36 -04:00
Arksine 36aec50bce docs: update authorization documentation
Document the "force_logins" option and the ability to accept JSON Web Tokens via the query string.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 19:59:06 -04:00
Arksine b8cf0d7fd2 authorization: check the query string for jwts
Clients may pass a json web token via the query string's "access_token" argument to authorize requests that do not allow modified headers.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 19:18:23 -04:00
Arksine dca7bd51cd authorization: add 'force_logins' option
When "force_logins" is enabled a user login is required if at least one user is registered, overriding the "trusted_clients" configuration.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 19:05:48 -04:00
Vladimir Poleh 6b9a3c656d app: Fixed download for the files with non-ASCII characters in name.
Replace non-ASCII characters with "?" and add escaped unicode version of the file name to the "Content-Disposition" header to fix problems with thumbnails and downloading for the gcode file with non-ASCII characters in filename.

Signed-off-by: Uladzimir Palekh <visor.rti@gmail.com>
2021-05-19 17:43:49 -04:00
Arksine 829b3a4ee8 docs: document log path for the file manager
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 08:26:30 -04:00
Arksine f5ccddb52b file_manager: add support for an optional "logs" root
This root may be used to store log files for Klipper, Moonraker, and other applications as necessary.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 08:23:24 -04:00
Arksine 94e1dcf2cb docs: update contributing doc
Update the code style guidelines informing contributors that they should validate their code with pycodestyle and mypy before submission.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 08:19:21 -04:00
Arksine 7465de389f gh-actions: enable mypy static type checking
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 07:34:05 -04:00
Arksine c83d91eea7 extract_metadata: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 06:59:38 -04:00
Arksine dbe28751df file_manager: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 06:59:38 -04:00
Arksine d392a895d9 update_manager: add annotations
USER CHANGE:  The deprecated "client_repo" and "client_path" options have been removed in this commit.  Use [update_manger client client_name] to configure clients.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 06:59:38 -04:00
Arksine 1026d59cad paneldue: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 06:59:38 -04:00
Arksine 1ada457364 power: add annotiations
This includes a refactoring of the PowerDevice base class so that it defines some abstract methods that its children must implement.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 06:54:57 -04:00
Arksine 12246029ef proc_stats: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine c977948c2c octoprint_compat: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 9994e1eb84 machine: Add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 1755d0f970 history: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine f5010e960b data_store: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 9bf4ade35b klippy_apis: Add annotiations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine ce7495ecce shell_command: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 41ddbb16a8 authorization: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 410db750c6 database: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine b91df6642d app: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 420ba065da confighelper: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:48 -04:00
Arksine ca69a10838 moonraker: add annotations
Annotate function definitions, class attributes, and local variables as necessary for type hinting.  This is useful for IDEs with linters that support type hints and also can be used by GitHub Actions to detect erroneous code.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:48 -04:00
Arksine 9c76dbef7a websockets: add annotations
Implement a "Subscribable" base class for objects that can maintain a status subscription.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:48 -04:00
Arksine 96e69240ca utils: add annotations
Add a SentinelClass singleton.  This can be used to generate Sentinels by
modules that need to use the Sentinel pattern for default values.  This
allows for more robust type checking, as the Sentinel type should not be
included as a return value.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:48 -04:00
Arksine 6c27885702 file_manager: send "root_update" notification for all registered directories
This includes non mutable directories such as "config_examples" and "docs".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 5a2e2b1f3f docs: update return value for "/server/files/list"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 316c6b5fa1 file_manager: rename "filename" field to "path" in "/server/files/list" request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine b2f8413057 docs: update documentation for changes to file_manager
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 17a436bc27 file_manager: validate file extension before attempting to parse metadata
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 93a29e0e34 file_manager: return more descriptive responses for op requests
File manager operations now return values similar to that of file change notifications.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine d46f04de0b file_manager: delete file trees in another thread
On slower platforms it is possible for this to take time and block the event loop.   Run shutil.rmtree in another thread to prevent this from occuring.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 55941b106b file_manager: only run the operation check for files in the "gcodes" root
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine ebaf355878 file_manager: synchronize inotify events with api requests
If an inotify event is generated as the result of an API request, the notifications are synchronized so that they occur after the request returns.  Use a mutex to prevent multiple "write" requests processing concurrently.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 21d290beb7 file_manager: implement metadata "move" functionality
If a file is moved from one location to another in the "gcodes" root it isn't necessary to rescan the file metadata as the underlying file information does not change.   Add the ability to change the metadata's key and move associated thumbnails when a file is moved.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine a9f1a98fa2 file_manager: remove metadata_update notifications
Since filelist_changed notifications are now delayed until after metadata is processed there is no need to send an additional metadata notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 5fe9f1a217 file_manager: don't send filelist notifications until metadata is processed
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 9da74f7bc6 file_manager: implement inotify using a bidirectional tree
Rather than tracking watch paths directly, wrap each watch in a node.  This makes makes it a bit easier to handle move and delete changes, as we don't have to manage several different dicts to store the information we need.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine e4d61de406 file_manager: bundle directory creation events
When a directory is created, attempt to suppress notifications generated as its children are created.
Wait until all items are copied before notifying clients and scanning metadata.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 93fcd1ae86 file_manager: process copy requests in another thread
The copy methods are blocking and will block the asyncio event loop.  Run them in a  ThreadPoolExecutor to keep the event loop free.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 43fcca5ffa scripts: add inotify-simple dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 9c31a360ee file_manager: remove child watches when a directory is stale
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine bb00825cd2 file_manager: bundle inotify delete events
When a directory is deleted this attempts to suppress delete events for all children.  Clients only need to be notified of the parent node, as its deletion implies all children have been deleted.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine db0eb8f22b extract_metadata: remove base64 data from metadata
The previously deprecated "data" field has now been removed. The "size" field now reports the size of the png.  Clients may use the "relative_path" field to retrieve thumbnail png files.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine c40c202220 file_manager: allow extract_metadata to unzip ufp files
This guarantees that .ufps will not be unzipped in parallel and offloads a potential blocking operation to another process.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine eaf35ded0c extract_metadata: add support for ufp file extraction
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine ecbf663b18 file_manager: make the thumbs directory hidden
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 23dd001a9b file_manager: don't add inotify watches for hidden directories
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 48607f8ab3 file_manager: allow inotify to exclusively handle gcode metadata and ufp files
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine c2871d94ed file_manager: remove gcode metadata prune callback
Inotify keeps metadata in sync with the file system.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 7744b1fd8a test_client: update file list changed notification
Handle the new action nomenclature correctly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 5756e27711 file_manager: exclusively manage websocket notifications using inotify
This removes all calls to "notify_filelist_changed" in the FileManager class.  This also simplfies the previous `_convert_path()` method, as it is no longer necessary to return the path relative to the root.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine fbb1fcf500 file_manager: add support for inotify event based monitoring
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 5f9b0e9b86 app: don't require authorization to retreive static files
Generally speaking static files do not require authorization, so there should be little harm in bypassing auth checks.  This allows clients to retrieve assets without XHRs or requesting tokens.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-17 17:52:47 -04:00
Arksine 9fe6ef82a5 power: Don't query a gpio line in "refresh_status"
On some devices gpiod does not report the correct state.  Since Moonraker maintains exclusive control over GPIO lines, its unnecessary to query the line itself for state, as we can maintain it ourselves.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-17 16:53:28 -04:00
Arksine fd07b077b9 update_manager: increase fetch timeout to 5 minutes
This should allow git's internal timeout mechanisms to trigger at the expense of potentially delaying response time if a fetch or pull hangs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-15 07:14:17 -04:00
Arksine 158f92f17f docs: Update the delete user documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-14 12:59:30 -04:00
Arksine e73f9b7bf5 test: add a delete user form to the test client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-14 12:59:30 -04:00
Arksine 2ba85533c2 authorization: refactor user delete API
It is now possible for any authorized request to delete a user, however a logged in user cannot delete its own account.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-14 12:59:30 -04:00
Arksine 490e66fe07 authorization: bypass authorization check when the request method is OPTIONS
If CORS is enabled then then OPTIONS should always return 204.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 19:33:42 -04:00
Arksine 4a61bf21de docs: update "/access/users/list" documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 18:01:18 -04:00
Arksine b3187710d0 authorization: Return more detail in "/access/users/list"
Return a list of objects with username and creation date fields.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 17:58:07 -04:00
Arksine e472fb6c1e docs: update authorization documentation
Add documentation for the "/access/users/list" endpoint.  Document the "notify_user_created" and "notify_user_deleted" websocket notifications.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 15:38:41 -04:00
Arksine 1af7f7d550 authorization: send websocket notifications when a user is created or deleted
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 15:24:41 -04:00
Arksine 400cefebc8 authorization: add '/access/users/list' API request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 14:58:22 -04:00
Arksine d3c251bc52 docs: update power module documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-10 08:42:08 -04:00
Arksine 0274a641b2 power: add LoxoneV1 support
This is a refactored version of loxone V1 support submitted by EraserFX.  Closes PR #94.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-10 07:50:23 -04:00
Arksine 0917536ccc power: use a mutex to prevent concurrent device requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-10 07:50:23 -04:00
Arksine 724c29c4a7 power: implement an HTTPDevice base class
This allows for some additional code reuse that is duplicated amongst several HTTP Device implementations.
2021-05-10 07:50:23 -04:00
Arksine 8e6bb34d1b power: remove unnecessary calls to get_server()
The server attribute for these classes is already assigned by their parent.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-10 07:50:23 -04:00
Arksine c02964e95c power: add endpoint for toggling a single device
A single endpoint that can be used to both toggle and retrieve device state is useful for interoperability with home automation software.  The previous endpoints will remain as they are still useful for batch operations.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-10 07:50:23 -04:00
Arksine cb8e5af8f7 power: always refresh status prior to processing a request
Make sure that the current device state is correct in the event that a device is toggled by an external source.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 19:36:58 -04:00
Arksine 06bea715a3 power: store device classes in a dict
This provides a cleaner way of adding new types.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 17:28:33 -04:00
Arksine 3d01b0b9da update_manager: attempt to handle empty git objects
Always run git fsck when initializing a repo.  If a loose object error is detected when running git pull or git fetch, attempt to remove  loose objects and retry.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 14:53:56 -04:00
Arksine f339aa7454 update_manager: don't allow repo init waiters to return success on a failure
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 12:47:33 -04:00
Arksine e69ac489c7 gh_actions: fix broken yaml
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:56:15 -04:00
Arksine 52f08eda08 extract_metdata: fix whitespace errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:17:24 -04:00
Arksine a746019790 power: fix whitespace errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:16:14 -04:00
Arksine efdcc263dd shell_command: fix typo
The trailing underscore in IDX_SIGKILL is not correct.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:15:20 -04:00
Arksine 4ee32ebaf3 history: minor codestyle change
Use the accepted "not in"  test for membership.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:13:18 -04:00
Arksine acd3b3c064 gh_actions: add initial test workflow
The intial test uses the python-lint action to validate code style
according to the preferences used for Python code in the Moonraker
repo.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:10:28 -04:00
Sébastien Jousse c53b95aa93 power: Add Home Assistant switch support
* power: Add Home Assistant switch support

Signed-off-by:  Sébastien Jousse <s.jousse@gmail.com>
2021-05-05 07:14:25 -04:00
Arksine 40d4daa96b docs: update proc_stats API documentation
Document the "cpu_temp" field in the "/machine/proc_stats" request along with the new "notify_proc_stat_update" websocket notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-03 08:59:19 -04:00
Arksine 68b793f059 test: register proc stat json-rpc notifications in client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-02 20:48:29 -04:00
Arksine f705f1145a proc_stats: add notify_proc_stat_update websocket notifcation
Report CPU temp in addition to moonraker stats in this notification and the proc_stat request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-02 20:42:19 -04:00
Arksine 5321a8a558 docs: update authorization documentation
The "trusted_clients" option now supports fqdns (full qualified domain names).

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-29 19:40:06 -04:00
Arksine 46e1d7b66b authorization: support fqdns as "trusted_clients"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-29 19:16:57 -04:00
Arksine 497423ddc2 confighelper: log detailed parsing errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-27 08:52:34 -04:00
Arksine 80707d1734 proc_stats: send cpu_throttled event when throttled state changes
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-04-26 12:35:40 -04:00
Arksine 275bcde081 docs: add documentation for /machine/system_info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-26 12:08:52 -04:00
Arksine 24eaff6951 machine: add distribution to system info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-26 12:08:52 -04:00
Arksine 5e87d8793d machine: add support for retrieving CPU and SDCard info
Add this info to the log rollover so it is always visible.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-26 12:08:52 -04:00
Stefan Dej 0791c658ad fix moonraker process stats link
Signed-off-by: Stefan Dej <meteyou@gmail.com>
2021-04-25 11:30:37 -04:00
Arksine 37615d4790 proc_stats: add CPU throttled flags to log rollover
Don't continuously log a change in throttled state, only log when a new throttled flag is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-23 07:03:17 -04:00
Maciej Rutkowski b9487276e9 power: Fix Shelly behavior when a timer is configured (#149)
* power: Fix Shelly behavior when a timer is configured

Signed-off-by:  Maciej Rutkowski <dev@nomadic.works>
2021-04-22 08:47:40 -04:00
Arksine 46dea00b2f docs: Document "Kasa Power Strip" configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 19:59:59 -04:00
Arksine 85be5cbfc1 docs: add "checksum" option to file upload documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 18:12:30 -04:00
Arksine 2b79a129aa app: fix unauthorized file upload access
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 18:12:30 -04:00
Arksine d42fd3b095 docs: fix accidental removal of trusted_clients option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 18:12:30 -04:00
Arksine 25b6f6fb34 test: add checksum calculation to client upload
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 18:12:30 -04:00
Arksine 9478678ea0 app: Add sha256 checksum validation to file uploads
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 18:12:30 -04:00
Arksine 2c078cbc7c database: don't return forbidden namespaces in the list request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 06:34:46 -04:00
Arksine 3627331527 scripts: update to lmdb 1.2.1
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 06:03:42 -04:00
Arksine f4ebb93546 docs: update documentation for the Authorization component
USER_CHANGE:  The "enable" and "api_key_file" options in the [authorizaton] section are now deprecated.  A new API Key will be generated.  Use the "fetch-apikey.sh" script to retrieve the new key.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 64e794f1b5 scripts: add fetch-apikey helper script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 5bba0fc2fa scripts: bump lmdb version to 1.2.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine a4273d2d0a test: implement JWT Authorization for test client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 0c765f7b71 app: improve http request logging
Log the current user for each request.   Dont' log requests that return with 200, 204, 206, or 304 in release mode.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 4e0e223599 authorization: allow auth related CORS Headers
Allow Authorization, X-Api-Key, and X-Access-Token headers when CORS is enabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 7eba8e58e3 authorization: add support for JWT User Authorizaton
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 43a8d25619 websockets: Store IP Address in WebRequest object
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 24e6fded91 authorization: use database to store API Key
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine dee9055347 database: introduce forbidden namespaces
A Moonraker component may now register a namespace as "forbidden".   API requests have no read/write access to forbidden namespaces and this cannot be overridden by the database debug option.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 0ce53bd98f app: return HTTP errors in json format
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 14991ac3b9 authorization: convert module to component
CONFIG CHANGE:  This deprecates the "enabled" option in the [authorization] section.  Authorization will be enabled if the section is included in moonraker.conf,  otherwise it will be disabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 57836047f6 octoprint compat: use subscriptions to update printer data
This tends to be more efficient than polling, particularly on slower machines.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:12:26 -04:00
Arksine 9873084667 octoprint_compat: correctly report printer state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 06:20:27 -04:00
Arksine e8f6862fd2 app: cache modified time in static file handler
Force an update to cached file hashes should the modified time change.  Re-enable the "should_return_304" check so clients can re-implement caching.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-17 07:05:31 -04:00
th33xitus 4d69a1f1c6 extract_metadata: parse filament_total and filament_total_weight for Slic3r
Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-17 06:06:53 -04:00
th33xitus f203567381 extract_metadata: add Cura filament weight parsing
Adds a simple implementation for parsing filament weight from Cura g-code with help of a custom start-g-code comment.

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-17 06:06:53 -04:00
th33xitus 0d601073a6 extract_metadata: add parsing of filament weight
This will parse the total used filament weight of g-code files created by Simplify3D, PrusaSlicer, SuperSlicer and ideaMaker

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-17 06:06:53 -04:00
Arksine daf3b202c3 app: restrict static file size to the detected content length
Some static files, such as logs, can change size during a request.  This results in a content length mismatch and error.   Cap the amount read based on the original content length.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-16 07:49:44 -04:00
Arksine 087240aa67 app: don't return 304 for static files
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-16 07:29:18 -04:00
Arksine 210cae2736 file_manager: check for broken symlinks in "get_file_list()"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-13 15:26:32 -04:00
th33xitus dae0f05378 extract_metadata: assign correct data parameter
This fix will now correctly parse the used filament from g-code generated by ideaMaker. The used filament is located in the footer of the g-code file.

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-11 11:36:06 -04:00
Arksine 4d1a2668f5 docs: add notes about sending M112 gcodes
Also  document the new "full_version_string" field reported by the update_manager.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-09 14:59:39 -04:00
Arksine 7d3bba75e1 update_manager: report full version string for git repos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-09 14:59:39 -04:00
fsironman b111e3d6c7 power.py add parameter timer
Add a timer parameter to shelly and tasmota integration.

Use case: 3D printer mains power is connected to one of these devices. Just turning off the smart switch will just kill power to the RaspberryPI. Adding a timer will allow the PI to shutdown cleanly before killing the power

Signed-off-by: Dominik Weis fsironman@gmail.com
2021-04-06 17:58:51 -04:00
Kamil Trzciński 6cc11276c8 Extend history API with reverse order
Signed-off-by: Kamil Trzciński <ayufan@ayufan.eu>
2021-04-05 11:41:14 -04:00
Arksine 5db596f0a5 docs: Add database debugging option to configuration.md
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 11:58:43 -04:00
Arksine aa3ffdbaaf power: fix whitespace issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 11:37:21 -04:00
Arksine 8724d5e9ed database: add "enable_database_debug" option
This allows protected namespaces to be modified externally.  This is for dev use only, modifying protected namespaces can potentially corrupt the database.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 11:37:21 -04:00
Arksine da9401dd1a database: make protected namespaces persistent
This fixes a bug where it is protected namespace can be modified in an optional component if that component is disabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 08:25:40 -04:00
Arnaud Schaer 85b1b44e20 power.py: fix issue with single relay tasmota
add a check and handle consequently in case tasmota device is only one relay and would return a power value when asked a power1 value

Signed-off-by:  Arnaud Schaer <arnaud.schaer@wanadoo.fr>
2021-04-02 08:24:32 -04:00
Michael Kreitzer c36f989c52 power: Adding TPLinkSmartPlug multi plug support (clean-up and sign off)
Signed-off-by:  Michael Kreitzer <reztierk@gmail.com>
2021-03-31 06:55:32 -04:00
Arksine 210f505157 docs: document changes to the update_manager
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 14:05:24 -04:00
Arksine 61c62154ae readme: Add mooncord to list of clients
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 12:05:23 -04:00
Arksine c18f0dac60 update_manager: add support for npm package updates
Execute "npm ci" for Git Repos that include node packages.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 12:01:33 -04:00
Arksine daad55640b update_manager: send a "update_refreshed" notification after init
The Klipper repo always initializes last.  Send a notification at this time, so if any clients are connected they can receive the full update status after init.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 09:19:14 -04:00
Arksine e489b795e6 update_manager: remove deprecated "include_deps" parameter in the update endpoint
During normal updates dependencies will always been updated when necessary.  It is possible to force a dependency updating using the new "/machine/update/recover" endpoint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 09:19:14 -04:00
Arksine 6b91b1eac1 scripts: add rsync and zlib1g-dev dependencies to the install script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 09:19:14 -04:00
Arksine c0389fbf3f update_manager: use SIGKILL to cancel git processes
It is necessary to guarantee that the process dies when cancelled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 09:19:14 -04:00
Arksine 9b0c9810a4 shell_command: allow callers to specify a "signal index"
Gives callers flexibility as to which signal is used to cancel a command first.  By default shell_command will start with SIGTERM, then proceed to SIGKILL.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 09:19:14 -04:00
Arksine da9b9e184d moonraker: Add a .gitignore file
Ignore bytecode.  This keeps git status compact and prevents git clean from removing these files.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 09:19:14 -04:00
Arksine eb681fc960 update_manager: implement git repo recovery endpoint
Rather than attempt to automate recovery, provide an endpoint for clients
to initiate.  Clients can choose between a "hard" recovery, which removes
a corrupt repo and restores from a backup, or a "soft" recover which attempts
a git clean followed by a git reset.

Backups are now only taken when a valid repo is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 09:19:14 -04:00
Arksine 6b0d981274 update_manager: add support for setting a shell command's cwd
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 09:15:00 -04:00
Arksine f1f318ea40 shell_command: add support for setting the cwd
This allows callers to set the current working directory in which the command should execute.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-29 07:17:53 -04:00
Arksine fb1f76e008 shell_command: ShellCommandError fix
Ensure that the stdout and stderr attributes cannot be set to a None type.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-28 20:49:19 -04:00
Arksine d6de095e66 update_manager: capture stdout and stderr from all git calls
Report this output back to clients so that users identify a failed command.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-28 20:49:19 -04:00
Arksine b1f8eaae51 update_manager: only perform rsync backups on clean repos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-26 08:55:48 -04:00
Arksine f0a6620267 docs: fix incorrect reference to ConfigWrapper in components.md
The correct object name is ConfigHelper.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-22 16:54:34 -04:00
Arksine eec85f86a9 docs: add /server/history/totals to documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-22 16:51:50 -04:00
Arksine e7f605327f history: set maximum jobs stored to 10000
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-22 11:45:15 -04:00
Arksine 4b13af4d86 history: track and report total job statistics
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-22 11:41:38 -04:00
Arksine f38cacd513 history: fix "/server/history/list" when no jobs are present
Return an empty list instead of an empty object.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-21 14:43:28 -04:00
Arksine c48fe983de scripts: update pillow to 8.1.2
Resolves security vulnerability in previous version reported by GitHub dependabot.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 20:32:06 -04:00
Arksine 8acd0f2728 docs: remove references to plugins and create components.md
Replace various notes with admonitions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 17:16:36 -04:00
Arksine 1dc920019c moonraker: rename the "plugins" package to "components"
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:29:31 -04:00
Arksine 976f9a732c power: fix whitespace issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:28:32 -04:00
Arksine bf67bce65f update_manager: replace references to "plugin" with "component"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:26:04 -04:00
Arksine f5c27f27ce shell_command: replace references to "plugin" with "component"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:25:08 -04:00
Arksine 480430720f proc_stats: replace references to "plugin" with "component"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:24:20 -04:00
Arksine fe8c7af79f power: replace references to "plugin" with "component"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:23:40 -04:00
Arksine 891d6bd871 paneldue: replace references to "plugin" with "component"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:22:53 -04:00
Arksine e251f26487 octoprint_compat: replace references to "plugin" with "component"
Note that this does not replace references to "Cura" or "Octoprint" plugins, which are also included in this module.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:22:12 -04:00
Arksine e2894b9907 machine: replace references to "plugin" with "component"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:20:53 -04:00
Arksine 92ac1ee21f klippy_apis: replace references to "plugin" with "component"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:20:10 -04:00
Arksine 6e6d974bad history: replace references to "plugin" with "component"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:19:19 -04:00
Arksine 8e609c503f file_manager: replace references to "plugin" with "component"
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:18:43 -04:00
Arksine 7949b6400b database: replace references to "plugin" with "component"
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:17:56 -04:00
Arksine 8d93bcf438 data_store: replace refrences to "plugin" with "component"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:16:56 -04:00
Arksine ce78e42065 app: use "lookup_component" instead of "lookup_plugin"
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:14:01 -04:00
Arksine ed217fb3e9 moonraker: replace all references of "plugins" to "components"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 08:12:56 -04:00
Arksine 0c455fcc0d update_manager: combine "init" locks into a single event.
It isn't necessary for each updater to have their own init lock. Combine them all into a single Event that is set after the "initialize_updaters" method completes.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-18 06:29:32 -04:00
Arksine 5e99378466 update_manager: increase shell command timeouts
Give more time for a standard command to complete.  This may help prevent a git command from being terminated prematurely.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-03-17 20:33:02 -04:00
Arksine 48621da6aa update_manager: apply the command lock to initialization
This makes sure that the Klipper and Moonraker git repos are not initialized simultaneously.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-17 20:33:02 -04:00
Arksine 47902cb03c update_manager: implement rsync recovery for git
Git repos can occasionally become corrupted when attempting to deploy updates thought automated means.  Use rysnc to create a backup of each git repo, allowing the repo to be restored in the event of a corrupted repo.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-17 20:33:02 -04:00
Arksine 038fcec1f4 file_manager: update call to "run_with_response" method in metadata.
Since "run_with_response" now raises an exception there is no need to inspect the response for a None type.  Instead the exception can be handled by the caller directly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-17 19:35:41 -04:00
Arksine 06c35fa0b2 shell_command: raise a ShellCommandError in run_with_response
This error contains the return code and anything received from stdout and stderr when "run_with_response" encounters an error.  This allows the caller to receive the output and easily distinguish between a successfully run command and an erronous command.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-17 15:57:18 -04:00
Arksine 3f48dd5510 database: sync the database before closing
This should prevent the database from losing entries on a reboot.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-17 06:53:20 -04:00
Arksine d9d087b9f3 docs: add "print_start_time" and "job_id" to the metadata documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-16 20:04:25 -04:00
Arksine 1e8ec5c517 history: update gcode metadata start time and job id fields
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-16 20:04:25 -04:00
Arksine 06a07f09e5 file_manager: initialize "print_start_time" and "job_id" fields in metadata
These fields will be updated by the [history] module.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-16 20:04:25 -04:00
Arksine 94ed9fbd7f docs: add documentation for the update_manager's primary_branch option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-16 14:26:45 -04:00
Arksine cd4641f959 update_manager: remove stale git lock files
Sometimes git will erroneously leave the lock file in place when a command fails.  Check for locked git repo before initialization, waiting up to 60 seconds before forcefully removing the lock.  Also check for a locked repo after a failed fetch or pull, removing it if it exists.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-16 14:26:44 -04:00
Arksine 4b89de53f7 update_manager: add "primary_branch" option
Git clients may specify a branch other than "master" as the primary to pass the validation checks.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-16 14:26:44 -04:00
Arksine 62265fd086 app: fix bug in type hint conversion method
Signed-off-by: Eric Callahan  <arksine.code@gmail.com>
2021-03-16 09:13:05 -04:00
Arksine e990e64ccd docs: Add .readthedocs.yaml
Use Python 3.8 and pin the version of mkdocs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-16 08:38:53 -04:00
Arksine 1615af731b readme: Add link to Read The Docs
Update the links for user changes and api changes.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-16 08:35:18 -04:00
Arksine dc60143ef8 docs: prepare documentation for readthedocs
This commit adds mkdocs.yml and modifies the existing markdown documentation so that  "readthedocs" can build documentation using "mkdocs".

Included are many formatting changes and fixes to the existing documentation so that it shows up correctly when published.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-16 06:34:17 -04:00
Arksine 7e230c1c77 docs: update API documenation to reflect recent changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-15 07:03:01 -04:00
Arksine 78324e0df4 scripts: remove deprecated moonraker-start.sh lsb script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-15 06:14:59 -04:00
Mark Dietzer a04958b1bf power: Add HomeSeer control
Signed-off-by: Mark Dietzer <git@doridian.net>
2021-03-15 06:00:17 -04:00
Arksine f09cd413ca history: add an "exists" field to requested jobs
This field does not persist in the database as it is subject change if a file is moved or deleted when Moonraker is not running.

Also add thumbnail information to the metadata sans the base64 image data for each entry.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-14 18:25:35 -04:00
Arksine 62012726da file_manager: add a "check_file_exists" method
Other modules may look up this plugin to determine if a particular file exists at the specified root.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-14 18:23:27 -04:00
Arksine a5c455a305 history: return removed item in NamespaceWrapper.delete()
This is required for the "pop" functionality to work correctly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-14 16:50:08 -04:00
Arksine ca2bd380cf file_manager: set a metadata version to force re-processing
When an entry is removed from metadata also remove associated thumbnails.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-14 16:50:08 -04:00
Arksine 05b8c4eaef extract_metadata: Copy thumbnails to the "thumbs" directory
Include a relative path the the thumbnail in the metadata.   This commit deprecates base64 image transfers.  A future commit will remove base64 data from the metadata, clients will be expected to retrieve thumbnails as a static file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-14 14:33:24 -04:00
Arksine 3b99307109 update_manager: don't raise an exception when restarting moonraker
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-14 08:49:51 -04:00
Arksine 5f741c28a5 update_manager: store detached remote in database
This allows the update manager to recover the remote should the upstream remote repo change.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-14 08:26:12 -04:00
Arksine 91e59706fa update_manager: track commits behind for git repos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-14 08:26:12 -04:00
Arksine ec3bb22c63 update_manager: automate git repo dependency checks
Moonraker now checks the modified time of both the install script and requirements file for git repos.  If either is out of date their associated dependencies will be installed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-14 08:26:12 -04:00
Arksine 978fcffab5 docs: fix API documentation for [octoprint_compat]
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-13 08:13:50 -05:00
Arksine 083d63568c docs: update history api documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-13 08:12:39 -05:00
Arksine 53ad4cb493 history: store job keys as zero padded hex values
This ensures that jobs in the database will be stored in the order they were started.  Doing so also eliminates the need for the `history_auto_inc_id", as we can initialize the next id from the database keys.

This also caches history keys in memory so we do not need to read them from the database on each access.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-13 07:00:10 -05:00
Arksine dd321a4754 history: refactor state tracking
Add an additional checks to determine if a job needs to be cancelled when we receive a new "printing" state.  A file name mismatch or a decrease in total_duration indicates a virtual sdcard reset.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-13 06:51:16 -05:00
Arksine 84bc9aa311 history: add "history_changed" notification
Notify clients when a job has been added or when it has been finished.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-13 06:51:16 -05:00
Arksine 1367083f99 history: refactor the APIs for consistency
Add GET and DELETE `/server/history/job` APIs and remvoe the `DELETE /server/history/delete` API.  When returning a list of jobs, return it as an array rather than as a object.  The `/server/history/list` API no longer accepts a job id.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-13 06:50:23 -05:00
Arksine 9331031f55 history: use mapping protocol to access namespaces where appropriate
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-12 12:35:11 -05:00
Arksine f0adbcf62d history: minor formatting changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-12 08:43:49 -05:00
Arksine d45ec3466e update_manager: default the GitUpdater "python_reqs" attribute to None
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-12 08:40:49 -05:00
Arksine 832eb6f130 update_manager: explicitly check if a repo path contains a .git folder
This allows the repo init sequence to distinguish between a broken git repo and an invalid git repo.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-12 08:40:49 -05:00
jordanruthe 9988da72c1 history: print history tracking
Signed-off-by: Jordan Ruthe <jordan.ruthe@gmail.com>
2021-03-11 20:09:25 -05:00
Arksine 7c89756263 authorization: allow trusted cors IPs on ports other than 80
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-10 20:35:07 -05:00
Arksine 92de4b75ee docs: Update documentation for changes to cors_domains option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-10 19:42:39 -05:00
Arksine 93e7eaa5b5 authorization: automatically pass "trusted" IPs when cors_domains is configured.
If a trusted IP address is passed as the origin then it is safe to assume that CORS access to this origin should be granted, but only if CORS is enabled by specifying at least one cors domain.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-10 19:28:43 -05:00
Arksine 0a3a83de37 authorization: check for dangerous "cors_domains"
A user may unintentionally allow access to dangerous domains if they place a wildcard in the top level domain portion of an entry.  Raise a config error when this condition is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-10 18:19:28 -05:00
Arksine df82730832 update_manager: refactor GitUpdater
Move git command functionality to its own class outside of the Updater class.  This class is responsible for tracking repo state and executing commands on the repo.  Fetch and Pull no longer use built in command timeouts, instead a callback is scheduled to see if the command returned progress.  Only when no progress is returned will a fetch or pull be terminated after a timeout.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-09 18:13:45 -05:00
Arksine 9632465a78 update_manager: create a CommandHelper class
This class handles running shell commands and sending http API requests.  Each updater class  shares an instance of the command helper rather than the UpdateManager instance.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-09 16:52:23 -05:00
Arksine 22b3a953c5 shell_command: fix verbosity issue when logging to stderr
In the "run()" method verbosity should still be allowed if log_stderr is True, even
if both callbacks are not set.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-03-09 16:52:23 -05:00
Arksine 51fd460b59 database: respect case for "namespace" and "key" arguments in request handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-09 16:52:03 -05:00
Arksine 2e0d3f36b4 moonraker: call optional "on_exit()" plugin method before "close()"
This allows plugins to interact with other plugins before they are closed.  For example, a plugin may wish to save persistent state to the database before it is closed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-08 17:04:06 -05:00
Arksine 5144508410 app: always log HTTP errors
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-03-08 15:36:19 -05:00
Arksine 056a9db23e file_manager: add .nc to valid gcode extensions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-07 21:01:51 -05:00
Arksine d20631e69f shell_command: enable stderr if a callback is set
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-07 09:11:11 -05:00
Arksine 15890b9e87 app: add a custom default request handler
This handler provides consistent error reporting in the event that the client attempts to access an unknown endpoint.  If the request is unauthorized, an 401 will be returned.  Otherwise a 404 will be returned, however if CORS is available the CORS headers will be set.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-07 06:47:28 -05:00
Arksine 9563bcff11 update_manager: add environment variables to git fetch and git pull
Pass GIT_HTTP_LOW_SPEED_LIMIT and  GIT_HTTP_LOW_SPEED_TIME environment variables to the "git fetch" and "git pull" commands.  If the remote is unreachable this should force the command to timeout before Moonraker forcefully terminates it.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-06 20:24:03 -05:00
Arksine 5d095125d3 shell_command: add "log_complete" argument to run methods
This brings consistency to the "run" methods.  It also removes potential confusion between the previous "quiet" argument and the "verbose" argument in "run()".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-06 19:25:14 -05:00
Arksine 44f1147f71 shell_command: remove "fire and forget" functionality
A consumer of shell command can achieve "fire and forget" by scheduling the future returned by "run()" to execute on the event loop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-06 19:20:48 -05:00
Arksine dc165636cb shell_command: extend output support
It is now possible to redirect stderr to a callback for asynchronous message transfer.   Also added is the env option, allowing custom environment variables to be passed to the subprocess.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-06 18:24:49 -05:00
Arksine 29644bd44c shell_command: Attempt to cleanly exit cancelled commands
Rather than use terminate to pre-emptively exit a shell command, attempt to exit with SIGINT, SIGTERM, and finally SIGKILL.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-06 14:54:12 -05:00
Arksine 606625a3aa docs: Update documentation with logging changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-06 07:56:21 -05:00
Arksine 438ffece72 app: initialize all logging options
Moving log level init to the app module and have it explicitly set the level.  This allows the logging level to be toggled with a server restart.  Default debug logging to False.

When debug logging is disabled do not  log HTTP requests.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-06 07:34:43 -05:00
Arksine d108334c37 octoprint_compat: "/api/printer" bugfix
Only report extruder and bed temperatures.  Use dict "get()" methods to make sure that the fields are available.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-06 06:26:38 -05:00
Arksine 13ccdb4df1 app: raise a clear exception when request arguments fail to parse
This error is an indication that a JSON body was sent without the content type set to "application/json".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 15:10:53 -05:00
Arksine 4de33bae4a scripts: update dependency version to 0.4.1
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 13:00:10 -05:00
Arksine 316fac1e75 docs: update default for max_upload_size
We now default 1024 MiB.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 12:59:42 -05:00
Arksine d057795bee scripts: add streaming-form-data dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 12:52:01 -05:00
Arksine 4efce1b868 file_manager: extract UFP files to disk rather than memory
The prior implementations assumed that uploaded files would be buffered in memory.
This is no longer the case, so UFP extraction is more efficient when done straight to disk.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 12:07:13 -05:00
Arksine db13827a48 shell_command: only log stderr if output was returned
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 12:07:13 -05:00
Arksine 4c914d7b4d file_manager: add support for streaming file uploads
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 12:07:13 -05:00
Arksine f1edaa1f61 app: add support for streaming file uploads
This should reduce issues with large file uploads.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 05:25:28 -05:00
th33xitus a111733431 docs: fix incorrect wording. 'mainsail' should correctly read 'moonraker'
Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-03-05 05:17:00 -05:00
Arksine c8a2aa7a6c confighelper: don't warn on valid sections without options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 21:15:30 -05:00
Arksine 84f663e2bc docs: update user_changes with octoprint_compat requirement
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 20:59:27 -05:00
Grigi 6ba45f6e35 docs: Document simulated Octoprint API
Signed-off-by:  Nickolas Grigoriadis <nagrigoriadis@gmail.com>
2021-03-04 20:52:55 -05:00
Grigi 39ab419c1f octoprint_compat: Compatibility with Cura Octoprint plugin to upload UFP files.
This PR is a minimal implementation of the Octoprint REST API that is required
for Cura to be able to establish a connection and  send gcode/UFP files to
moonraker without errors.
Currently it only supports the "global apikey authentication" method.

Signed-off-by:  Nickolas Grigoriadis <nagrigoriadis@gmail.com>
2021-03-04 20:52:55 -05:00
Евгений Непомнящий 228ed34eb1 docs: add git_repo path example
Signed-off-by: Eugene Rush <rush.zlo@gmail.com>
2021-03-04 20:43:05 -05:00
Евгений Непомнящий 0fa3c14f51 update_manager: expand user on path
Signed-off-by: Eugene Rush <rush.zlo@gmail.com>
2021-03-04 20:41:48 -05:00
Arksine 46680f4cda docs: add documentation for new machine APIs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:52:49 -05:00
Arksine e32c14b1a7 machine: add service "stop" and "start" endpoints
This allows clients to toggle specific services on/off.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:45:31 -05:00
Arksine 1f9d896e17 update_manager: attempt client archive download before removing old client files
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:45:31 -05:00
Arksine d9edcd9396 shell_command: Add "quiet" argument to run_with_response
This reduces logging when "run_with_response" is called from a loop or a timer.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:45:31 -05:00
Arksine 22a5f6720c shell_command: reset internal proc state in "run_with_response"
This sets a clean state should a shell command be run more than once.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:45:31 -05:00
Arksine cea9af1ef8 proc_stats: moonraker process tracking
Track Moonraker CPU Usage, Rss Memory Usage, and Raspberry Pi Throttled State.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:45:31 -05:00
Arksine 63c685e1c4 database: return 404 when a key or namespace is not found
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-03 19:23:18 -05:00
Arksine 84f46b1cb1 app: fix issue with json Content-Type checks
Allow the Content-Type header to specify a "charset" by only validating the start of the string.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-03 19:13:20 -05:00
Arksine d1dfa86081 docs: fix typos in last web_api update
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-01 15:53:35 -05:00
Arksine dbf5f93919 docs: add more detail to the API overview in web_api.md
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-01 15:49:52 -05:00
Arksine d878340a7a app: refactor the dynamic request handlers
Unify the Local and Remote request handlers into a single handler.  This reduces duplicated code.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-01 11:50:09 -05:00
Arksine fb24917f1a app: expand support for HTTP arguments
Request arguments may now be parsed from the path, body, and query string.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-02-28 19:45:11 -05:00
Arksine 62324650e5 update_manager: improve the git owner regex
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-28 17:51:12 -05:00
Arksine bf48744048 update_manager: report "owner" in update status
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 20:36:12 -05:00
Arksine 6c994f6c9c machine: add webcamd to the list of allowed services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 20:05:22 -05:00
Arksine bb3eb27b3d scripts: bump dependency version to 0.4.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 17:29:09 -05:00
Arksine 94b690c2e9 docs: add database documentation
Also add documentation for query string type hints.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 17:29:09 -05:00
Arksine aa4c13742e app: add support for query string type hints
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 17:29:09 -05:00
Arksine 900345e2d9 scripts: add lmdb dependencies
Signed-off-by:  Eric Callahan arksine.code@gmail.com
2021-02-27 17:29:09 -05:00
Arksine ec85b31a62 paneldue: exit send loop when serial port is disconnected
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:48 -05:00
Arksine ab6ed40bcb websockets: minor fixes
When a websocket is closed, set "is_closed" to True in the on_closed handler.   When closing all websockets, iterate through a list of values.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:48 -05:00
Arksine 87e136003f file_manager: save metadata to the database
This allows gcode file metadata to persist through restarts, reducing the time spent parsing.  The gcode file path also persists, so it is available even when Klippy is not.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:48 -05:00
Arksine 7ff54d8f2f file_manager: use "run_with_response" to extract metadata
Enable logging to stderr so that it is not necessary to extract logged data from the command.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 9e41d9d84b extract_metadata: write log output to stderr
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 75dce0af1a shell_command: refactor using asyncio
At times a subprocess created by shell command fails.  Attempt to mitigate this by using asyncio's version of subprocess, which should be more stable when running via the event loop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 4abfb886f5 moonraker: don't explictly load klippy_apis in init
Instead, look up klippy_apis after all plugins are loaded.  This allows the "CORE_PLUGINS" list to determine the exact order in which core plugins are loaded.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 979aef2903 websockets: explicitly log JSON-RPC errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 958a0f3270 moonraker: add handler for SIGTERM
This performs a graceful shutdown when SIGTERM is received.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 54b1bd8b04 database: initial implementation
This provides an lmdb database which can be used to keep persistent data.   This can be used by internal plugins or by clients.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:54:59 -05:00
Arksine 1f61357dd6 update_manager: register websocket notifications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-17 08:33:00 -05:00
Arksine b89aa77bc9 power: register websocket notification
Change event prefix from "gpio_power" to "power".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-17 08:33:00 -05:00
Arksine 537ba281ab file_manager: register websocket notifications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-17 08:33:00 -05:00
Arksine 83c24ff765 moonraker: register notifications via the websocket's "register_notification" method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-17 08:27:59 -05:00
Arksine b726747261 websockets: implement "register_notification" method
Rather than require developers to add new notification handlers to websockets.py directly, implement a method that may be called to register websocket notifications during init.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-17 08:27:59 -05:00
Arksine eb37ce767d docs: add documentation for "/server/config" endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-16 11:43:31 -05:00
Arksine 60ba8ff1d5 moonraker: validate parsed configuration options after plugins are loaded
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-16 06:38:23 -05:00
Arksine 45557b8260 confighelper: add method to validate configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-16 06:38:23 -05:00
Arksine f229c3ec2c moonraker: add "GET /server/config" endpoint
Clients may call this method to retrieve moonraker's current configuration in json format.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-16 06:35:01 -05:00
Arksine 0e22a0cfe8 confighelper: track parsed configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-16 06:35:00 -05:00
Arksine f2135d7483 websockets: improve closed websocket handling
When a closed websocket is detected set a flag to prevent further status updates until the websocket is removed.

Also make sure that the associated subscriptions are removed if a closed websocket is detected during a notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-15 11:26:54 -05:00
Arksine baf97f8ea4 docs: document new "data_store" options.
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-14 17:50:45 -05:00
Arksine 29b89fb87d data_store: make the temperature and gcode store sizes configurable
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-14 17:46:05 -05:00
Arksine ec7936ee97 confighelper: fix bug that ignores enable_debug_logging option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-11 15:14:40 -05:00
Arksine ceaa4911bb scripts: revert the "remove_sudo_fix" addition
This causes the uninstallation script to fail if the user has not applied the patch.  It should be removed in a separate script.

Signed-off-by:  Eric Callahan <arksine.colde@gmail.com>
2021-02-08 06:48:19 -05:00
Arksine f9dcda7ba9 scripts: update uninstallation script
Remove the LSB or systemd service, depending on which is installed.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-08 06:45:01 -05:00
zellneralex 0fcae5b6e4 power: add Shelly device support
Signed-off-by: Alex Zellner <alexander.zellner@googlemali.com>
2021-02-07 07:31:04 -05:00
Arksine dd81beab47 extract_metadata: add support for metadata thumbnail extraction in Cura
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-06 08:39:41 -05:00
Arksine 9648630392 file_manager: process ufp files found when refreshing a directory
This allows users to manaully place ufp files in the gcode directory.  Resolves #81.

Signed-off-by:  Eric Callahan  <arskine.code@gmail.com>
2021-01-31 12:33:50 -05:00
Arksine fe2cec1087 update_manager: use glob pattern matching to find site package folder
This allows for python version flexibility.  Resolves #76.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-31 12:33:33 -05:00
Arksine 81104a6618 docs: update documentation for latest changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com
2021-01-31 07:41:16 -05:00
Arksine 980912270e data_store: store fan speed for temperature fans
Refactor the the temperature store to only store fields available to a sensor.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-01-31 06:52:42 -05:00
Arksine 39334d1098 update_manager: add "persistent_files" option to web clients
This allows clients to define files that will persist through an update, useful if the client has some sort of static configuration.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-31 06:52:42 -05:00
Arksine 943b78195b power: fix incorrect indentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-28 07:36:21 -05:00
Arksine 49c5583e95 machine: fix typo in service restart handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-28 07:35:33 -05:00
Arksine e8776a5d85 docs: fix incorrect wording for 'klipper_restart_when_powered'
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-27 07:12:19 -05:00
Arksine 9c385ce067 docs: document 'restart_klipper_when_powered' option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-27 06:58:27 -05:00
Arksine 9e240c3b86 power: add "klipper_restart_method" option
When this option is set Mooraker will restart Klipper after the device has been powered on.  An additional "restart_delay" option has been added to customize the delay in which the restart is executed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-27 06:58:27 -05:00
Arksine c365de32cf machine: add "restart_service" method
Move the service restart functionality out of the "service restart" request into its own method.  This allows the "service restart" to be called internally by other modules.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-27 06:22:15 -05:00
Arksine aa9bf0fb9c docs: document the enable_auto_refresh option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-26 18:05:06 -05:00
Arksine ddc7405249 update_manager: resolve initialization issues
Fix issue where apt-get update is called on startup.  This should only be done by the "auto updater" or by a specific request to refresh.

Always set an Updater's init event to true when refresh() is called, regardless of the result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-26 17:47:10 -05:00
Arksine 25b3911d3d confighelper: fix bug in "getfloat" method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Arksine 19bc2bfbb8 update_manager: make auto refresh optional
Decrease the frequency of auto updates roughly every 24 hours.  The manager will attempt to update once between 12am and 4am.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Arksine 578ce740c5 docs: update API documentation for changes to update_manager
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Arksine 6a88df095e scripts: modify update_manger.conf for new configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Jordan Ruthe c17d86aa09 docs: update configuration to reflect multiple update clients
Signed-off-by: Jordan Ruthe <jordan.ruthe@gmail.com>
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Arksine 0ad97fd9eb update_manager: extract and verify configurable git repo options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Jordan Ruthe f3ae6da635 update_manager: Allow for multiple client entries
Signed-off-by: Jordan Ruthe <jordan.ruthe@gmail.com>
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Arksine e9ab5fb480 power: add missing call to super() for Tasmota devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:16:51 -05:00
Arksine 21d1726bfd power: report device name in error when "locked while printing"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 11:20:36 -05:00
Jordan Ruthe 0b3b8cede8 power: Raise error if trying to change a locked device during printing
Signed-off-by: Jordan Ruthe <jordan.ruthe@gmail.com>
2021-01-22 11:00:31 -05:00
Jordan Ruthe 00db209d5d power: Add 'locked_while_printing' to device list
Signed-off-by: Jordan Ruthe <jordan.ruthe@gmail.com>
2021-01-22 11:00:31 -05:00
Jordan Ruthe b4602115d7 power: add "locked_while_printing" option to avoid accidental shutdown
Signed-off-by: Jordan Ruthe <jordan.ruthe@gmail.com>
2021-01-22 11:00:31 -05:00
Arksine ff8e53b269 moonraker: return list of registered directors in server.info response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-20 10:21:27 -05:00
Arksine e2c325a724 extract_metadata: support first layer height expressed as a percentage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-16 12:46:56 -05:00
Arksine a1f2228473 extract_metadata: add shebang to script
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-01-16 12:38:54 -05:00
Arksine d70bd8d2e0 data_store: add support for storing gcode commands
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-12 14:56:37 -05:00
Bryan Mayland 8c365c62cb data_store: Add heater PWM value to /server/temperature_store
Signed-off-by: Bryan Mayland <bmayland@capnbry.net>
2021-01-12 11:36:19 -05:00
Volodymyr Babchynskyy 6f4a72fe2e Readme: added link to Klipper
Signed-off-by: Volodymyr Babchynskyy <vvchik@gmail.com>
2021-01-09 05:46:28 -05:00
Arksine bdd270fa4a update_manager: wrap calls to http.fetch in "gen.with_timeout"
This is a workaround for an issue where the http client fails to propogate an exception back to the caller, hanging the update process.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-07 20:27:23 -05:00
Arksine d194ce00ab update_manager: send notification response upon update error
Attach "is_complete" to the response so clients know that the transaction is done, even though it resulted in an error.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 19:42:40 -05:00
Arksine 5f986ab770 power: refactor initialization
The entire configuration should be validated prior to device initialization.  In the event of an error, the GPIO Chip factory must be closed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 14:39:33 -05:00
Arksine e0f4b46364 update_manager: refactor initialization
We need to be sure that the entire update_manager is correctly configured prior to queueing the callbacks for the initial refresh.   Rather than have each updater spawn a "refesh" callback, move them all into a single init method spawned after the module has been fully configured.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 14:14:12 -05:00
Arksine fb3706c54f paneldue: configure the serial connection last
This allows the PanelDue object to be properly cleaned in the event of a configuration error.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 14:00:29 -05:00
Arksine d1388080c4 moonraker: don't crash the server if an optional plugin fails to import
The server can still operate and be used to fetch the logs if a plugin fails to load.  Add a 'failed_plugins' field to the /server/info response so clients can notify users that this plugin failed to load.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 12:32:26 -05:00
Arksine f1a75117db confighelper: add config file path to systemargs
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-01-06 12:05:10 -05:00
Arksine 4ae63dbbf8 moonraker: log config file at startup
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 12:05:10 -05:00
Arksine 30637011e6 utils: add method for setting rollover info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 12:05:09 -05:00
Arksine 8a18fa6c2f confighelper: Add method to write config to a file object
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 09:09:29 -05:00
Arksine 4cd97d61f9 file_manager: remove unnecessary call to get_file_list() in get_file_metadata()
If the metadata doesnt exist simply return an empty dict.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 07:49:47 -05:00
Arksine 40f876192c file_manager: check for new metadata on each call to _list_directory
Previously this check was only on done when a directory was requested by the API.  Moving this check to _list_directory ()updates metadata for internal calls as well.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 07:19:37 -05:00
Arksine fa53d889d0 file_mananager: Use absolute paths instead of normalized paths
This prevents potential issues where relative paths may be compared to absolute paths.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-05 12:09:52 -05:00
Arksine 6fcb26ddd7 file_manager: skip broken symlinks in list directory
This resolves an issue where an exception is raised when path info is requested.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-05 11:27:46 -05:00
Arksine 67adcfc448 docs: note update_manager API changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-04 08:51:41 -05:00
Arksine 0c280122fb websockets: Add "update_refreshed" notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-04 08:18:11 -05:00
Arksine 5b9f637c2d update_manager: Implement auto refresh
The slower system package update will now only executed by the auto-refresh routine.  Moonraker will check for updates roughly every 2 hours, however system packages updates will only occur between 1am and 4am local time.

If a print is in progress any attempt to refresh or update will be aborted.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-04 08:18:10 -05:00
Arksine 2bb9128b5b docs: document the "off_when_shutdown" option for the power plugin
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 19:53:41 -05:00
Arksine 222f0c4695 power: introduce "off_when_shutdown" device option
This allows devices to power down when a Klippy shutdown is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 19:42:04 -05:00
Arksine ea1ad0277d update_manager: use a lock to prevent concurrent update and refresh requests
This should reduce the load on low perfomance devices.  This also makes it possible to queue update requests.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 14:58:38 -05:00
Arksine 1e81297624 update_manager: resolve potential rentry issues
Calls to "refresh" should not be allowed to occur while a client a current refresh is in progress.  Updates will wait for a pending refresh to complete before beginning the update procedure.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 09:11:41 -05:00
Arksine ae3661b100 app: Force register moonraker and klippy log endpoints
It is possible for the log files to be registered after a rollover,  which can result in the file not existing.  Force the log endpoints to register, bypassing the existance check.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 06:45:04 -05:00
Arksine 67f5b32d84 file_manager: Increase extract_metadata timeout to 10 seconds
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 06:23:17 -05:00
Arksine 14b5384572 update_manager: retry failed "run_with_response" commands
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 20:52:46 -05:00
Arksine c261ee51f3 shell_command: Add retries to "run_with_response" method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 20:52:46 -05:00
Arksine 67f992dabd file_manager: add disk usage to directory listing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 17:06:33 -05:00
Arksine a535e6e94a paneldue: Improve file name parsing
Previously file names containing whitespace were not parsed correctly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 12:46:31 -05:00
Arksine 4aa2a86e3b docs: Document "notify_klippy_shutdown"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 11:51:52 -05:00
Arksine 7d738c7a8b websockets: add "klippy_shutdown" notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 11:48:31 -05:00
Arksine f753263c60 docs: document the "-n" command line option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 11:47:03 -05:00
Arksine 2f8a1567a8 moonraker: add --nologfile (-n) option to the command line
This allows moonraker to run without generating a log file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 11:28:34 -05:00
Arksine 933622adda docs: Note changes to the file manager path restrictions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-31 20:23:48 -05:00
Arksine 1814a11a8d file_manager: remove restriction that file paths must be in HOME
Instead make sure that the supplied path is not the system root and check that moonraker has the appropriate privileges to access the directory.

Also track visited directories when retreiving a full file list to prevent infinite recursion.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-12-31 19:36:55 -05:00
Arksine 77c483ea0f docs: document changes to the update_manager plugin
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-31 08:25:59 -05:00
Arksine 96941922bc update_manager: move repo specific data to a supplemental config file
This provides the update manager flexibility, such as the ability to define disto specific dependencies.  This also fixes an issue where two updates are necessary to install additional dependencies.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 19:45:20 -05:00
Arksine 1f2c1b3fcd confighelper: implement read_supplemental_config
This allows the config object to read additional config files as requred.  Also implement a "get_options" method that can be used to retrive a dictionary of all options in the current section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 19:45:20 -05:00
Arksine 2953c3f16f update_manager: Use the "klippy_identified" event to update Klippy paths
Only update the Klipper Repo Object if the paths have changed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 19:45:20 -05:00
Arksine 8fc5aab2f0 update_manager: report system package info
Report available package count and a list of available packages.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 19:45:20 -05:00
Arksine 1acb00e2f1 update_manager: only fetch the git remote when necessary
After a repo has been updated fetching the remote is not needed, as it was just done in the prior update step.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine b0fda218f1 update_manager: manage GitHub rate limits
Track rate limit attributes and reject requests when the user IP has reached their limit.  Use conditional API requests to reduce the number of requests that count against the limit.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine 34af0b4bfb shell_command: always log the result of a shell command
Use the return code to help determine if the command successfully finished.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine fad6bc4ad7 update_manager: timeout bug fixes
It shouldn't be necessary to use gen.with_timeout during the fetch with tornado 6.1.  Also fix some potential issues with unbound timeouts variables.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine 9501d72059 update_manager: Don't use github's API to check repo version
The remote version info can be retrieved by simply doing a git fetch, then running "git rev-parse" and "git describe" on the desired remote branch.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine 9993b1e656 update_manager: implement 'enable_repo_debug' option
Allow developers to update a detached git repo.  Note that this option should not be used on production machines.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine b5394228ef shell_command: reset tracking attributes in run()
Clear partial output and cancelled attributes prior to each call of run().  This allows a command to be cleanly run again after a failure.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine 6bf4ef8b00 moonraker: add "klippy_identified" event
This allows Moonraker to update its paths to Klippy immediately upon a successful response from the info endpoint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:16 -05:00
Arksine 0a7080741c app: Register a default file path for klippy.log
This will make klippy.log available in the event that Klippy has not successfully connected, assuming the log is available at the default location.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 07:53:48 -05:00
Arksine 223c125106 app: Don't replace "+" with a space char when deleting a file
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 06:41:27 -05:00
Arksine f9fc679831 moonraker: add shebang to moonraker.py
Also make moonraker.py executable.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-28 20:00:56 -05:00
Arksine 586bb6a7ca docs: document "initial_state" option for the power plugin
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-25 19:31:57 -05:00
Arksine 76ccc8b3e1 power: Add 'initial_state' option for GPIO devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-25 19:31:03 -05:00
Arksine f91e425463 power: fix formatting issues with tasmota impelmentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-25 19:30:21 -05:00
Arksine 46de7c48c8 moonraker: bump env version to 0.2.6
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 19:06:53 -05:00
Arksine 063ef7194a update_manager: fix bug in env dist package update
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 18:33:37 -05:00
Arksine 313357061e moonraker: bump env version to 0.2.5
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 18:29:03 -05:00
Arksine 0f62b283bd update_manager: rebuild the enviroment if a new env version is detected
This should be done even if new dependencies are not required.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 18:10:58 -05:00
Arksine 9f9a05cabb update_manager: symlink dist packages on virtualenv rebuild
This allows for the installation of python "dist-packages" without enabling "system-site-packages" in the virtualenv.  As of the moment moonraker only requires the gpiod dist package.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 17:59:22 -05:00
Arksine 40fbe1abf1 scripts: don't install system site packages in virtualenv
This can create issues of the system includes conflicting packages.  Create a symlink for the system "gpiod" instead.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 15:41:42 -05:00
Arksine 9a309ffd59 file_manager: allow directories in "/etc/moonraker" to be registered
This may be useful for system packaging options that do not wish to put configuration in the home directory.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-20 08:37:45 -05:00
Arksine 684ff07ba2 update_manager: check local git version after an update
Before the service is restarted, check the local version.  This should make sure that the local repo state is reported correctly after an update, regardless of the timing of a status request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-20 06:46:52 -05:00
Arksine 0a7eed2767 update_manager: fix bug in "check_initialized" methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-19 14:05:11 -05:00
Arksine 6898ff8ab6 update_manager: make sure than all updaters are intialized before updating status
It is possible that a status request can occur while an updater is checking intial state.  Use an event to wait on initializing before returning the status request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-19 07:40:23 -05:00
Arksine 653c9190c4 docs: document "complete" field for "notifiy_update_response"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:58:04 -05:00
Arksine cdbaaedc8a test client: log when an update is complete
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:45:51 -05:00
Arksine fa20d106cf update_manager: add "complete" field to update_repsonse notification
This signals to connected clients that the current update in progress has compelted.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:45:51 -05:00
Arksine 40b74cefb5 update_manager: refresh the local git repo state when a status refresh is requested
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:45:51 -05:00
Arksine 20d27b0be6 docs: Add KlipperScreen to list of available clients
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-16 12:39:46 -05:00
Arksine 44bdf708e6 update_manager: correctly handle origins that do not contain a ".git" extension
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-16 11:50:52 -05:00
Arksine 2ddd1966fe file_manager: handle gcode files with special characters
Files with quotation marks and spaces are now acceptable and properly handled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-14 10:21:38 -05:00
Arksine 8bb7139468 websockets: remove refrenced to undefined attribute in websocket handler
This resolves an issue where an unhandled exception is rasied when a websocket attempts to write to a closed websocket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-13 17:05:44 -05:00
Arksine ba4d771d10 paneldue: implement queues for command handling
This implements two queues, one for commands that execute locally and a second
for gcode commands that execute on the Klippy host.  While it is valid for a local
command to execute concurrently with a remote command, commands of the same type
(local or remote) should execute sequentially.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>

Update paneldue.py
2020-12-12 08:35:04 -05:00
Arksine eea2abd60e paneldue: execute commands synchronously
This prevents gcode requests from blocking temperature updates, accessing the file list, etc.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-11 07:28:39 -05:00
Arksine 70501772c1 paneldue: re-initalize if the paneldue disconnects
If 10 seconds passes without an update request, re-initialize the PanelDue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-10 11:31:40 -05:00
Arksine 119b0bf60c paneldue: attempt reconnect if disconnected due to error
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-10 06:29:49 -05:00
Arksine 59e58226ff paneldue: prevent reentry when processing incoming commands
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-10 06:29:49 -05:00
Arksine ec5be560d5 paneldue: update macros on first connection
Report that the PanelDue is "idle" until it is first initialized.  This allows for the Macros to be set upon first connection

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-12-10 06:29:28 -05:00
KwadFan d19e9e2d28 scripts: add update support to sudo_fix.sh
Signed-off-by: Stephan Wendel <me@stephanwe.de>
2020-12-06 07:39:50 -05:00
Arksine abbd02aa73 scripts: minor fixes
Run the legacy install cleanup after Klipper is detected in install-moonraker.sh

Fix whitespace errros in uninstall-moonraker.sh

Signed-ff-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 07:28:11 -05:00
Arksine 1b997b7457 docs: Note changes to install script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 07:05:21 -05:00
Arksine 6dfd3ca915 scripts: install Moonraker as a systemd service
This allows users to view the log using the journalctl command.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 06:54:48 -05:00
Arksine aaa6ec8eb2 utils: add support for logging to stdout
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 06:54:48 -05:00
Arksine aba5bdf339 docs: add clarification
This clarifies the installation and configuration instructions, updating some outdated info.  Also added is a sample moonraker.conf file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-05 19:19:13 -05:00
Eric Callahan 43e2893e01 docs: Note supported version of PanelDue Firmware
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-02 07:46:26 -05:00
KwadFan e025a5ce01 make executable by default
Signed-off-by: Stephan Wendel <me@stephanwe.de>
2020-11-30 14:07:14 -05:00
Arksine 2e44766e1e shell_command: check the return code of the proc for success
Add a "get_return_code" method that allows users to fetch the return code after the shell command has executed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-29 12:12:58 -05:00
KwadFan 77f79fcc20 scripts: add sudo_fix.sh
This script may be used to fix sudo permissions on "custompios" based distributions.

Signed-off-by: Stephan Wendel <me@stephanwe.de>
2020-11-29 07:46:02 -05:00
Arksine 1d0a790ef5 scripts: bump version to 0.2.2
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-29 07:26:04 -05:00
Arksine e2a8a9b49f update_manager: Add 5 minute timeout to env build
This should remove the necessity of waiting after the shell command.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-29 07:14:21 -05:00
Arksine 290be28dae scripts: bump version to 0.2.1
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-29 07:03:07 -05:00
Arksine f488e985ab update_manager: implement ability to rebuild the python env
This implementation adds a delay that allows for pip to function correclty after the venv is built.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-29 06:52:08 -05:00
Arksine 8678e25427 shell_command: return False if an exception is raised
Signed-off- by:  Eric Callahan <arksine.code@gmail.com>
2020-11-29 06:36:34 -05:00
Arksine d41c1c4c00 update_manager: disable python env rebuild
The current method for rebuilding the virtualenv fails. A potential workaround is to do the rebuild and subsequent update with a script.  For now, disable the rebuild.

Signed-off-by:  Eric Callahan <arskine.code@gmail.com>
2020-11-28 07:50:10 -05:00
Arksine 6a13260e67 scripts: add version.txt
Moonraker's update_manager plugin will check this file to see if dependencies or the python enviroment need an update.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-28 07:29:25 -05:00
Arksine 6403eaa0db docs: document "update_manager" plugin
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-28 07:22:09 -05:00
Arksine 4edad1b7a4 test_client: add support for "update_response" notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-27 16:59:29 -05:00
Arksine 21a7a4e530 websockets: Add "update_response" notification
This will send output from "update" commands over the websocket to clients.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-27 16:59:29 -05:00
Arksine d9af161a18 update_manager: initial implementation
This manager can perform updates on moonraker and klipper, assuming that the source is located in a valid git repo, the origin points to the official repo, and the currently selected branch is "master".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-27 16:59:29 -05:00
Arksine 83381446a0 machine: add "/machine/services/restart" endpoint
This makes it possible for clients to hard restart an service in the event it becomes unresponsive.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine 093b8c14d6 shell_command: refactor output parsing
Separate output by line, and execute the output callback once per line.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine 116c1e9f29 shell_command: add run_with_response() method
This method collects the entire response and returns it with the call.  Suitable for commands that produce little output.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine 706d86dd21 file_manager: update paths in "ready" event handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine df81854f89 moonraker: Store info received from initial "info" request to klippy
This allows moonraker plugins to look up the stored info without needing to make an addition "info" request to Klippy.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine b0469da462 moonraker: add software version to system_args
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine 2e9c6de5d0 moonraker: refactor references to cmd_line_args
They are now named "system_args", as they represent system wide arguments.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine f96fb997da docs: document API for retreiving Klipper "docs"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:45 -05:00
Arksine b0f781ec16 file_manager: serve Klipper's "docs" directory
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:17:23 -05:00
Matthias Neumayr 93fd850b63 Added Tasmota SetOption26 to power/Tasmota setup description
Signed-off-by: Matthias Neumayr <matt.neumayr@gmail.com>
2020-11-21 13:59:29 -05:00
Matthias Neumayr a2327a093b Fixed error when reading Tasmota status response
Signed-off-by: Matthias Neumayr <matt.neumayr@gmail.com>
2020-11-21 13:59:29 -05:00
Matthias Neumayr 4415a3c858 Updated documentation with Tasmota power configuration settings and sample
Signed-off-by: Matthias Neumayr <matt.neumayr@gmail.com>
2020-11-21 13:59:29 -05:00
Matthias Neumayr 6ba54d9cb1 Added Tasmota power plugin
Signed-off-by: Matthias Neumayr <matt.neumayr@gmail.com>
2020-11-21 13:59:29 -05:00
Arksine 8d3e185894 docs: fix typo in user_changes.md
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-20 14:36:13 -05:00
Arksine 01a48e530f docs: update documentation for changes to "power" plugin
The power APIs were never properly documented, so this adds them to web_api.md.  In addition, a new "user_changes.md" document has been added to help users transition to the new plugin.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-19 15:43:24 -05:00
Arksine 675fe750f6 test client: log objects received via the "power changed" notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-19 08:42:55 -05:00
Arksine 8ead49504b power: add support for tplink smartplug (Kasa) devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-19 08:32:37 -05:00
Arksine 47c7cea5a5 power: add initial support for device types
This changes the API endpoints from "/machine/gpio_power" to "/machine/device_power".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-19 08:32:37 -05:00
Arksine f6fa093369 power: refactor power requests
Do not allow on, off, or status requests without arguments.    Pass device objects to "power_device()" rather than device names.

Signed-off-by:  Eric Callahan <arkine.code@gmail.com>
2020-11-19 08:32:37 -05:00
Arksine 6738aa8c68 power: Use libgpiod instead of sysfs for gpio management
This resolves issues inherent with sysfs gpio management.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-19 08:32:37 -05:00
Arksine 48266e0bd6 power: rework configuration
Devices are now configured using "prefix" sections.   The pin configuration now more closely mimics that of Klipper's configuration so as to reduce confusion.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine 1975b875a5 confighelper: Add helper methods
Add "get_name()" and "get_prefix_section" methods

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine 0a7b580799 moonraker: handle "prefix" section during inital load
Only load the plugin for each prefix section once.  Plugins themselves will be responsible for parsing the configuration from each prefix section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine d18fc889d5 docs: update installation.md with install script's command line options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine a5e8c290ef scripts: update tornado version in requirements file
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine 8b5ed3c9da scripts: update install script
Add python3-libgpiod dependency.

As this dependency requiress a rebuild of the python3 environment, add some command line options to the install script:
- "-r" will rebuild the virtualenv
- "-f" will force overwite the defaults file.  By default an existing defaults file will not be modified.
- "-c <config_path>" will direct moonraker to use the supplied path for the config file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine de34fee72a machine: register "reboot_machine" and "shutdown_machine" remote methods
This allows Klippy to command moonraker to reboot or shutdown the host machine.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 12:21:16 -05:00
Arksine 346fce177f app: close server connections when closing app
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 06:53:05 -05:00
Arksine 7ca910ec46 authorization: add additional CORS logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 06:52:47 -05:00
Arksine 5081810a96 file_manager: normalize the path for the metadata script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-16 19:55:37 -05:00
Arksine ac1d798a36 authorization: Add wildcards to cors_domians option
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-11-16 07:13:30 -05:00
Arksine 2d2f8bfbcd authorization: fix issue cors issue when an error is detected
Tornado clears the headers when an error is detected, "set_default_headers" must be overrridden so that errors are properly returned.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-14 17:59:08 -05:00
Arksine 7414781b3a docs: update config documentation
The `enable_cors` option has been removed from the [server] config.  CORS is now configured in [authorization] via the `cors_domains` option.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 08:57:10 -05:00
Arksine ea62bc9ed1 app: change enable_cors option to cors_domains
Rather than allow all origins as was the default with "enable_cors", users may not specify the domains allowed.  If "*" is specified, all domains are allowed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 07:27:17 -05:00
Arksine 2cfc5b9501 docs: update metadata documentation
Document the "gcode_start_byte" and "gcode_end_byte" fields.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 06:53:20 -05:00
Arksine 222dda50bc extract_metadata: parse "gcode_start_byte" and "gcode_end_byte"
Determine the byte location of the first and last gcode command (Either Mxxx or Gxxx commands).  This is useful for determining the portion of the file that consists of actual commands.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 06:45:21 -05:00
Arksine b021d10de5 klippy_apis: add quotes around filename in call to SDCARD_PRINT_FILE
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 06:03:19 -05:00
Arksine 6763ea6197 file_manager: correct issue with directories that contain spaces
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 05:25:37 -05:00
Arksine 697be6a822 file_manager: Immedately fetch metadata for file uploads
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-12 17:27:52 -05:00
Arksine a1de70ff89 docs: document "notify_klippy_ready" websocket notfication
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 17:59:08 -05:00
Arksine 6254586a65 test_client: support additional notifications
Add support for "notify_klippy_ready" and "notify_power_changed".

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 17:53:58 -05:00
Arksine 3d827d7513 websockets: Add "notify_klippy_ready" notification
GIven that subscriptions are reset,  connected clients no longer maintained and they cannot check "webhooks.state" to see if Klippy is ready.  This notifcation may be used to in its place.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 17:53:58 -05:00
Arksine 4b2f3a6f5f docs: update API documentation
Document the new server.websocket.id method and update the documentation for the subscription APIs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 11:58:28 -05:00
Arksine 2ba41701e1 test_client: Add connection ID to http requests if available
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 08:32:06 -05:00
Arksine 07c307f4ea moonraker: Only return subscribed items in response to "objects/subscribe"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 08:32:06 -05:00
Arksine daa93b0a2f app: include all arguments in parsers
Clients may provide arguments either in the query string or body.  Reserved arguments "token" and "connection_id" are excluded from the result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 05:37:20 -05:00
Arksine 5836d60d88 app: allow http requests to specifiy a websocket id
Some requests, such "printer/objects/subscribe", require a websocket
for asynchronous updates.  Clients may now specify a "connection_id"
in the form data that identifies an associated websocket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 92d1715d88 app: Simplify request handlers
There is no need to pass the auth, server, or websocket manager objects to request handlers.  They can be retreived directly from the application reference.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 7abc86847e websockets: register server.websocket.id remote method
This allows clients to request the unique ID associated with each connected websocket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine a6913a982a moonraker: manage subscriptions independently for each connection
This allows clients to "unsubscribe"by sending an empty dict.  Each client will receive updates only for subscribed objects.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 8d1239c316 websockets: pass connection to WebRequest
This gives handlers direct access to a websocket client connection.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine de1575f757 power: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 6c8ef93f9f machine: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine a260356d78 klippy_apis: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 27a17ed5a6 file_manager: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 870cabfa05 data_store: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 7cd51fe1eb authorization: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine ac38899d1f moonraker: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine faa415a823 app: Wrap incoming requests in a WebRequest object
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 30c236f1a9 websockets: add WebRequest class
This class encapsulates all request data received from a client.  This simplifies callbacks and makes it easier to add additional parameters to a client request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine b83211e98d paneldue: convert "paneldue_beep" into a coroutine
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:41:26 -05:00
Arksine 6dfab37ef8 moonraker: spawn remote methods on the event loop
This allows regsitered methods to be coroutines.  Execution is done on the event loop to prevent a coroutine from blocking the incoming command queue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:39:53 -05:00
Pawel Zubrycki a0e23eb22a power: make the module more modular
Signed-off-by:  Pawel Zubrycki <paw.zubr@gmail.com>
2020-11-09 06:48:00 -05:00
Arksine 0fada7ffc2 moonraker: add .editorconfig file
Developers may use this to help conform to the repo's basic coding style.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-08 08:50:51 -05:00
Arksine 453745c1b6 file_manager: rename references from "url_path" to "rel_path"
This is a better description of the item parsed from _convert_path() is a path relative to the "root" directory.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-08 07:39:59 -05:00
Arksine 3b63205e70 websockets: Report exception when "TypeError" is caught
Signed-off-by:  Eric Callahan <arksine.coded@gmail.com>
2020-11-08 07:39:37 -05:00
Arksine ffdcfd527a file_manager: clear metadata on item delete or move
When a directory is deleted or moved go ahead and prune the storage.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-08 07:39:36 -05:00
Arksine 472c7c4b23 file_manager: rename all refrences of "base" to "root"
Previously different parts of the file manager referred to name identifying a "root directory" as either base or root.  This could lead to confusion, so all references are now "root".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:36:08 -05:00
Arksine c415f9ee15 file_manager: Don't store file lists
Since we need to walk through a file list each time one is requested there is no gain from storing lists locally.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:36:08 -05:00
Arksine e51dbb45c1 file_manager: refactor the MetadataStorage class
Storage is now updated by individual calls to "parse_metadata()" instead of passing a full list.  This will allow the manager to

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:36:08 -05:00
Arksine e5f3aeca78 docs: document remote method calls
This updates the "PANELDUE_BEEP" gcode macro to use the "paneldue_beep" remote method.  Also included is documentation on the "set_device_power" method added to the power plugin.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:34:56 -05:00
Arksine 59d27e6829 power: register "set_device_power" remote method
This allows device power to be toggled from a klipper gcode macro.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:34:56 -05:00
Arksine 6464bbfc3c paneldue: register "paneldue_beep" remote method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:34:56 -05:00
Arksine ba78a82a26 moonraker: add ability to register remote methods with Klippy
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:34:56 -05:00
Arksine c6d629659b klippy_apis: Add API to register methods with Klippy
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:34:56 -05:00
Arksine 5ff87aa24e docs: Add home assistant example
Example provided courtesy of Github User Kruppes.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-11-06 07:00:01 -05:00
Arksine 8bd6e45303 file_manager: fix bug in _handle_metadata_request()
Don't modify the metadata directly.  Create a copy, then add the "filename" item.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-05 12:43:17 -05:00
Arksine 73cbcb7b7e docs: document "extended" argument for GET directory endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-02 20:18:07 -05:00
Arksine 624be50026 file_manager: add "extended" argument to directory endpoint
If extended==True is passed to GET directory then the result for each gcode file will include associate metadata, if present.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-02 20:18:07 -05:00
Arksine f14b1f3ff0 file_manager: use os.path.splitext to find file extensions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-02 20:18:03 -05:00
Arksine 0c7fa454e9 scripts: add "pillow" python requirement
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-31 08:40:49 -04:00
Arksine aac11a9fb8 extract_metadata: Add support for extracting Cura thumbnails
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-31 08:40:49 -04:00
Arksine 0d515e4938 file_manager: Add support for uploading and extracting ufp files
Credit to GitHub user cdkeito for creating a template from which this implementation was inspired.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-31 08:40:49 -04:00
Jordan Ruthe b63d192df7 power: add websocket notification
Signed-off-by: Jordan Ruthe <jordanruthe@gmail.com>
2020-10-27 18:08:56 -04:00
Arksine d582d76346 docs: Add clarification to printer object description
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-26 21:29:53 -04:00
Arksine 9394bf592c docs: Add documentation for Klipper Printer Objects
This documents the most useful printer objects available for query, providing the fields that a query returns and what the represent.

Also add a basic  "print state monitoring" example and  "bed_mesh" example to web_api.md.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-26 21:25:20 -04:00
Arksine 4919548ef5 test_client: Add button to retreive mesh
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-26 20:29:02 -04:00
th33xitus 374d984ced fix: make installer not fail if klipper is installed as systemd service
If Klipper is installed as systemd service, the script would fail and exit at step 6 (corrected that typo) when trying to stop Klipper via init.d.
Changing the used command to systemctl will be compatible with both init.d and systemd services.

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2020-10-26 14:46:44 -04:00
Arksine 413062f8e8 docs: Update API documentation
The "modified" field returned by all file manager endpoints and notifications now refers to unix time (in seconds).

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-25 19:50:24 -04:00
Arksine 7554a599b4 paneldue: Convert "modifed" attribute of metadata to a string
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-21 17:54:36 -04:00
Arksine dfb1e19948 extract_metadata: store file "modified" time as unix time
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-21 17:53:45 -04:00
Arksine f2fb8d33d4 file_manager: store file "modified" time as unix time
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-21 17:53:08 -04:00
Arksine 2d77400a65 docs: update for latest API additions and changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-21 15:42:03 -04:00
Arksine 8a6503da8a datastore: Add timestamp (in unix time) field to each line in the gcode store
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-18 16:52:08 -04:00
Arksine ab35346f24 moonraker: Add method to retreive host info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-13 07:53:40 -04:00
Arksine 28844cb41d PanelDue: Dump recieved gcode queue on restart
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-11 09:09:17 -04:00
Arksine 8fcccfd46e moonraker: Add "/server/restart" endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-11 09:09:17 -04:00
Arksine f220e1b2ee moonraker: remove stale objects from subscription tracking
This prevents moonraker from subscribing to unknown printer objects on startup.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-10 08:52:44 -04:00
Arksine 346c3ad2a0 PanelDue: Make checksums optional
Some displays which emulate PD firmware do not use checksums.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-08 14:28:15 -04:00
Arksine 7a013a42f7 machine: Use shutdown -r command to reboot
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-05 18:23:58 -04:00
Arksine 264e708c1d file_manager: fix typo in directory check
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-05 18:16:10 -04:00
Arksine 620fb356cc file_manager: Update the internal file list when get_directory is called
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-05 17:57:18 -04:00
Arksine 43d8e181be readme: Add Fluidd to the list of supported clients
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-30 18:08:41 -04:00
Arksine ac648cefcf docs: Add new endpints to API documention
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-30 18:03:25 -04:00
Arksine 7e3f236393 data_store: add "/server/gcode_store" endpoint
Clients may use this API to fetch up to 1000 lines of cached gocde responses.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-28 14:57:44 -04:00
Arksine b8fc6f5130 plugins: rename "temperature_store" plugin to "data_store".
This is in preparation for additional storage functionality.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-28 14:08:40 -04:00
Eric Callahan a578199dab docs: fix incorrect option for API Key file location
Resolves #22.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-28 06:53:45 -04:00
Arksine 8440a10b9e extract_metadata: attempt to parse object height from PrusaSlicer comments
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-26 11:44:18 -04:00
Arksine 756492f349 moonraker: add "/server/info" endpoint
This method provides basic server information, such as loaded plugins and the state of the UDS connection to Klippy.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-26 08:34:05 -04:00
Arksine 6905515f3d shell_command: add ability to cancel a running process
Also adds an indefinite timeout if the timeout is specified as "None".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-26 06:14:35 -04:00
Arksine 3d1faebf15 moonraker: load_plugin() fix
Make sure that the correct config section is loaded when "load_plugin" is called.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-26 06:09:08 -04:00
Arksine d1c0cdf65b docs: Fix incorrect option for klippy_uds_address
Resolves #20.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-16 11:27:20 -04:00
Arksine 36fb1da46d docs: add missing documentation
- Document "enable_cors".  Resolves #18.
- Add a note that Moonraker is not aware of the gcode file path  until Klippy successfully starts.  Resolves #16.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-12 07:48:54 -04:00
Arksine 8b08b03fbf app: add max_upload_size configuration option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-11 06:27:48 -04:00
Arksine 733cf0afac docs: Update metadata API documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-09 11:32:37 -04:00
Arksine 57fe71c800 extract_metadata: parse slicer version during identifcation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-09 08:29:22 -04:00
Arksine ec86c7bfda extract_metadata: optimize regex
Use calls to re.search() in place of re.findall() where appropriate.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-08 17:29:08 -04:00
Arksine ad8680be38 extract_metadata: Add support for IceSL slicer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-08 12:49:42 -04:00
Arksine 805821c928 extract_metadata: extract first layer temperatures
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-08 11:33:10 -04:00
Arksine e38f63254f extract_metadata: extract basic metadata when slicer is unknown
It is possible to extract some metatdata, such as layer height, from bare gcode script.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-08 08:41:09 -04:00
Arksine 97cb072981 docs: Add documentation for "delete_file" websocket API.
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:51:39 -04:00
Arksine 4285ea7348 test client: Add jstree file management support
This allows for easier regression testing of the full file management API.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
Arksine 36c82d0c7f file_manager: simplify directory registration
Now that the file_manager directly  handles DELETE file requests, it is not necessary have the HTTP file handler perform any checks.   Thus it is no longer required to pass a "can_delete" parameter.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
Arksine 2a967303cb test client: add support for websocket file delete
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
Arksine ae49dfe8f2 file_manager: add websocket method for file delete
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
Arksine 7078d5c980 file_manager: update delete_file method
This method is now the primary means of deleting files, as it includes checks to make sure that the delete is allowed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
Arksine 059f5d6a73 app: allow local handlers to select their supported protocol
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
jruthe c523f35c5e Fixing paths on power plugin\
Signed off by: Jordan Ruthe
2020-09-05 14:17:45 -04:00
Arksine c122bd68e0 docs: document API changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 15:26:46 -04:00
Arksine 59277f8b7a test_client: Update websocket APIs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:43:13 -04:00
Arksine 8eaef1e559 power: Refactor APIs
Register APIs in the "machine/gpio_power" namespace.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine 5904c2daf5 temperature_store: Update API registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine 33b965644b machine: Update API registration
Signed-off- by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine 34008569dd klippy_apis: Update API registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine 371c15aa33 file_manager: update API registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine b034485ce8 authorization: update API registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine 76ea4d25a4 app: refactor websocket handler registration
Websocket APIs are now generated using traditional namespaces, for example "printer.gcode.script" rather than "post_printer_gcode_script".   Local endpoints that register multiple requests methods will have the method prefixed (ie:. "server.files.get_directory", "server.files.post_directory", "server.files.delete_directory")

Signed-off-by:  Eric Callahan
2020-09-03 14:01:34 -04:00
Arksine fdec6277eb moonraker: handle Klippy disconnects during initialization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 12:27:13 -04:00
Arksine 2a34986acb file_manager: check for unsuccessful attempt at metadata extraction
If the metadata script encoutners an error it will return an empty dict for the "metadata" item.  Do not update the metadata storage or send a notification if the dict is empty.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-02 17:13:25 -04:00
Arksine d59d1e5f7f docs: document new "notify_metadata_update" notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-01 11:37:06 -04:00
Arksine 28977bd579 moonraker: Don't use a PeriodicCallback for the init routine
The init function blocks, making it reentrant.  Use "call_later" instead.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-01 08:49:52 -04:00
Arksine f9b1e2922d moonraker: speed up intialization procedure
Attempt to reconnect every 250ms when disconnected.  Once connected, attempt to initialize every 250ms.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-01 07:41:53 -04:00
Arksine 960334d087 moonraker: stop the background logger prior to exiting
This allows all records on the queue to be logged before exiting the program.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-31 15:30:30 -04:00
Arksine 005caba234 test_client: log metadata notifications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-30 15:40:56 -04:00
Arksine 2c5bb4710e websockets: Add metadata update notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-30 15:30:38 -04:00
Arksine bcb7e17105 extract_metadata: Set slicer type to "Unknown" if not able to detect
Signed-off-by:  Eric Callahan <akrsine.code@gmail.com>
2020-08-30 15:28:21 -04:00
Arksine 304e861a28 file_manager: refactor metadata extraction
Move logic for managine metadata to its own class.  Allow 3 retries if extraction fails, and send a printer event if metadata is updated due to an added file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-30 15:28:21 -04:00
Arksine 16269c1a49 temperature_store: correctly handle subscribed diffs
When processing a status update, default the temperature and target to the last received value.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-29 14:12:23 -04:00
Arksine 9613bb01de extract_metadata: include "days" when calculating time for PrusaSlicer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-28 14:26:08 -04:00
Arksine 5b87c43535 moonraker: send "client_info" after initial connection to Klippy
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-26 07:34:29 -04:00
Arksine d021eddb16 docs: Fix typo in readme
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-22 20:47:56 -04:00
Arksine 1aa12e4ff1 utils: Add support for a QueueLogger
Logging to a file has the potential to block a the main thread, a QueueLogger resolves this by forwarding logging request to a secondary thread.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-19 10:59:07 -04:00
Arksine 55919fc7d3 docs: update the PANELDUE_BEEP macro documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-18 08:59:32 -04:00
Arksine f338bccc3b paneldue: Add support for the piezo buzzer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-18 08:48:57 -04:00
Arksine 5a6f1ae062 websockets: don't handle ServerError in local callbacks
They can propogate back to the JSONRPC.execute_method() where they will be correctly handled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-17 20:16:03 -04:00
Arksine 8b02797ede test client: use 'gcode_move' in place of 'gcode'
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-17 19:56:42 -04:00
Arksine 2848b4e9c1 paneldue: 'gcode' status is now in 'gcode_move'
Also toolhead.status is no longer available, use idle_timeout.state.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-17 19:55:53 -04:00
Arksine 88bbd66a3b docs: document latest API changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 19:58:15 -04:00
Arksine a17e1d4056 test client: support "disconnect" notification
The webhooks module may now be used to retreive "ready" and "shutdown" state

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine 279d53afde moonraker: rework klippy state events
Emit specific events for each klippy state rather than one for all of them.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine 56bd9a61ea moonraker: reorganize initialization
This optimized version should initialize faster as it doesn't rely on an additional Periodic Callback when Klippy is detected as ready.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine 76493215c5 moonraker: move klippy connection logic to its own class
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine a3c0f06c5f docs: Update API documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine f9f70ce989 test client: Update for compatibility with Klippy API changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine 8840434c7c paneldue: use klippy_apis module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine 6fb4cdca62 termperature_store: use klippy_apis module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-15 14:19:19 -04:00
Arksine 4a57dba586 moonraker: update protocol for data received from klippy
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-15 14:19:19 -04:00
Arksine 291f2b0e91 klippy_apis: new module replacing deprecated "gcode_apis"
Like gcode_apis, the klippy_apis module registers Web API aliases for particular gcodes.  In addition, this module presents an interface where moonraker can call Klippy APIs directly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-15 14:19:19 -04:00
Arksine 43b057c40c moonraker: klippy requests no longer take a "request method"
Klippy rpc methods now accept either GET or POST, the method will be executed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-15 08:38:06 -04:00
Arksine 5b6d4371c8 moonraker: convert missed legacy strings to f-strings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-13 19:23:17 -04:00
Arksine e9cd86f468 docs: add "confirmed_macros" option to paneldue documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-12 17:53:17 -04:00
Arksine 7cae2f4aac paneldue: add confirmation box option to macros
This allows users to specify a "confirmed_macros" that wil pop up a message box requiring confirmation before proceeding.  Useful for restart and firmware_restart to prevent accidental execution.

Also do not raise an exception when Klippy disconnects after a restart or firmware_restart.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-12 17:25:54 -04:00
Arksine a7147a44ca moonraker: refactor "make_request"
The make_request() method is now awaitable and returns the result directly vs the previous behavior of returning a request that was awaited.

There is no longer a need to check the result to see if it is an error, exceptions are raised if an error is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-12 08:43:37 -04:00
Arksine d04a419a80 docs: Update documentation for 0.1 release
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 21:27:41 -04:00
Arksine e78a2e3e41 gcode_apis: handle restart exceptions
It is expected that the Klippy will disconnect when a restart request is sent.  Handle those exceptions so they return an acknowledgement.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 20:50:58 -04:00
Arksine 2c332a968f file_manager: require base paths be located within home directory
They however cannot be the home directory.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 20:34:20 -04:00
Arksine b3f02a73a4 extract_metadata: Improve error reporting
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:28:59 -04:00
Arksine 1d520310ac utils: update git describe arguments
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:28:59 -04:00
Arksine 7cd22804dd moonraker: replace legacy string interpolation with f-strings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:28:41 -04:00
Arksine de1a79a7ca docs: update API documentation regarding file list notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:21:28 -04:00
Arksine 82fbee2bc0 test client: Update to handle new file list notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:21:27 -04:00
Arksine 7441da4b57 file_manager: refactor notify_filelist_changed()
This brings more consistency to the notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:21:27 -04:00
Arksine 6dc43f7e12 moonraker: replace "check_available" with "check_available_objects"
There "check_available" endpoint no longer exists in Klippy, so use "objects/list" instead.  If Klippy is not properly configured Moonraker will log the result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 0775f3d0c6 moonraker: Connect to Klippy as a client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine e1addb16fd utils: remove unused SocketLoggingHandler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 62e5f85473 moonraker: use tornado's iostream wrapper for klippy connection
This reduces the amount of code needed to handle the connection and adds more robust error handling.   This also prepares moonraker for the eventual transition of Klippy hosting the server socket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine b92000dd46 moonraker: Use file_manager to update mutable endpoints
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine a4638f6c21 moonraker: Improve connection error logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 0abfc76871 temperature_store: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 470cc13b0e shell_command: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 6b45c0c1d8 power: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine f114985dc6 paneldue: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 52907155d2 machine: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 5853f3f447 gcode_apis: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:27 -04:00
Arksine 98b3c990e0 file_manager: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:27 -04:00
Arksine e5cb27f5b7 authorization: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:27 -04:00
Arksine de462b1d0f app: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:27 -04:00
Arksine 7a94fb3a6b moonraker: Add configparser support
Rather than receive its configuration from Klippy, moonraker will receive its configuration from a config file.  By default this file is located at ~/moonraker.conf.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:27 -04:00
Arksine e2850ee77e paneldue: fix incorrect default baudrate
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 21:10:30 -04:00
Arksine 9c76875896 file_manager: use print_stats to determine if an operation is safe
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 14:02:06 -04:00
Arksine d19737f4c5 moonraker: don't timeout requests to Klippy
Klippy requests typically only timeout when the connection between Klippy and the Server is disconnected.  Rather returning a timeout, send an error if there are any pending requests when a disconnection is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine d235139e6b paneldue: use the new "print_stats" module to check printing state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine 4f97ebb28d test_client: Update to use new "print_stats" module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine f082d4dd44 paneldue: Update to fetch status from Klipper's print_stats object
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine 89fa9ba47e gcode_apis: update "print start" API to use SDCARD_PRINT_FILE gcode
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
83 changed files with 30791 additions and 4380 deletions

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# Editorconfig file for moonraker repo, courtesy of @trevjonez
root = true
[*]
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
[*.py]
max_line_length = 80
+51
View File
@@ -0,0 +1,51 @@
# CI Code for generating and publishing beta assets
name: publish_assets
on:
release:
types: [published]
jobs:
generate_assets:
runs-on: ubuntu-latest
steps:
- name: Checkout Moonraker
uses: actions/checkout@v2
with:
fetch-depth: 0
ref: ${{ github.ref }}
path: moonraker
- name: Checkout Klipper
uses: actions/checkout@v2
with:
fetch-depth: 0
repository: KevinOConnor/klipper
path: klipper
- name: Build Beta Assets
if: ${{ github.event.release.prerelease }}
run: >
./moonraker/scripts/build-zip-release.sh -b
-o ${{ github.workspace }}
-k ${{ github.workspace }}/klipper
- name: Build Stable Assets
if: ${{ !github.event.release.prerelease }}
run: >
./moonraker/scripts/build-zip-release.sh
-o ${{ github.workspace }}
-k ${{ github.workspace }}/klipper
- name: Upload assets
run: |
cd moonraker
gh release upload ${{ env.TAG }} ${{ env.FILES }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
FILES: >
${{ github.workspace }}/moonraker.zip
${{ github.workspace }}/klipper.zip
${{ github.workspace }}/RELEASE_INFO
${{ github.workspace }}/COMMIT_LOG
TAG: ${{ github.event.release.tag_name }}
+20
View File
@@ -0,0 +1,20 @@
# CI for code style and application tests
name: test-code
on: [push, pull_request]
jobs:
lint-python-code:
runs-on: ubuntu-18.04
steps:
- uses: actions/checkout@v1
- uses: ricardochaves/python-lint@v1.4.0
with:
python-root-list: "moonraker scripts"
use-pylint: false
use-pycodestyle: true
use-flake8: false
use-black: false
use-mypy: true
use-isort: false
extra-pycodestyle-options: "--ignore=E226,E301,E302,E303,W503,W504 --max-line-length=80 --max-doc-length=80"
extra-mypy-options: "--ignore-missing-imports --follow-imports=silent"
+4
View File
@@ -0,0 +1,4 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
+10
View File
@@ -0,0 +1,10 @@
version: 2
mkdocs:
configuration: mkdocs.yml
fail_on_warning: false
python:
version: 3.8
install:
- requirements: docs/doc-requirements.txt
+26 -5
View File
@@ -1,9 +1,30 @@
# Moonraker - API Web Server for Klipper
Moonraker is a Python 3 based web server that exposes APIs with which
client applications may use interact with Klipper. Communcation between
the Klippy host and Moonraker is done over a Unix Domain Socket.
client applications may use to interact with
[Klipper](https://github.com/KevinOConnor/klipper). Communcation between
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
is used to provide Moonraker's server functionality.
Moonraker depends on Tornado for its server functionality. Moonraker
does not come bundled with a client, you will need to install one,
such as [Mainsail](https://github.com/meteyou/mainsail).
Documentation for users and developers can be found on
[Read the Docs](https://moonraker.readthedocs.io/en/latest/).
Note that Moonraker does not come bundled with a client, you will need to
install one. The following clients are currently available:
- [Mainsail](https://github.com/meteyou/mainsail) by Meteyou
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
- [KlipperScreen](https://github.com/jordanruthe/KlipperScreen) by jordanruthe
- [mooncord](https://github.com/eliteSchwein/mooncord) by eliteSchwein
### Changes
This section contains changelogs that users and developers may reference
to see if any action is necessary on their part. The date of the most
recent change is included.
Users:\
[user_changes.md](https://moonraker.readthedocs.io/en/latest/user_changes/) - April 19th 2021
Developers:\
[api_changes.md](https://moonraker.readthedocs.io/en/latest/api_changes/) - March 15th 2021
+368
View File
@@ -0,0 +1,368 @@
##
This document keeps a record of all changes to Moonraker's web APIs.
### May 8th 2021
- The `file_manager` has been refactored to support system file
file events through `inotify`. Only mutable `roots` are monitored,
(currently `gcodes` and `config`). Subfolders within these
these roots are also monitored, however hidden folders are not.
The following changes API changes have been made to acccommodate
this functionality:
- The `notify_filelist_changed` actions have changed. The new
actions are as follows:
- `create_file`: sent when a new file has been created. This
includes file uploads and copied files.
- `create_dir`: sent when a new directory has been created.
- `delete_file`: sent when a file has been deleted.
- `delete_dir`: sent when a directory has been deleted.
- `move_file`: sent when a file has moved.
- `move_dir`: sent when a directory has moved.
- `modify_file`: sent when an existing file has been modified
- `root_update`: sent when a root directory location has been set.
For example, if a user changes the gcode path in Klipper, this
action is sent with a `notify_filelist_changed` notification.
- File list notifications for gcode files are now only sent after
all metadata has been processed. Likewise, requests to copy,
move, or upload a file will only return after metadata has been
processed. Notifications are synced with requests so that the
request should always return before the notification is sent.
- Thumbnails are now stored in the `.thumbs` directory to prevent
changes to thumbnails from emitting filelist notications. This
change will be reflected in the metadata's `relative_path` field,
so clients that use this field should not need to take additional
action. Note that existing thumbnails will remain in the `thumbs`
directory and filelist notifications will be sent for changes to
these thumbnails.
- The `notify_metadata_update` notification has been removed Clients
- can reliably expect metadata to be available for new or moved gcode
files when a request returns.
- The return values for several endpoints have been updated. They
now contain information similar to that which is pushed by the
`notify_filelist_changed` notification.
- The deprecated `data` field in gcode metadata has been removed.
The `size` field now returns the size of the `.png` file.
### March 15th 2021
- The `data` field for gcode thumbnails is now deprecated and will
be removed in the near future. Thumbnails are now saved to png
files in a `thumbs` directory relative to a gcode file's location.
This path is available in the `relative_path` field for each
thumbnail entry in the metadata.
### January 31st 2021
- The `GET /server/temperature_store` endpoint now only returns fields
that each sensor reports. For example, if a particuarly temperature
sensor does not report "target" or "power", then the corresponding
fields will not be reported for that sensor in response to the
`temperature_store` request.
### January 22nd 2021
- The `POST /machine/update/client` endpoint now requires a `name`
argument. This change added multiple client support
- The response to `GET /machine/update/status` no longer returns a
`client` field. Instead it will add fields matching the `name` of
each configured client. Keep in mind that the client object could
have a different set of fields depending on the type of a client. The
easy way to check for this is to see if a `branch` field is present.
If so, this client is a `git repo`. Otherwise it is a `web` client.
### January 4th 2021
- A `notify_update_refreshed` notification has been added. Moonraker now
auto-refreshes the update status at roughly a 2 hour interval. When
an auto-refresh is complete this notification is broadcast. Included
is an object that matches the response from `/machine/update/status`.
- The behavior of some of the `update_manager` APIs has changed:
- The `refresh` argument for `/machine/update/status` is now more
of a suggestion than a rule. If an update or a print is in
progress then the request will ignore the refresh argument
and immediately return the current status. Generally speaking requesting
a refresh should not be necessary with addition of auto refresh.
- The update requests (ie `/machine/update/klipper`) will now return
an error if a print is in progress. If the requested update is in
progress then the request will return valid with a message stating
that the update is in progress. If another object is being updated
then the request will be queued and block until it its complete.
### January 1st 2021
- A `notify_klippy_shutdown` websocket notification has been added
### December 30th 2020
- Some additional fields are now reported in the response to
`GET /machine/update/status`.
### November 28th 2020
- The following new endpoints are available when the `[update_manager]`
section has been configured:
- `GET /machine/update/status`
- `POST /machine/update/moonraker`
- `POST /machine/update/klipper`
- `POST /machine/update/client`
- `POST /machine/update/system`
- The following endpoint has been added and is available as part of the
core API:
- `POST /machine/services/restart`
See [web_api.md](web_api.md) for details on these new endpoints.
### November 23rd 2020
- Moonraker now serves Klipper's "docs" directory. This can be access
at `GET /server/files/docs/<filename>`.
### November 19th 2020
- The path for the power APIs has changed from `gpio_power` to `device_power`:
- `GET /machine/device_power/devices`\
`{"jsonrpc":"2.0","method":"machine.device_power.devices","id":"1"}`\
Returns an array of objects listing all detected devices.
Each object in the array is guaranteed to have the following
fields:
- `device`: The device name
- `status`: May be "init", "on", "off", or "error"
- `type`: May be "gpio" or "tplink_smartplug"
- `GET /machine/device_power/status?dev_name`\
`{"jsonrpc":"2.0","method":"machine.device_power.status","id":"1",
"params":{"dev_name":null}}`\
It is no longer possible to call this method with no arguments.
Status will only be returned for the requested device, to get
status of all devices use `/machine/device_power/devices`. As
before, this returns an object in the format of
`{device_name: status}`, where device_name is the name of the device
and `status` is the devices current status.
- `POST /machine/device_power/on?dev_name`\
`{"jsonrpc":"2.0","method":"machine.device_power.on","id":"1",
"params":{"dev_name":null}}`\
Toggles device on. Returns the current status of the device.
- `POST /machine/device_power/off?dev_name`\
`{"jsonrpc":"2.0","method":"machine.device_power.off","id":"1",
"params":{"dev_name":null}}`\
Toggles device off. Returns the current status of the device.
- The `notify_power_changed` notification now includes an object
containing device info, matching that which would be recieved
from a single item in `/machine/power/devices`.
### November 12th 2020
- Two new fields have been added to the gcode metadata:
- `gcode_start_byte`: Indicates the byte position in the
file where the first "Gxx" or "Mxx" command is detected.
- `gcode_end_byte`: Indicates the byte position in the
file where the last "Gxx" or "Mxx" command is detected.
These fields may be used to more accurately predict print
progress based on the file size.
### November 11th 2020
- The `server.websocket.id` API has been added. This returns a
unique ID that Moonraker uses to track each client connection.
As such, this API is only available over the websocket, there
is no complementary HTTP request.
- All HTTP API request may now include arguments in either the
query string or in the request's body.
- Subscriptions are now managed on a per connection basis. Each
connection will only recieve updates for objects in which they
are currently subscribed. If an "empty" request is sent, the
subscription will be cancelled.
- The `POST /printer/object/subscribe` now requires a
`connection_id` argument. This is used to identify which
connection's associated subscription should be updated.
Currenlty subscriptions are only supported over the a
websocket connection, one may use the id received from
`server.websocket.id`.
- The `notify_klippy_ready` websocket notification has been
added.
### November 2nd 2020
- The `GET /server/files/directory` endpoint now accepts a new
optional argument, `extended`. If `extended=true`, then
the data returned for gcode files will also include extracted
metadata if it exists.
### October 25th 2020
- The `modified` field reported for files and directories is no
longer represented as a string. It is now a floating point
value representing unix time (in seconds). This can be used
to display the "last modified date" based on the client's
timezone.
### October 21st 2020
- The `/server/gcode_store` endpoint no longer returns a string
in the result's `gcode_store` field. It now returns an
Array of objects, each object containing `message` and `time`
fields. The time refers to a timestamp in unix time (seconds),
and may be used to determine when the gcode store received the
accompanying `message`.
### September 30th 2020
- Two new endpoints have been added:
- `GET /server/info` (`server.info`)
- `GET /server/gcode_store` (`server.gcode_store`)
See web_api.md for details on their usage.
### September 7th 2020
- A new websocket API has been added, `server.files.delete_file`:
```
{jsonrpc: "2.0", method: "server.files.delete_file", params:
{path: "<root>/<file_name>"}, id: <request id>}
```
Where <root> is either "gcodes" or "config", and <file_name> is
the relative path to the file for deletion. For example:
`path: "gcodes/my_sub_dir/my_gcode_file.gcode"`
### September 3rd 2020
- The Websocket APIs have changed for clarity. The APIs methods now
use namespaces similar to those found in common programming languages.
This change affects all websocket APIs, however websocket events have
not changed. Below is a chart mapping the Previous API to the New API:
| Previous Websocket Method | New Websocket Method |
|---------------------------|----------------------|
| get_printer_info | printer.info |
| post_printer_emergency_stop | printer.emergency_stop |
| post_printer_restart | printer.restart |
| post_printer_firmware_restart | printer.firmware_restart |
| get_printer_objects_list | printer.objects.list |
| get_printer_objects_query | printer.objects.query |
| post_printer_objects_subscribe | printer.objects.subscribe |
| get_printer_query_endstops_status | printer.query_endstops.status |
| post_printer_gcode_script | printer.gcode.script |
| get_printer_gcode_help | printer.gcode.help |
| post_printer_print_start | printer.print.start |
| post_printer_print_pause | printer.print.pause |
| post_printer_print_resume | printer.print.resume |
| post_printer_print_cancel | printer.print.cancel |
| post_machine_reboot | machine.reboot |
| post_machine_shutdown | machine.shutdown |
| get_server_temperature_store | server.temperature_store |
| get_file_list | server.files.list |
| get_file_metadata | server.files.metadata |
| get_directory | server.files.get_directory |
| post_directory | server.files.post_directory |
| delete_directory | server.files.delete_directory |
| post_file_move | server.files.move |
| post_file_copy | server.files.copy |
- The "power" plugin APIs have changed. This affects both HTTP and
Websocket APIs. They were originally added to the "/printer" path,
however this adds the possibility of a naming conflict. The new
APIs are as follows:
- `GET /machine/gpio_power/devices` : `machine.gpio_power.devices`
- `GET /machine/gpio_power/status` : `machine.gpio_power.status`
- `POST /machine/gpio_power/on` : `machine.gpio_power.on`
- `POST /machine/gpio_power/off` : `machine.gpio_power.off`
### September 1st 2020
- A new notification has been added: `notify_metdata_update`. This
notification is sent when Moonraker parses metdata from a new upload.
Note that the upload must be made via the API, files manually (using
SAMBA, SCP, etc) do not trigger a notification. The notification is
sent in the following format:
```
{jsonrpc: "2.0", method: "notify_metadata_update", params: [metadata]}
```
Where `metadata` is an object in the following format:
```json
{
filename: "file name",
size: <file size>,
modified: "last modified date",
slicer: "Slicer Name",
first_layer_height: <in mm>,
layer_height: <in mm>,
object_height: <in mm>,
estimated_time: <time in seconds>,
filament_total: <in mm>,
thumbnails: [
{
width: <in pixels>,
height: <in pixels>,
size: <length of string>,
data: <base64 string>
}, ...
]
}
```
### August 16th 2020
- The structure of data returned from `/printer/info` (`get_printer_info`)
has changed to the following format:
```json
{
state: "<klippy state>",
state_message: "<current state message>",
hostname: "<hostname>",
software_version: "<version>",
cpu_info: "<cpu_info>",
klipper_path: "<moonraker use only>",
python_path: "<moonraker use only>",
log_file: "<moonraker use only>",
config_file: "<moonraker use only>",
}
```
The "state" item can be one of the following:
- "startup" - Klippy is in the process of starting up
- "ready" - Klippy is ready
- "shutdown" - Klippy has shutdown
- "error" - Klippy has experienced an error during startup
The message from each state can be found in the `state_message`.
- A `webhooks` printer object has been added, available for subscription or
query. It includes the following items:
- `state` - Printer state identical to that returned from `/printer/info`
- `state_message` - identical to that returned from `/printer/info`
- `/printer/objects/status` (`get_printer_objects_status`) has been renamed to
`/printer/objects/query` (`get_printer_objects_query`). The format of the
websocket request has changed, it should now look like the following:
```json
{
jsonrpc: "2.0",
method: "get_printer_objects_query",
params: {
objects: {
gcode: null,
toolhead: ["position", "status"]
}
},
id: <request id>
}
```
As shown above, printer objects are now wrapped in an "objects" parameter.
When a client wishes to subscribe to all items of a printer object, they
should now be set to `null` rather than an empty array.
The return value has also changed:
```json
{
eventtime: <klippy time of update>,
status: {
gcode: {
busy: true,
gcode_position: [0, 0, 0 ,0],
...},
toolhead: {
position: [0, 0, 0, 0],
status: "Ready",
...},
...}
}
```
The `status` item now contains the requested status.
- `/printer/objects/subscription` (`post_printer_objects_subscription`) is now
`printer/objects/subscribe` (`post_printer_objects_subscribe`). This
request takes parameters in the same format as the `query`. It now returns
state for all currently subscribed objects (in the same format as a `query`).
This data can be used to initialize all local state after the request
completes.
- Subscriptions are now pushed as "diffs". Clients will only recieve updates
for subscribed items when that data changes. This requires that clients
initialize their local state with the data returned from the subscription
request.
- The structure of data returned from `/printer/objects/list` has changed. It
now returns an array of available printer objects:
```json
{ objects: ["gcode", "toolhead", "bed_mesh", "configfile",....]}
```
- The `notify_klippy_state_changed` notification has been removed. Clients
can subscribe to `webhooks` and use `webhooks.state` to be notified of
transitions to the "ready" and "shutdown" states
- A `notify_klippy_disconnected` event has been added to notify clients
when the connection between Klippy and Moonraker has been terminated.
This event is sent with no parameters:
```json
{jsonrpc: "2.0", method: "notify_klippy_disconnected"}
```
+365
View File
@@ -0,0 +1,365 @@
## Components
Components in Moonraker are used to extend Moonraker's functionality,
similar to "extras" in Klipper. Moonraker divides components into
two categories, "core" components and "optional" components. A core
component gets its configuration from the `[server]` section and is
loaded when Moonraker starts. For example, the `file_manager` is a
core component. If a core component fails to load Moonraker will
exit with an error.
Optional components must be configured in `moonraker.conf`. If they
have no specific configuration, a bare section, such as `[octoprint_compat]`
must be present in `moonraker.conf`. Unlike with core components,
Moonraker will still start if an optional component fails to load.
Its failed status will be available for clients to query and present
to the user.
### Basic Example
Components exist in the `components` directory. The below example
shows how an `example.py` component might look:
```python
# Example Component
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
class Example:
def __init__(self, config):
self.server = config.get_server()
self.name = config.get_name()
# Raises an error if "example_int_option" is not configured in
# the [example] section
self.example_int_opt = config.getint("example_int_option")
# Returns a NoneType if "example_float_option is not configured
# in the config
self.example_float_opt = config.getfloat("example_float_option", None)
self.server.register_endpoint("/server/example", ['GET'],
self._handle_example request)
async def request_some_klippy_state(self):
klippy_apis = self.server.lookup_component('klippy_apis')
return await klippy_apis.query_objects({'print_stats': None})
async def _handle_example_request(self, web_request):
web_request.get_int("required_reqest_param")
web_request.get_float("optional_request_param", None)
state = await self.request_some_klippy_state()
return {"example_return_value": state}
def load_component(config):
return Example(config)
```
If you have created a "Klippy extras" module then the above should look
look familiar. Moonraker attempts to use similar method for adding
extensions, making easier Klipper contributors to add new functionality
to Moonraker. Be aware that there is no "Reactor" object in Moonraker,
it uses `asyncio` for coroutines. Like Klippy, you should not write
code that blocks the main thread.
### The ConfigHelper Object
As shown above, each component is passed a config object. This object
will be a `ConfigHelper` type, which is an object that wraps a
configuration section to simply access to the native `ConfigParser`.
A `ConfigHelper` should never be directly instantiated.
#### *ConfigHelper.get_server()*
Returns the primary [server](#the-server-object) instance.
#### *ConfigHelper.get_name()*
Returns the configuration section name associated with this `ConfigHelper`.
#### *ConfigHelper.get(option_name, default=Sentinel)*
Returns the value of the option`option_name` as a string. If
the option does not exist, returns `default`. If `default` is
not provided raises a `ConfigError`.
#### *ConfigHelper.getint(option_name, default=Sentinel)*
Returns the value of the option`option_name` as an integer. If
the option does not exist, returns `default`. If `default` is
not provided raises a `ConfigError`.
#### *ConfigHelper.getfloat(option_name, default=Sentinel)*
Returns the value of the option`option_name` as a float. If
the option does not exist, returns `default`. If `default` is
not provided raises a `ConfigError`.
#### *ConfigHelper.getboolean(option_name, default=Sentinel)*
Returns the value of the option`option_name` as a boolean. If
the option does not exist, returns `default`. If `default` is
not provided raises a `ConfigError`.
#### *ConfigHelper.has_section(section_name)*
Returns True if a section matching `section_name` is in the configuration,
otherwise False.
Note that a ConfigHelper object also implements `__contains__`,
which is an alias for `has_section`, ie: `section_name in config_instance`
#### *ConfigHelper.getsection(section_name)*
Returns a Config object for the section matching `section_name`. If the
section does not exist in the configuration raises a `ConfigError`.
Note that a ConfigHelper object also implements `__getitem__`,
which is an alias for `get_section`, ie: `config_instance[section_name]`
#### *ConfigHelper.get_options()*
Returns a dict mapping options to values for all options in the Config
object.
#### *ConfigHelper.get_prefix_sections(prefix)*
Returns a list section names in the configuration that start with `prefix`.
These strings can be used to retreve ConfigHelpers via
[get_section()](#confighelpergetsectionsection_name).
### The Server Object
The server instance represents the central management object in Moonraker.
It can be used to register endpoints, register notifications, look up other
components, send events, and more.
#### *Server.lookup_component(component_name, default=Sentinel)*
Attempts to look up a loaded component, returning the result. If
the component has not been loaded, `default` will be returned.
If `default` is not provided a `ServerError` will be raised.
#### *Server.load_component(config, component_name, default=Sentinel)*
Attempts to load an uninitialized component and returns the result. It is
only valid to call this within a a component's `__init__()` method, and
should only be necessary if one optional component relies on another. Core components will always be loaded before optional components, thus an optional
component may always call
[lookup_component()](#serverlookup_componentcomponent_name-defaultsentinel)
when it needs a reference to core component.
If the component fails to load `default` will be returned. If `default`
is not provided a `ServerError` will be raised.
#### *Server.register_endpoint(uri, request_methods, callback, transports=["http", "websocket", "mqtt"], wrap_result=True)*
Registers the supplied `uri` with the server.
The `request_methods` argument should be a list of strings containing any
combination of `GET`, `POST`, and `DELETE`.
The `callback` is executed when a request matching the `uri` and a
`request_method` is received. The callback function will be passed a
`WebRequest` object with details about the request. This function
should be able of handling each registered `request_method`. The
provided callback must be a coroutine.
The `transports` argument is a list containing any combination of
`http`, `websocket` and `mqtt`. JSON-RPC methods for `websocket` and `mqtt`
will be generated based on what is supplied by the `uri` and
request_methods` argument. A unique JSON_RPC method is generated for each
request method. For example:
```python
self.server.register_endpoint("/server/example", ["POST"], self._handle_request)
```
would register a JSON-RPC method like:
```
server.example
```
However, if multiple requests methods are supplied, the generated JSON-RPC
methods will differ:
```python
self.server.register_endpoint("/server/example", ["GET", "POST", "DELETE"],
self._handle_request)
```
would register:
```
server.get_example
server.post_example
server.delete_example
```
The `wrap_result` argument applies only to the `http` protocol. In Moonraker
all http requests return a result with a JSON body. By default, the value returned
by a `callback` is wrapped in a dict:
```python
{"result": return_value}
```
It is only necessary to set this to false if you need to return a body that
does not match this result. For example, the `[octoprint_compat]` component
uses this functionality to return results in a format that match what
Octoprint itself would return.
#### *Server.register_event_handler(event, callback)*
Registers the provided `callback` method to be executed when the
provided `event` is sent. The callback may be a coroutine, however it
is not required.
#### *Server.send_event(event, \*args)*
Emits the event named `event`, calling all callbacks registered to the
event. All positional arguments in `*args` will be passed to each
callback. Event names should be in the form of
`"module_name:event_description"`.
#### *Server.register_notification(event_name, notify_name=None)*
Registers a websocket notification to be pushed when `event_name`
is emitted. By default JSON-RPC notifcation sent will be in the form of
`notify_{event_description}`. For example, when the server sends the
`server:klippy_connected` event, the JSON_RPC notification will be
`notify_klippy_connected`.
If a `notify_name` is provided it will override the `{event_description}`
extracted from the `event_name`. For example, if the `notify_name="kconnect`
were specfied when registering the `server:klippy_connected` event, the
websocket would emit a `notify_kconnect` notification.
#### *Server.get_host_info()*
Returns a tuple of the current host name of the PC and the port Moonraker
is serving on.
#### *Server.get_klippy_info()*
Returns a dict containing the values from the most recent `info` request to
Klippy. If Klippy has never connected this will be an empty dict.
### The WebRequest Object
All callbacks registered with the
[register_endpoint()](#serverregister_endpointuri-request_methods-callback-protocolhttp-websocket-wrap_resulttrue)
method are passed a WebRequest object when they are executed. This object
contains information about the request including its endpoint name and arguments
parsed from the request.
#### *WebRequest.get_endpoint()*
Returns the URI registered with this request, ie: `/server/example`.
#### *WebRequest.get_action()*
Returns the request action, which is synonomous with its HTTP request
method. Will be either `GET`, `POST`, or `DELETE`. This is useful
if your endpoint was registered with multiple request methods and
needs to handle each differently.
#### *WebRequest.get_connection()*
Returns the associated Websocket connection ID. This will be `None`
for HTTP requests when no associated websocket is connected to
the client.
#### *WebRequest.get_args()*
Returns a reference to the entire argument dictionary. Useful if
one request handler needs to preprocess the arguments before
passing the WebRequest on to another request handler.
#### *WebRequest.get(key, default=Sentinel)*
Returns the request argument at the provided `key`. If the key is not
present `default` will be returned. If `default` is not provided a
`ServerError` will be raised.
#### *WebRequest.get_str(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to a string, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `ServerError` will be raised.
#### *WebRequest.get_int(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to an integer, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `ServerError` will be raised.
#### *WebRequest.get_float(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to a float, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `ServerError` will be raised.
#### *WebRequest.get_boolean(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to a boolean, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `ServerError` will be raised.
### MQTT
If configured by the user the MQTT component is available for lookup.
Developers may use this to subscribe and publish topics.
#### *MQTTClient.is_connected()*
Returns true if Moonraker is currently connected to the Broker, false
otherwise.
#### *MQTTClient.wait_connection(timeout=None)*
Blocks until a connection with the broker has been successfully established
or until the specified timeout has exceeded. Returns true if the connection
was successful established, or False on timeout. If no timeout is specified
then this method will block indefinitely until a connection has been
established.
#### *MQTTClient.publish_topic(topic, payload=None, qos=None, retain=False)*
Attempts to publish a topic to the Broker. The `payload` may be a bool, int,
float, string, or json encodable (Dict or List). If omitted then an empty
payload is sent. The `qos` may be an integer from 0 to 2. If not specifed
then the QOS level will use the configured default. If `retain` is set to
`True` then the retain flag for the payload will be set.
Returns a Future that will block until topic is confirmed as published.
For QOS level 0 an exception will be raised if the broker is not connected.
#### *MQTTClient.publish_topic_with_response(topic, response_topic, payload=None, qos=None, retain=False, timeout=None)*
Publishes the supplied `topic` with the arguments specified by `payload`,
`qos`, and `retain`, then subscribes to the `response_topic`. The payload
delivered by the response topic is returned. Note that this method is
a coroutine, it must always be awaited. The call will block until the
entire process has completed unless a `timeout` (in seconds) is specifed.
The `timeout` is applied to both the attempt to publish and the pending
response, so the maximum waiting time would be approximately 2*timeout.
!!! warning
This should only be used when it is guaranteed that the `response_topic`
does not have a retained value. Otherwise the returned response will
be the retained value.
#### *MQTTClient.subscribe_topic(topic, callback, qos=None)*
Subscibes to the supplied `topic` with the specified `qos`. If `qos` is not
supplied the configured default will be used. The `callback` should be a
callable that accepts a `payload` argument of a `bytes` type. The callable
may be a coroutine. The callback will be run each time the subscribed topic
is published by another client.
Returns a `SubscriptionHandle` that may be used to unsubscribe the topic.
#### *MQTTClinet.unsubscribe(hdl)*
Unsubscribes the callback associated with `hdl`. If no outstanding callbacks
exist for the topic then the topic is unsubscribed from the broker.
+557
View File
@@ -0,0 +1,557 @@
#
This document describes Moonraker's full configuration. As this file
references configuration for both Klipper (`printer.cfg`) and Moonraker
(`moonraker.conf`), each example contains a commment indicating which
configuration file is being refrenenced. A basic
[sample configuration](./moonraker.conf) in the `docs` directory.
## `[server]`
The `[server]` section provides essential configuration for Moonraker
and its core components. This section is requrired.
```ini
# moonraker.conf
[server]
host: 0.0.0.0
# The host address in which to bind the HTTP server. Default is to bind
# to all interfaces
port: 7125
# The port the HTTP server will listen on. Default is 7125
ssl_port: 7130
# The port to listen on for SSS (HTTPS) connections. Note that the HTTPS
# server will only be started of the certificate and key options outlined
# below are provied. The default is 7130.
ssl_certificate_path:
# The path to a self signed ssl certificate. The default is no path, which
# disables HTTPS.
ssl_key_path:
# The path to the private key used to signed the certificate. The default
# is no path, which disables HTTPS.
klippy_uds_address: /tmp/klippy_uds
# The address of Unix Domain Socket used to communicate with Klippy. Default
# is /tmp/klippy_uds
max_upload_size: 1024
# The maximum size allowed for a file upload (in MiB). Default is 1024 MiB.
enable_debug_logging: False
# When set to True Moonraker will log in verbose mode. During this stage
# of development the default is False.
config_path:
# The path to a directory where configuration files are located. This
# directory may contain Klipper config files (printer.cfg) or Moonraker
# config files (moonraker.conf). Clients may also write their own config
# files to this directory. Note that this may not be the system root
# (ie: "/") and moonraker must have read and write access permissions
# for this directory.
database_path: ~/.moonraker_database
# The path to the folder that stores Moonraker's lmdb database files.
# It is NOT recommended to place this file in a location that is served by
# Moonraker (such as the "config_path" or the location where gcode
# files are stored). If the folder does not exist an attempt will be made
# to create it. The default is ~/.moonraker_database.
log_path:
# An optional path to a directory where log files are located. Users may
# configure various applications to store logs here and Moonraker will serve
# them at "/server/files/logs/*". The default is no log paths.
enable_database_debug: False
# For developer use only. End users should leave this option set to False.
temperature_store_size: 1200
# The maximum number of temperature values to store for each sensor. Note
# that this value also applies to the "target", "power", and "fan_speed"
# if the sensor reports them. The default is 1200, which is enough to
# store approximately 20 minutes of data at one value per second.
gcode_store_size: 1000
# The maximum number "gcode lines" to store. The default is 1000.
```
## `[authorization]`
The `[authorization]` section provides configuration for Moonraker's
authorization module.
```ini
# moonraker.conf
[authorization]
login_timeout:
# The time, in days, after which a user is forced to re-enter their
# credentials to log in. This period begins when a logged out user
# first logs in. Successive logins without logging out will not
# renew the timeout. The default is 90 days.
trusted_clients:
192.168.1.30
192.168.1.0/24
my-printer.lan
# A list of newline separated ip addresses, ip ranges, or fully qualified
# domain names that are trusted. Trusted clients are given full access to
# the API. Both IPv4 and IPv6 addresses and ranges are supported. Ranges
# must be expressed in CIDR notation (see http://ip.sb/cidr for more info).
# For example, an entry of 192.168.1.0/24 will authorize IPs in the range of
# 192.168.1.1 - 192.168.1.254. Note that when specifying IPv4 ranges the
# last segment of the ip address must be 0. The default is no clients are
# trusted.
cors_domains:
http://klipper-printer.local
http://second-printer.local:7125
# Enables CORS for the specified domains. One may specify * if they wish
# to allow all domains, however this should be an option reserved for
# client developers and not used in production. A * can also be used
# to specify a wildcard that matches several domains. For example:
# *.local
# http://*.my-domain.com
# *.my-domain.com:*
# Are all valid entries. However, a wildcard may not be specified in
# the top level domain:
# http://my-printer.*
# The above example will be rejected.
# When CORS is enabled by adding an entry to this option, all origins
# matching the "trusted_clients" option will have CORS headers set as
# well. If this option is not specified then CORS is disabled.
force_logins: False
# When set to True a user login is required for authorization if at least
# one user has been created, overriding the "trusted_clients" configuration.
# If no users have been created then trusted client checks will apply.
# The default is False.
```
## `[octoprint_compat]`
Enables partial support of Octoprint API is implemented with the purpose of
allowing uploading of sliced prints to a moonraker instance.
Currently we support Slic3r derivatives and Cura with Cura-Octoprint.
```ini
# moonraker.conf
[octoprint_compat]
```
## `[history]`
Enables print history tracking.
```ini
# moonraker.conf
[history]
```
## `[paneldue]`
Enables PanelDue display support. The PanelDue should be connected to the
host machine, either via the machine's UART GPIOs or through a USB-TTL
converter. Currently PanelDue Firmware Version 1.24 is supported. Other
releases may not behave correctly.
```ini
# moonraker.conf
[paneldue]
serial:
# The serial port in which the PanelDue is connected. This parameter
# must be provided.
baud: 57600
# The baud rate to connect at. The default is 57600 baud.
machine_name: Klipper
# An optional unique machine name which displays on the PanelDue's
# Header. The default is "Klipper".
macros:
LOAD_FILAMENT
UNLOAD_FILAMENT
PANELDUE_BEEP FREQUENCY=500 DURATION=1
# A list of newline separated "macros" that are displayed in the
# PanelDue's "macros" tab. These can be gcode macros or simple
# gcodes. A macro may contain parameters. The default is no
# macros will be displayed by the PanelDue.
confirmed_macros:
RESTART
FIRMWARE_RESTART
# Like the "macros" option, this list is added to the macros tab.
# When one of these macros is excuted the PanelDue will prompt
# the user with a confirmation dialog. The default is to include
# RESTART and FIRMWARE_RESTART.
```
Most options above are self explanatory. The "macros" option can be used
to specify commands (either built in or gcode_macros) that will show up
in the PanelDue's "macro" menu.
Note that buzzing the piezo requires the following gcode_macro in `printer.cfg`:
```ini
# printer.cfg
[gcode_macro PANELDUE_BEEP]
# Beep frequency
default_parameter_FREQUENCY: 300
# Beep duration in seconds
default_parameter_DURATION: 1.
gcode:
{action_call_remote_method("paneldue_beep",
frequency=FREQUENCY|int,
duration=DURATION|float)}
```
## `[power]`
Enables device power control. Currently GPIO (relays), TPLink Smartplug,
and Tasmota (via http) devices, HomeAssistant switch are supported.
```ini
# moonraker.conf
[power device_name]
type: gpio
# The type of device. Can be either gpio, tplink_smartplug, tasmota
# shelly, homeseer, homeassistant, or loxonev1.
# This parameter must be provided.
off_when_shutdown: False
# If set to True the device will be powered off when Klipper enters
# the "shutdown" state. This option applies to all device types.
# The default is False.
locked_while_printing: False
# If True, locks the device so that the power cannot be changed while the
# printer is printing. This is useful to avert an accidental shutdown to
# the printer's power. The default is False.
restart_klipper_when_powered: False
# If set to True, Moonraker will issue a "FIRMWARE_RESTART" to Klipper
# after the device has been powered on. The default is False, thus no
# attempt to made to restart Klipper after power on.
restart_delay: 1.
# If "restart_klipper_when_powered" is set, this option specifies the amount
# of time (in seconds) to delay the restart. Default is 1 second.
pin: gpiochip0/gpio26
# The pin to use for GPIO devices. The chip is optional, if left out
# then the module will default to gpiochip0. If one wishes to invert
# the signal, a "!" may be prefixed to the pin. Valid examples:
# gpiochip0/gpio26
# gpio26
# !gpiochip0/gpio26
# !gpio26
# This parameter must be provided for "gpio" type devices
initial_state: off
# The initial state for GPIO type devices. May be on or
# off. When moonraker starts the device will be set to this
# state. Default is off.
address:
port:
# The above options are used for "tplink_smartplug" devices. The
# address should be a valid ip or hostname for the tplink device.
# The port should be the port the device is configured to use.
# "Power Strips" can be controlled by including the socket index
# in the ip address. For example, to control socket index 1:
# 192.168.1.127/1
# The address must be provided. The port defaults to 9999.
address:
password:
output_id:
timer:
# The above options are used for "tasmota" devices. The
# address should be a valid ip or hostname for the tasmota device.
# Provide a password if configured in Tasmota (default is empty).
# Provided an output_id (relay id) if the Tasmota device supports
# more than one (default is 1).
# If your single-relay Tasmota device switches on/off successfully,
# but fails to report its state, ensure that 'SetOption26' is set in
# Tasmota.
address:
user:
password:
output_id:
timer:
# The above options are used for "shelly" devices. The
# address should be a valid ip or hostname for the Shelly device.
# Provide a user and password if configured in Shelly (default is empty).
# If password is set but user is empty the default user "admin" will be used
# Provided an output_id (relay id) if the Shelly device supports
# more than one (default is 0). When timer option is used to delay the turn
# off make sure to set the state to "on" in action call_remote_method.
# So we send a command to turn it on for x sec when its already on then
# it turns off.
address:
device:
user:
password:
# The above options are used for "homeseer" devices. The
# address should be a valid ip or hostname for the homeseer controller.
# "device" should be the ID of the device to control.
# To find out the ID, in the HomeSeer UI, click on the device you want to
# control (Make sure to click the sub-device that actually has On/Off
# buttons). And then go to the "status/graphics" tab and it should list
# "ID" in the "advanced information" section.
# Provide a user and password with access to "device control"
# and at least the specific device you want to control
address:
port:
device:
token:
domain:
# The above options are used for "homeassistant" devices. The
# address should be a valid ip or hostname for the homeassistant controller.
# "device" should be the ID of the switch to control.
# "domain" is the class of device set managed by homeassistant, defaults to "switch".
address:
user:
password:
output_id:
# The above options are used for "loxone smart home miniserver v1 " devices.
# The address should be a valid ip or hostname for the loxone miniserver v1
# device. All entries must be configured in advance in the loxone config.
# Provide a user and password configured in loxone config.
# The output_id is the name of a programmed output, virtual input or virtual
# output in the loxone config his output_id (name) may only be used once in
# the loxone config
```
Below are some potential examples:
```ini
# moonraker.conf
[power printer]
type: gpio
pin: gpio26
off_when_shutdown: True
initial_state: off
[power printer_led]
type: gpio
pin: !gpiochip0/gpio16
initial_state: off
[power light_strip]
type: gpio
pin: gpiochip0/gpio17
initial_state: on
[power wifi_switch]
type: tplink_smartplug
address: 192.168.1.123
[power tasmota_plug]
type: tasmota
address: 192.168.1.124
password: password1
[power shelly_plug]
type: shelly
address: 192.168.1.125
user: user2
password: password2
[power homeassistant_switch]
type: homeassistant
address: 192.168.1.126
port: 8123
device: switch.1234567890abcdefghij
token: home-assistant-very-long-token
domain: switch
```
It is possible to toggle device power from the Klippy host, this can be done
with a gcode_macro, such as:
```ini
# printer.cfg
[gcode_macro POWER_OFF_PRINTER]
gcode:
{action_call_remote_method("set_device_power",
device="printer",
state="off")}
```
The `POWER_OFF_PRINTER` gcode can be run to turn off the "printer" device.
This could be used in conjunction with Klipper's idle timeout to turn the
printer off when idle with a configuration similar to that of below:
```ini
# printer.cfg
[delayed_gcode delayed_printer_off]
initial_duration: 0.
gcode:
{% if printer.idle_timeout.state == "Idle" %}
POWER_OFF_PRINTER
{% endif %}
[idle_timeout]
gcode:
M84
TURN_OFF_HEATERS
UPDATE_DELAYED_GCODE ID=delayed_printer_off DURATION=60
```
## `[update_manager]`
This enables moonraker's update manager. Note that updates can only be
performed on pristine git repos. Repos that have been modified on
disk or cloned from unofficial sources are not supported.
```ini
# moonraker.conf
[update_manager]
enable_repo_debug: False
# When set to True moonraker will bypass repo validation and allow
# updates from unofficial remotes and/or branches. Updates on
# detached repos are also allowed. This option is intended for
# developers and should not be used on production machines. The
# default is False.
enable_auto_refresh: False
# When set to True Moonraker will attempt to fetch status about
# available updates roughly every 24 hours, between 12am-4am.
# When set to False Moonraker will only fetch update state on startup
# and clients will need to request that Moonraker updates state. The
# default is False.
enable_system_updates: True
# A boolean value that can be used to toggle system package updates.
# Currently Moonraker only supports updating packages via APT, so
# this option is useful for users that wish to experiment with linux
# distros that use other package management applications, or users
# that prefer to manage their packages directly. Note that if this
# is set to False users will be need to make sure that all system
# dependencies are up to date. The default is True.
channel: dev
# The update channel applied to Klipper and Moonraker. May be 'dev'
# which will fetch updates using git, or 'beta' which will fetch
# zipped beta releases. Note that this channel does not apply to
# client updates, a client's update channel is determined by its
# 'type' option. When this option is changed the next "update" will
# swap channels, any untracked files in the application's path will be
# removed during this process. The default is dev.
```
### Client Configuration
This allows client programs such as Fluidd, KlipperScreen, and Mainsail to be
updated in addition to klipper, moonraker, and the system os. Repos that have
been modified or cloned from unofficial sources are not supported.
There are two types of update manager clients and each will be detailed
separately. The first one is targeted towards releases that do not need a
service restart such as Fluidd/Mainsail.
```ini
# moonraker.conf
[update_manager client_name]
type: web
# Indicates that this is a web client.
repo:
# This is the GitHub repo of the client, in the format of user/client.
# For example, this could be set to cadriel/fluidd to update Fluidd or
# meteyou/mainsail to update Mainsail. This parameter must be provided.
path:
# The path to the client's files on disk. This parameter must be provided.
persistent_files:
# A list of newline separated file names that should persist between
# updates. This is useful for static configuration files, or perhaps
# themes. The default is no persistent files.
```
This second example is for "applications". These may be git repositories
or zipped distributions.
Note that git repos must have at least one tag for Moonraker
to identify its version.
```ini
# moonraker.conf
# service_name must be the name of the systemd service
[update_manager service_name]
type: git_repo
# Can be git_repo, zip, or zip_beta. See your the client's documentation
# for recommendations on which value to use. Generally a git_repo is
# an applications "dev" channel, zip_beta is its "beta" channel, and zip
# is its "stable" channel. This parameter must be provided.
path:
# The absolute path to the client's files on disk. This parameter must be
# provided.
# Example:
# path: ~/service_name
origin:
# The full git URL of the "origin" remote for the repository. This can
# be be viewed by navigating to your repository and running:
# git remote -v
# This parameter must be provided.
primary_branch:
# The name of the primary branch used for release code on this repo. This
# option allows clients to specify 'main', or their own unique name, as
# the branch used for repo validity checks. The default is master.
env:
# The path to the client's virtual environment executable on disk. For
# example, Moonraker's venv is located at ~/moonraker-env/bin/python.
# The default is no env, which disables updating python packages.
requirements:
# This is the location in the repository to the client's virtual environment
# requirements file. This location is relative to the root of the repository.
# This parameter must be provided if the "env" option is set, otherwise it
# should be omitted.
install_script:
# The file location, relative to the repository, for the installation script.
# The update manager parses this file for "system" packages that need updating.
# The default is no install script, which disables system package updates
enable_node_updates:
# When set to True, Moonraker will asssume that this repo relies upon node
# and will attempt to execute "npm ci --only=prod" when it detects a change
# to package-lock.json. Note that if your project does not have a
# package-lock.json in its root directory then the plugin will fail to load.
# Default is False.
host_repo:
# The GitHub repo in which zipped releases are hosted. Note that this does
# not need to match the repository in the "origin" option, as it is possible
# to use a central GitHub repository to host multiple client builds. As
# an example, Moonraker's repo hosts builds for both Moonraker and Klipper.
# This option defaults to the repo extracted from the "origin" option,
# however if the origin is not hosted on GitHub then this parameter must
# be provided.
```
## `[mqtt]`
Enables an MQTT Client. When configured most of Moonraker's APIs are availble
by publishing JSON-RPC requests to `{instance_name}/moonraker/api/request`.
Responses will be published to `{instance_name}/moonraker/api/response`. See
the [API Documentation](web_api.md#json-rpc-api-overview) for details on
on JSON-RPC.
It is also possible for other components within Moonraker to use MQTT to
publish and subscribe to topics.
```ini
[mqtt]
address:
# Address of the Broker. This may be a hostname or IP Address. This
# parameter must be provided.
port:
# Port the Broker is listening on. Default is 1883.
username:
# An optional username used to log in to the Broker. Default is no
# username (an anonymous login will be attempted)
password_file:
# An optional path to a text file containing a password used to log in
# to the broker. It is strongly recommended that this file be located
# in a folder not served by Moonraker. It is also recommended that the
# password be unique and not used for other logins, as it is stored in
# plain text. To create a password file, one may ssh in to the device
# and enter the following commands:
# cd ~
# echo mypassword > .mqttpass
# Then set this option to:
# ~/.mqttpass
# If this option is omitted no password will be used to login.
mqtt_protocol: v3.1.1
# The protocol to use when connecting to the Broker. May be v3.1,
# v3.1.1, and v5. The default is v3.1.1
enable_moonraker_api: True
# If set to true the MQTT client will subscribe to API topic, ie:
# {instance_name}/moonraker/api/request
# This can be set to False if the user does not wish to allow API
# requests over MQTT. The default is True.
instance_name:
# An identifer used to create unique API topics for each instance of
# Moonraker on network. This name cannot contain wildcards (+ or #).
# For example, if the instance name is set to my_printer, Moonraker
# will subscribe to the following topic for API requests:
# my_printer/moonraker/api/request
# Responses will be published to the following topic:
# my_printer/moonraker/api/response
# The default is the machine's hostname.
default_qos: 0
# The default QOS level used when publishing or subscribing to topics.
# Must be an integer value from 0 to 2. The default is 0.
api_qos:
# The QOS level to use for the API topics. If not provided, the
# value specified by "default_qos" will be used.
```
+67 -16
View File
@@ -8,24 +8,75 @@ are near those of Klipper:
- All source files should begin with a copyright notice in the following
format:
```
# Module name and brief description of module
#
# Copyright (C) 2020 YOUR NAME <YOUR EMAIL ADDRESS>
#
# This file may be distributed under the terms of the GNU GPLv3 license
```
- No line in the source code or documentation should exceed 80 characters.
Be sure there is no trailing whitespace.
# Module name and brief description of module
#
# Copyright (C) 2021 YOUR NAME <YOUR EMAIL ADDRESS>
#
# This file may be distributed under the terms of the GNU GPLv3 license
- No line in the source code should exceed 80 characters. Be sure there is no
trailing whitespace. To validate code before submission one may use `pycodestyle`
with the following options:
- `--ignore=E226,E301,E302,E303,W503,W504`
- `--max-line-length=80`
- `--max-doc-length=80`
- Generally speaking, each line in submitted documentation should also be no
longer than 80 characters, however there are situations where this isn't
possible, such as long hyperlinks or example return values.
- Python code should be fully annotated. Moonraker uses the `mypy` static
type checker for code validation with the following options:
- `--ignore-missing-imports`
- `--follow-imports=silent`
- Each Commit message should be in the following format:
```
module name: brief description of commit
More detailed explanation if necessary.
module name: brief description of commit
More detailed explanation if necessary.
Signed-off-by: Your Name <your email address>
Signed-off-by: Your Name <your email address>
```
- By signing off on commits, you acknowledge that you agree to the
[developer certificate of origin](developer-certificate-of-origin).
As with Klipper, this must contain your real name and a current
[developer certificate of origin](../developer-certificate-of-origin)
shown below. Your signature must contain your real name and a current
email address.
```text
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
+56
View File
@@ -1,3 +1,59 @@
### Moonraker Version 0.1 - August 11 2020
- It is no longer possible to configure the subscription timer. All subscribed
objects will update at an interval of 250ms.
- Request timeout configuration has been removed. The server will no longer
apply a timeout to requests. Any requests pending when Klippy disconnects
will be aborted with an error. All pending requests are logged each minute.
- The RESET_SD gcode is now SDCARD_RESET_FILE
- The "virtual_sdcard" object has removed the following items:
- "filename"
- "total_duration"
- "print_duration"
- "filament_used"
- A new object, "print_stats", has been added. It reports the following items:
- "filename"
- "total_duration"
- "print_duration"
- "filament_used"
- "state" - can be one of the following:
- "standby" - sd print not in progress
- "printing" - print in progress
- "paused" - print paused
- "error" - print experienced an error
- "complete" - print complete
- "message" - contains error message when state is "error"
- The behavior of print_stats is slightly different. When a print is finished the stats are
not cleared. They will remain populated with the final data until the user issues a
SDCARD_RESET_FILE gcode.
- Moonraker Configuration has moved to moonraker.conf
- Klippy now hosts the Unix Domain Socket. As a result, the order in which the
Klipper and Moonraker services are started no longer matters.
- The `notify_filelist_changed` event has been refactored for clarity. It now
returns a result in the following format:
```json
{
action: "<action>",
item: {
path: "<file or directory path>",
root: "<root_name>",
size: <file size>,
modified: "<date modified>"
},
source_item: {
path: "<file or directory path>",
root: "<root_name>"
}
}
```
Note that the `source_item` is only present for `move_item` and `copy_item`
actions. Below is a list of all available actions:
- `upload_file`
- `delete_file`
- `create_dir`
- `delete_dir`
- `move_item`
- `copy_item`
### Moonraker Version .08-alpha - 7/2/2020
- Moonraker has moved to its own repo.
- Python 3 support has been added.
+1
View File
@@ -0,0 +1 @@
mkdocs==1.2.1
+52
View File
@@ -0,0 +1,52 @@
# Example Home Assistant configuration file for a Voron V0.
# Credit to GitHub user @Kruppes
#
sensor:
- platform: rest
name: Voron_V0_sensor
resource: "http://192.168.178.56:7125/printer/objects/query?heater_bed&extruder&print_stats&toolhead&display_status&virtual_sdcard"
json_attributes_path: "$.result.status"
json_attributes:
- heater_bed
- extruder
- print_stats
- toolhead
- display_status
- virtual_sdcard
value_template: 'OK'
- platform: template
sensors:
vzero_hotend_target:
friendly_name: 'V0.126 Hotend Target'
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["target"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
vzero_hotend_actual:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["temperature"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
vzero_bed_target:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["target"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
vzero_bed_actual:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["temperature"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
vzero_state:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["state"]}}'
vzero_current_print:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["filename"]}}'
vzero_current_progress:
value_template: '{{ (states.sensor.voron_v0_sensor.attributes["display_status"]["progress"])*100 | round(1) }}'
unit_of_measurement: '%'
vzero_print_time:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"] |timestamp_custom("%H:%M:%S", 0)}}'
vzero_time_remaining:
value_template: '{{ (((states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]/states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]- states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]) if states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]>0 else 0)) | timestamp_custom("%H:%M:%S", 0)}}'
vzero_eta:
value_template: '{{ (as_timestamp(now())+2*60*60+((states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]/states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]- states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]) if states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]>0 else 0)) | timestamp_custom("%H:%M:%S", 0)}}'
vzero_nozzletemp:
value_template: '{{[( states.sensor.voron_v0_sensor.attributes["extruder"]["temperature"] | float | round(1)| string)," / ",( states.sensor.voron_v0_sensor.attributes["extruder"]["target"] | float | round(1)| string)]|join}}'
vzero_bedtemp:
value_template: '{{[( states.sensor.voron_v0_sensor.attributes["heater_bed"]["temperature"] | float | round(1)| string)," / ",( states.sensor.voron_v0_sensor.attributes["heater_bed"]["target"] | float | round(1)| string)]|join}}'
+15
View File
@@ -0,0 +1,15 @@
# Welcome to Moonraker Documentation
Users should refer to the [Installation](installation.md) and
[Configuration](configuration.md) sections for documentation on how
to install and configure Moonraker.
Client developers may refer to the [Client API](web_api.md)
documentation.
Backend developers should refer to the
[contibuting](contributing.md) section for basic contribution
guidelines prior to creating a pull request. The
[components](components.md) document provides a brief overview
of how to create a component and interact with Moonraker's
primary internal APIs.
+165 -195
View File
@@ -6,241 +6,211 @@ may work, however they may need a custom install script. Moonraker
requires Python 3.7 or greater, verify that your distribution's
Python 3 packages meet this requirement.
### Installing Klipper
Klipper should be installed prior to installing Moonraker. Please see
[Klipper's Documention](https://github.com/KevinOConnor/klipper/blob/master/docs/Installation.md)
for instructions on how to do this.
[Klipper's Documention](https://klipper3d.com/Overview.html) for details.
After installing Klipper you should make sure to add Moonraker's
[configuration requirements](#klipper-configuration-requirements).
Moonraker is still in alpha development, and thus some of its dependencies
in Klipper have yet to be merged. Until this has been done it will be
necessary to add a remote and work off a developmental branch of Klipper
to correctly run Moonraker.
### Klipper Configuration Requirements
```
cd ~/klipper
git remote add arksine https://github.com/Arksine/klipper.git
Moonraker depends on the following Klippy extras for full functionality:
- `[virtual_sdcard]`
- `[pause_resume]`
- `[display_status]`
If you have a `[filament_switch_sensor]` configured then `[pause_resume]` will
automatically be loaded. Likewise, if you have a `[display]` configured then
`[display_status]` will be automatically loaded. If your configuration is
missing one or both, you can simply add the bare sections to `printer.cfg`:
```ini
[pause_resume]
[display_status]
[virtual_sdcard]
path: ~/gcode_files
```
Now fetch and checkout:
```
git fetch arksine
git checkout arksine/dev-moonraker-testing
```
Note that you are now in a detached head state and you cannot pull. Any
time you want to update to the latest version of this branch you must
repeat the two commands above.
### Enabling the Unix Socket
For reference, if you want to switch back to the clone of the official repo:
After Klipper is installed it may be necessary to modify its `defaults` file in
order to enable the Unix Domain Socket. Begin by opening the file in your
editor of choice, for example:
```
git checkout master
sudo nano /etc/default/klipper
```
Note that the above command is NOT part of the Moonraker install procedure.
You should see a file that looks something like the following:
```
# Configuration for /etc/init.d/klipper
KLIPPY_USER=pi
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log"
```
Add `-a /tmp/klippy_uds` to KLIPPY_ARGS:
```
# Configuration for /etc/init.d/klipper
KLIPPY_USER=pi
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
```
!!! note
Your installation of Klipper may use systemd instead of
the default LSB script. In this case, you need to modify the
klipper.service file.
You may also want to take this opportunity to change the location of
printer.cfg to match Moonraker's `config_path` option (see the
[configuration document](configuration.md#primary-configuration)
for more information on the config_path). For example, if the `config_path`
is set to `~/printer_config`, your klipper defaults file might look
like the following:
```
# Configuration for /etc/init.d/klipper
KLIPPY_USER=pi
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer_config/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
```
If necessary, create the config directory and move printer.cfg to it:
```
cd ~
mkdir printer_config
mv printer.cfg printer_config
```
### Installing Moonraker
Begin by cloning the git respository:
You can now install the Moonraker application:
```
cd ~
git clone https://github.com/Arksine/moonraker.git
```
If you have an older version of moonraker installed, it must be removed:
```
cd ~/moonraker/scripts
./uninstall-moonraker.sh
```
Now is a good time to create [moonraker.conf](configuration.md). If you are
using the `config_path`, create it in the specified directory otherwise create
it in the HOME directory. The [sample moonraker.conf](./moonraker.conf) in
the `docs` directory may be used as a starting point.
Finally, run moonraker's install script:
For a default installation run the following commands:
```
cd ~/moonraker/scripts
./install-moonraker.sh
```
Or to install with `moonraker.conf` in the `config_path`:
```
cd ~/moonraker/scripts
./install-moonraker.sh -f -c /home/pi/printer_config/moonraker.conf
```
The install script has a few command line options that may be useful,
particularly for those upgrading:
- `-r`:
Rebuilds the virtual environment for existing installations.
Sometimes this is necessary when a dependency has been added.
- `-f`:
Force an overwrite of Moonraker's systemd script. By default the
the systemd script will not be modified if it exists.
- `-c /home/pi/moonraker.conf`:
Specifies the path to Moonraker's config file. The default location
is `/home/<user>/moonraker.conf`. When using this option to modify
an existing installation it is necessary to add `-f` as well.
When the script completes it should start both Moonraker and Klipper. In
`klippy.log` you should find the following entry:\
`Moonraker: server connection detected`
`/tmp/klippy.log` you should find the following entry:
Currently Moonraker is responsible for creating the Unix Domain Socket,
so so it must be started first for Klippy to connect. In any instance
where Klipper was started first simply restart the klipper service.
```
sudo service klipper restart
```
After the connection is established Klippy will register API endpoints and
send configuration to the server. Once the initial configuration is sent
to Moonraker its configuration will be retained when Klippy disconnects
(either through a restart or by stopping the service), and updated when
Klippy reconnects.
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`
# Configuration
The host, port, log file location, socket file location and api key file
are all specified via command arguments:
Now you may install a client, such as
[Mainsail](https://github.com/meteyou/mainsail) or
[Fluidd](https://github.com/cadriel/fluidd)
### Command line usage
This section is intended for users that need to write their own
installation script. Detailed are the command line arguments
available to Moonraker:
```
usage: moonraker.py [-h] [-a <address>] [-p <port>] [-s <socketfile>]
[-l <logfile>] [-k <apikeyfile>]
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>] [-n]
Moonraker - Klipper API Server
optional arguments:
-h, --help show this help message and exit
-a <address>, --address <address>
host name or ip to bind to the Web Server
-p <port>, --port <port>
port the Web Server will listen on
-s <socketfile>, --socketfile <socketfile>
file name and location for the Unix Domain Socket
-c <configfile>, --configfile <configfile>
Location of moonraker configuration file
-l <logfile>, --logfile <logfile>
log file name and location
-k <apikeyfile>, --apikey <apikeyfile>
API Key file location
-n, --nologfile disable logging to a file
```
The default configuration is:
- address = 0.0.0.0 (Bind to all interfaces)
- port = 7125
- socketfile = /tmp/moonraker
- logfile = /tmp/moonraker.log
- apikeyfile = ~/.moonraker_api_key
- config file path- `~/moonraker.conf`
- log file path - `/tmp/moonraker.log`
- logging to a file is enabled
It is recommended to use the defaults, however one may change these
arguments by editing `/etc/default/moonraker`.
All other configuration is sent to the server via Klippy, thus it is done in
printer.cfg. A basic configuration that authorizes clients on a range from
192.168.1.1 - 192.168.1.254 is as follows:
If one needs to start moonraker without generating a log file, the
`-n` option may be used, for example:
```
[moonraker]
trusted_clients:
192.168.1.0/24
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -n -c /path/to/moonraker.conf
```
In general it is not recommended to install moonraker with this option.
While moonraker will still log to stdout, all requests for support must
be accompanied by moonraker.log.
These options may be changed by editing
`/etc/systemd/system/moonraker.service`. The `install-moonraker.sh` script
may also be used to modify the config file location.
### Retreiving the API Key
Some clients may require an API Key to connect to Moonraker. After the
`[authorization]` component is first configured Moonraker will automatically
generate an API Key. There are two ways in which the key may be retreived
by the user:
Retreive the API Key via the command line (SSH):
```
cd ~/moonraker/scripts
./fetch-apikey.sh
```
Below is a detailed explanation of all options currently available:
```
#[moonraker]
#require_auth: True
# Enables Authorization. When set to true, only trusted clients and
# requests with an API key are accepted.
#enable_cors: False
# Enables CORS support. If serving static files from a different http
# server then CORS will need to be enabled.
#trusted_clients:
# A list of new line separated ip addresses and/or ip ranges that are trusted.
# Trusted clients are given full access to the API. Both IPv4 and IPv6
# addresses and ranges are supported. Ranges must be expressed in CIDR
# notation (see http://ip.sb/cidr for more info). For example an entry of
# 192.168.1.0/24 will authorize IPs in the range of 192.168.1.1 -
# 192.168.1.254. Note that when specifying IPv4 ranges the last segment
# of the ip address must be 0.
# The default is no clients or ranges are trusted.
#request_timeout: 5.
# The amount of time (in seconds) a client request has to process before the
# server returns an error. This timeout does NOT apply to gcode requests.
# Default is 5 seconds.
#long_running_gcodes:
# BED_MESH_CALIBRATE, 120.
# M104, 200.
# A list of gcodes that will be assigned their own timeout. The list should
# be in the format presented above, where the first item is the gcode name
# and the second item is the timeout (in seconds). Each pair should be
# separated by a newline. The default is an empty list where no gcodes have
# a unique timeout.
#long_running_requests:
# gcode/script, 60.
# pause_resume/pause, 60.
# pause_resume/resume, 60.
# pause_resume/cancel, 60.
# A list of requests that will be assigned their own timeout. The list
# should be formatted in the same manner as long_running_gcodes. The
# default is matches the example shown above.
#status_tier_1:
# toolhead
# gcode
#status_tier_2:
# fan
#status_tier_3:
# extruder
# virtual_sdcard
# Subscription Configuration. By default items in tier 1 are polled every
# 250 ms, tier 2 every 500 ms, tier 3 every 1s, tier 4 every 2s, tier
# 5 every 4s, tier 6 every 8s.
#tick_time: .25
# This is the base interval used for status tier 1. All other status tiers
# are calculated using the value defined by tick_time (See below for more
# information). Default is 250ms.
#config_include_path: ~/klipper_config
# The path of a directory in which "included" configuration files reside.
# If specified, moonraker will serve this path allowing file and directory
# manipuation within it. Note that this should not be the same directory
# in which printer.cfg is located (the home directory for most installations).
# The default is None, in which no included config files will be served.
```
Retreive the API Key via the browser from a trusted client:
The "status tiers" are used to determine how fast each klippy object is allowed
to be polled. Each tier is calculated using the `tick_time` option. There are
6 tiers, `tier_1 = tick_time` (.25s), `tier_2 = tick_time*2` (.5s),
`tier_3 = tick_time*4` (1s), `tier_4 = tick_time*8` (2s),
`tier_5 = tick_time*16` (4s), and `tier_6 = tick_time*16` (8s). This method
was chosen to provide some flexibility for slower hosts while making it easy to
batch subscription updates together.
- Navigate to `http://{moonraker-host}/access/api_key`, where
`{moonraker-host}` is the host name or ip address of the desired
moonraker instance.
- The result will appear in the browser window in JSON format. Copy
The API Key without the quotes.
## Plugin Configuration
The core plugins are configured via the primary configuration above. Optional
plugins each need their own configuration as outlined below.
{"result": "8ce6ae5d354a4365812b83140ed62e4b"}
### PanelDue Plugin
### Additional Notes
```
[moonraker_plugin paneldue]
serial: /dev/ttyAMA0
baud: 57600
machine_name: Voron 2
macros:
LOAD_FILAMENT
UNLOAD_FILAMENT
PREHEAT_CHAMBER
TURN_OFF_MOTORS
TURN_OFF_HEATERS
PANELDUE_BEEP FREQUENCY=500 DURATION=1
```
- Make sure that Moonraker and Klipper both have read and write access to the
directory set in the `path` option for the `[virtual_sdcard]` in
`printer.cfg`.
- Upon first starting Moonraker is not aware of the gcode file path, thus
it cannot serve gcode files, add directories, etc. After Klippy enters
the "ready" state it sends Moonraker the gcode file path.
Once Moonraker receives the path it will retain it regardless of Klippy's
state, and update it if the path is changed in printer.cfg.
Most options above are self explanatory. The "macros" option can be used
to specify commands (either built in or gcode_macros) that will show up
in the PanelDue's "macro" menu.
Note that buzzing the piezo requires the following gcode_macro:
```
[gcode_macro PANELDUE_BEEP]
# Beep frequency
default_parameter_FREQUENCY: 300
# Beep duration in seconds
default_parameter_DURATION: 1.
gcode:
{ printer.moonraker.action_call_remote_method(
"paneldue_beep", frequency=FREQUENCY|int,
duration=DURATION|float) }
```
### Power Control Plugin
```
[moonraker_plugin power]
devices: printer, led
# A comma separated list of devices you wish to control. Do not use spaces in
# the device's name here
#{dev}_name: Friendly Name
# This is the friendly name for the device. {dev} must be swapped for the name
# of the device used under devices, as an example:
# printer_name: My Printer
{dev}_pin: 23
# This option is required.
# The GPIO Pin number you wish to control
#{dev}_active_low: False
# If you have a device that needs a low or 0 signal to be turned on, set this
# option to True.
```
Define the devices you wish to control under _devices_ with a comma separated
list. For device specific configrations, swap {dev} for the name of the device
that you listed under devices.
Each device can have a Friendly Name, pin, and activehigh set. Pin is the only
required option. For devices that should be active when the signal is 0 or low,
set {dev}_activehigh to False, otherwise don't put the option in the
configuration.
Please see [configuration.md](configuration.md) for details on how to
configure moonraker.conf.
+20
View File
@@ -0,0 +1,20 @@
# Sample Moonraker Configuration File
[server]
# Bind server defaults of 0.0.0.0, port 7125
enable_debug_logging: True
config_path: ~/printer_config
[authorization]
enabled: True
trusted_clients:
# Enter your client IP here or range here
192.168.1.0/24
cors_domains:
# Allow CORS requests for Fluidd
http://app.fluidd.xyz
# Enable Octoprint compatibility for Slicer uploads
# Supports Cura, Slic3r, and Slic3r dervivatives
# (PrusaSlicer, SuperSlicer)
[octoprint_compat]
-3
View File
@@ -1,3 +0,0 @@
## Plugins
Documentation Forthcoming
+385
View File
@@ -0,0 +1,385 @@
#
As mentioned in the API documentation, it is possible to
[query](web_api.md#query-printer-object-status) or
[subscribe](web_api.md#subscribe-to-printer-object-status)
to "Klipper Printer Objects." There are numerous printer objects in
Klipper, many of which are optional and only report status if they are
enabled by Klipper's configuration. Client's may retreive a list of
available printer objects via the
[list objects endpoint](web_api.md#list-available-printer-objects). This
should be done after Klipper reports its state as "ready".
This section will provide an overview of the most useful printer objects.
If a developer is interested in retreiving state for an object not listed here,
look in Klipper's source code for module you wish to query. If the module
contains a "get_status()" method, its return value will contain a dictionary
that reports state which can be queried.
## webhooks
```json
{
"state": "startup",
"state_message": "message"
}
```
The `webhooks` object contains the current printer state and the current
state message. These fields match those returned via the `/printer/info`
endpoint. This is provided as a convience, clients may subscribe to `webhooks`
so they are asynchonously notified of a change to printer state. The `state`
may be `startup`, `ready`, `shutdown`, or `error`. The `state_message`
contains a message specific to the current printers state.
## gcode_move
```json
{
"speed_factor": 1.0,
"speed": 100.0,
"extrude_factor": 1.0,
"absolute_coordinates": true,
"absolute_extrude": false,
"homing_origin": [0.0, 0.0, 0.0, 0.0],
"position": [0.0, 0.0, 0.0, 0.0],
"gcode_position": [0.0, 0.0, 0.0, 0.0]
}
```
The `gcode_move` object reports the current gcode state:
- `speed_factor`: AKA "feedrate", this is the current speed multiplier
- `speed`: The current gcode speed in mm/s.
- `extrude_factor`: AKA "extrusion multiplier".
- `absolute_coorinates`: true if the machine axes are moved using
absolute coordinates, false if using relative coordinates.
- `absolute_extrude`: true if the extruder is moved using absolute
coordinates, false if using relative coordinates.
- `homing_origin`: [X, Y, Z, E] - returns the "gcode offset" applied to
each axis. For example, the "Z" axis can be checked to determine how
much offset has been applied via "babystepping".
- `position`: [X, Y, Z, E] - The internal gcode position, including
any offsets (gcode_offset, G92, etc) added to an axis.
- `gcode_position`: [X, Y, Z, E] - The current gcode position
sans any offsets applied. For X, Y, and Z, this should match
the most recent "G1" or "G0" processed assuming the machine is
using absolute coordinates.
!!! Note
The printer's actual movement will lag behind the reported positional
coordinates due to lookahead.
## toolhead
```json
{
"homed_axes": "xyz",
"print_time": 0.0,
"estimated_print_time": 0.0,
"extruder": "extruder",
"position": [0.0, 0.0, 0.0, 0.0],
"max_velocity": 500.0,
"max_accel": 3000.0,
"max_accel_to_decel": 1500.0,
"square_corner_velocity": 5.0
}
```
The `toolhead` object reports state of the current tool:
- `homed_axes`: a string containing the axes that are homed. If no axes
are homed, returns a null string.
- `print_time`: internal value, not generally useful for clients
- `estimated_print_time`: internal value, not generally useful for clients.
- `extruder`: the name of the currently selected extruder, ie "extruder"
or "extruder1".
- `position`: [X, Y, Z, E] - This the the last position toward which the tool
was commanded to move. It includes any offsets applied via gcode as well
as any transforms made by modules such as "bed_mesh", "bed_tilt", or
"skew_correction".
- `max_velocity`: The currently set maximum velocity of the tool (mm/s^2).
- `max_accel`: The currently set maximum acceleration of the tool (mm/s^2).
- `max_accel_to_decel`: The currently set maximum accel to decel of the tool.
This value is the maximum rate at which the tool can transition from
acceleration to deceleration (mm/s^2).
- `square_corner_velocity`: The currently set square corner velocity. This
is the maximum velocity at which the tool may travel a 90 degree corner.
!!! tip
`max_velocity`, `max_accel`, `max_accel_to_decel`, and
`square_corner_velocity` can be changed by the `SET_VELOCITY_LIMIT` gcode.
`M204` can also change `max_accel`.
## configfile
```json
{
"config": {},
"settings": {},
"save_config_pending": false
}
```
The `configfile` object reports printer configuration state:
- `config`: This is an object containing the configuration as read from
printer.cfg. Each config section will be an object containing the
configured options. Values will ALWAYS be reported as
strings. Note that default values are not reported, only options
configured in printer.cfg are present.
- `settings`: Similar to `config`, however this object includes default
values that may not have been included in `printer.cfg`. It is possible
for a value to be a string, integer, boolean, or float.
- `save_config_pending`: True if the printer has taken an action which
has updated the internal configuration (ie: PID calibration, probe
calibration, bed mesh calibration). This allows clients to present
the user with the option to execute a SAVE_CONFIG gcode which will
save the configuration to printer.cfg and restart the Klippy Host.
## extruder
*Enabled when `[extruder]` is included in printer.cfg*
!!! note
If multiple extruders are configured, extruder 0 is available as
`extruder`, extruder 1 as `extruder1` and so on.
```json
{
"temperature": 0.0,
"target": 0.0,
"power": 0.0,
"pressure_advance": 0.0,
"smooth_time": 0.0
}
```
The `extruder` object reports state of an extruder:
- `temperature`: The extruder's current temperature (in C).
- `target`: The extruder's target temperature (in C).
- `power`: The current pwm value applied to the heater. This value is
expressed as a percentage from 0.0 to 1.0.
- `pressure_advance`: The extruder's current pressure advance value.
- `smooth_time`: The currently set time range to use when calculating the
average extruder velocity for pressure advance.
## heater_bed
*Enabled when `[heater_bed]` is included in printer.cfg*
```json
{
"temperature": 0.0,
"target": 0.0,
"power": 0.0,
}
```
The `heater_bed` object reports state of the heated bed:
- `temperature`: The bed's current temperature
- `target`: The bed's target temperature
- `power`: The current pwm value applied to the heater. This value is
expressed as a percentage from 0.0 to 1.0.
## fan
*Enabled when `[fan]` is included in printer.cfg*
```json
{
"speed": 0.0,
"rpm": 4000
}
```
The `fan` object returns state of the part cooling fan:
- `speed`: The current fan speed. This is reported as a
percentage of maximum speed in the range of 0.0 - 1.0.
- `rpm`: The fan's revolutions per minute if the tachometer
pin has been configured. Will report `null` if no tach
has been configured.
## idle_timeout
```json
{
"state": "Idle",
"printing_time": 0.0
}
```
The `idle_timeout` object reports the idle state of the printer:
- `state`: Can be `Idle`, `Ready`, or `Printing`. The printer will
transition to the `Printing` state whenever a gcode is issued that
commands the tool, this includes manual commands. Thus this should
not be used to determine if a gcode file print is in progress. It can
however be used to determine if the printer is busy.
- `printing_time`: The amount of time the printer has been in the
`Printing` state. This is reset to 0 whenever the printer transitions
from `Printing` to `Ready`.
## virtual_sdcard
*Enabled when `[virtual_sdcard]` is included in printer.cfg*
```json
{
"progress": 0.0,
"is_active": false,
"file_position": 0
}
```
The `virtual_sdcard` object reports the state of the virtual sdcard:
- `progress`: The print progress reported as a percentage of the file
read, in the range of 0.0 - 1.0.
- `is_active`: Returns true if the virtual sdcard is currently processing
a file. Note that this will return false if a virtual sdcard print is
paused.
- `file_position`: The current file position in bytes. This will always
be an integer value
!!! Note
`progress` and `file_position` will persist after a print has
paused, completed, or errored. They are cleared when the user issues
a SDCARD_RESET_FILE gcode or when a new print has started.
## print_stats
*Enabled when `[virtual_sdcard]` is included in printer.cfg*
```json
{
"filename": "",
"total_duration": 0.0,
"print_duration": 0.0,
"filament_used": 0.0,
"state": "standby",
"message": ""
}
```
The `print_stats` object reports `virtual_sdcard` print state:
- `filename`: The name of the current file loaded. This will be a null
string if no file is loaded. Note that name is a path relative to the
gcode folder, thus if the file is located in a subdirectory it would
be reported as "my_sub_dir/myprint.gcode".
- `total_duration`: The total time (in seconds) elapsed since a print
has started. This includes time spent paused.
- `print_duration`: The total time spent printing (in seconds). This is
equivalent to `total_duration` - time paused.
- `filament_used`: The amount of filament used during the current print
(in mm). Any extrusion during a pause is excluded.
- `state`: Current print state. Can be one of the following values:
- `"standby"`
- `"printing"`
- `"paused"`
- `"complete"`
- `"cancelled"`
- `"error"` - Note that if an error is detected the print will abort
- `message`: If an error is detected, this field contains the error
message generated. Otherwise it will be a null string.
!!! Note
After a print has started all of the values above will persist until
the user issues a SDCARD_RESET_FILE gcode or when a new print has started.
## display_status
*Enabled when `[display]` or `[display_status]` is included in printer.cfg*
```json
{
"message": "",
"progress": 0.0
}
```
The `display_status` object contains state typically used to update displays:
- `message`: The message set by a M117 gcode. If no message is set this will
be a null string.
- `progress`: The percentage of print progress, as reported by M73. This
will be in the range of 0.0 - 1.0. If no M73 has been issued this value
will fallback to the eqivalent of `virtual_sdcard.progress`. Note that
progress updated via M73 has a timeout. If no M73 is received after 5
seconds, `progress` will be set to the fallback value.
## temperature_sensor sensor_name
*Enabled when `[temperature_sensor sensor_name]` is included in printer.cfg.
It is possible for multiple temperature sensors to be configured.*
```json
{
"temperature": 0.0,
"measured_min_temp": 0.0,
"measured_max_temp": 0.0
}
```
A `temperature_sensor` reports the following state:
- `temperature`: Sensor's current reported temperature
- `measured_min_temp`: The mimimum temperature read from the sensor
- `measured_max_temp`: The maximum temperature read from the sensor
## temperature_fan fan_name
*Enabled when `[temperature_fan fan_name]` is included in printer.cfg. It is
possible for multiple temperature fans to be configured.*
```json
{
"speed": 0.0,
"temperature": 0.0,
"target": 0.0
}
```
A `temperature_fan` reports the following state:
- `speed`: Current fan speed as a percentage of maximum speed, reported
in the range of 0.0 - 1.0
- `temperature`: Currently reported temperature of the sensor associated
with the fan
- `target`: The current target temperature for the `temperature_fan`.
## filament_switch_sensor sensor_name
*Enabled when `[filament_switch_sensor sensor_name]` is included in
printer.cfg. It is possible for multiple filament sensors to be configured.*
```json
{
"filament_detected": false,
"enabled": true
}
```
A `filament_switch_sensor` reports the following state:
- `filament_detected`: Set to true if the switch detects filament, otherwise
false
- `enabled`: Set to true if the sensor is currently enabled, otherwise false
## output_pin pin_name
*Enabled when `[output_pin pin_name]` is included in printer.cfg.
It is possible for multiple output pins to be configured.*
```json
{
"value": 0.0
}
```
An `output_pin` reports the following state:
- `value`: The currently set value of the pin, in the range of 0.0 - 1.0.
A digital pin will always be 0 or 1, whereas a pwm pin may report a value
across the entire range.
## bed_mesh
*Enabled when `[bed_mesh]` is included in printer.cfg.*
```json
{
"profile_name": "",
"mesh_min": [0.0, 0.0],
"mesh_max": [0.0, 0.0],
"probed_matrix": [[]],
"mesh_matrix": [[]]
}
```
The `bed_mesh` printer object reports the following state:
- `profile_name`: The name of the currently loaded profile. If no profile is
loaded then this will report a null string. If the user is not using
bed_mesh profile management then this will report `default` after mesh
calibration completes.
- `mesh_min`: [X, Y] - The minimum x and y coordinates of the mesh.
- `mesh_max`: [X, Y] - The maximum x and y coordinates of the mesh.
- `probed_matrix`: A 2 dimensional array representing the matrix of probed
values. If the matrix has not been probed the the result is `[[]]`.
- `mesh_matrix`: A 2 dimension array representing the interpolated mesh. If
no matrix has been generated the result is `[[]]`.
!!! tip
See [web_api.md](web_api.md##bed-mesh-coordinates) for an example
of how to use this information to generate (X,Y,Z) coordinates.
## gcode_macro macro_name
*Enabled when `[gcode_macro macro_name]` is included in printer.cfg.
It is possible for multiple gcode macros to be configured.*
Gcode macros will report the state of configured `variables`.
While user defined macros likely won't report state that is useful
for a client, it is possible for client developers to recommend or
request a specific gcode_macro configuration, then have the client
take action based on the variables reported by the macro.
+86
View File
@@ -0,0 +1,86 @@
##
This file will track changes that require user intervention,
such as a configuration change or a reinstallation.
### April 19th 2021
- The `[authorization]` module is now a component, thus is only
loaded if the user has it configured in `moonraker.conf`. This
deprecates the previous `enable` option, as it is enabled
if configured and disabled otherwise.
- The API Key is now stored in the database. This deprecates the
`api_key_file` option in the `[authorization]` module. Users can
no longer read the contents of the API Key file to retreive the
API Key. Instead, users can run `scripts/fetch-apikey.sh` to
print the API Key. Alternative a user can navigate to
`http://{moonraker-host}/access/api_key` from a trusted client
to retreive the API Key.
### March 10th 2021
- The `cors_domain` option in the `[authoriztion]` section is now
checked for dangerous entries. If a domain entry contains a
wildcard in the top level domain (ie: `http://www.*`) then it
will be rejected, as malicious website can easily reproduce
this match.
### March 6th 2021
- The `enable_debug_logging` in the `[server]` section now defaults
to `False`. This dramatically reduces the amount of logging produced
by Moonraker for the typical user.
### March 4th 2021
- To enable Octoprint compatibility with slicer uploads it is now
required to add `[octoprint_compat]` to `moonraker.conf`. After
making this change it is necessary to restart the Moonraker service
so the module is loaded.
### December 31st 2020
- The file manager no longer restricts the `config_path` to a folder
within the HOME directory. The path may not be the system root,
however it can reside anywhere else on the file system as long as
Moonraker has read and write access to the directory. This applies
to gcode path received from Klipper via the `virtual_sdcard` section
as well.
### December 6th 2020
- Moonraker is now installed as a systemd service. This allows logging
to stdout which can be viewed with the `journalctl -u moonraker` command.
This changes requires the user to rerun the install script. If
`moonraker.conf` is not located in the home directory, the command
will looks something like the following:
cd ~/moonraker
./scripts/install-moonraker.sh -f -c /home/pi/klipper_config/moonraker.conf
Otherwise you can run the install script with no arguments.
### November 19th 2020
- The install script (`install-moonraker.sh`) now has command-line
options:\
`-r` Rebuild the python virtual env\
`-f` Force an overwrite of `/etc/default/moonraker` during installation\
`-c /path/to/moonraker.conf` Allows user to specify the path to
moonraker.conf during configuration. Using this in conjunction with `-f`
will update the defaults file wih the new path.
- New dependencies have been added to Moonraker which require reinstallation.
Run the following command to reinstall and rebuild the virtualenv:
~/moonraker/scripts/install-moonraker.sh -r
- The power plugin configuration has changed. See the
[install guide](installation.md#power-control-plugin) for
details on the new configuration.
- Users transitioning from the previous version of the power plugin will need
to unexport any curently used pins. For example, the following command
may be used to unexport pin 19:
echo 19 > /sys/class/gpio/unexport
Alternatively one may reboot the machine after upgrading:
cd ~/moonraker/
git pull
~/moonraker/scripts/install-moonraker.sh -r
sudo reboot
Make sure that the power plugin configuration has been updated prior
to rebooting the machine.
+3329 -599
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
site_name: Moonraker
site_url: https://moonraker.readthedocs.io
repo_url: https://github.com/Arksine/moonraker
nav:
- 'User Documentation':
- Installation: installation.md
- Configuration : configuration.md
- User Changes: user_changes.md
- 'Client Developers':
- Client API: web_api.md
- Printer Objects: printer_objects.md
- API Changes: api_changes.md
- 'Backend Developers':
- Contributing: contributing.md
- Components: components.md
theme:
name: readthedocs
plugins:
- search
markdown_extensions:
- codehilite
- admonition
+692 -219
View File
File diff suppressed because it is too large. Load diff
-247
View File
@@ -1,247 +0,0 @@
# API Key Based Authorization
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import base64
import uuid
import os
import time
import ipaddress
import logging
import tornado
from tornado.ioloop import IOLoop, PeriodicCallback
TOKEN_TIMEOUT = 5
CONNECTION_TIMEOUT = 3600
PRUNE_CHECK_TIME = 300 * 1000
class Authorization:
def __init__(self, api_key_file):
self.api_key_loc = os.path.expanduser(api_key_file)
self.api_key = self._read_api_key()
self.auth_enabled = True
self.trusted_ips = []
self.trusted_ranges = []
self.trusted_connections = {}
self.access_tokens = {}
self.prune_handler = PeriodicCallback(
self._prune_conn_handler, PRUNE_CHECK_TIME)
self.prune_handler.start()
def load_config(self, config):
self.auth_enabled = config.get("require_auth", self.auth_enabled)
# reset trusted ips
self.trusted_ips = []
trusted_ips = config.get("trusted_ips", [])
for ip in trusted_ips:
try:
ip_addr = ipaddress.ip_address(ip)
except ValueError:
logging.info("IP address <%s> invalid" % (ip))
continue
self.trusted_ips.append(ip_addr)
# reset trusted ranges
self.trusted_ranges = []
trusted_ranges = config.get("trusted_ranges", [])
for ip_range in trusted_ranges:
try:
ip_net = ipaddress.ip_network(ip_range)
except ValueError:
logging.info("IP range <%s> invalid" % (ip_range))
continue
self.trusted_ranges.append(ip_net)
self._reset_trusted_connections()
t_clients = [str(ip) for ip in self.trusted_ips] + \
[str(rng) for rng in self.trusted_ranges]
logging.info(
"Authorization Configuration Loaded\n"
"Auth Enabled: %s\n"
"Trusted Clients:\n%s" %
(self.auth_enabled, "\n".join(t_clients)))
def register_handlers(self, app):
# Register Authorization Endpoints
app.register_local_handler(
"/access/api_key", None, ['GET', 'POST'],
self._handle_apikey_request, http_only=True)
app.register_local_handler(
"/access/oneshot_token", None, ['GET'],
self._handle_token_request, http_only=True)
async def _handle_apikey_request(self, path, method, args):
if method.upper() == 'POST':
self.api_key = self._create_api_key()
return self.api_key
async def _handle_token_request(self, path, method, args):
return self.get_access_token()
def _read_api_key(self):
if os.path.exists(self.api_key_loc):
with open(self.api_key_loc, 'r') as f:
api_key = f.read()
return api_key
# API Key file doesn't exist. Generate
# a new api key and create the file.
logging.info(
"No API Key file found, creating new one at:\n%s"
% (self.api_key_loc))
return self._create_api_key()
def _create_api_key(self):
api_key = uuid.uuid4().hex
with open(self.api_key_loc, 'w') as f:
f.write(api_key)
return api_key
def _reset_trusted_connections(self):
valid_conns = {}
for ip, access_time in self.trusted_connections.items():
if self._check_authorized_ip(ip):
valid_conns[ip] = access_time
else:
logging.info(
"Connection [%s] no longer trusted, removing" % (ip))
self.trusted_connections = valid_conns
def _check_authorized_ip(self, ip):
if ip in self.trusted_ips:
return True
for rng in self.trusted_ranges:
if ip in rng:
return True
return False
def _prune_conn_handler(self):
cur_time = time.time()
expired_conns = []
for ip, access_time in self.trusted_connections.items():
if cur_time - access_time > CONNECTION_TIMEOUT:
expired_conns.append(ip)
for ip in expired_conns:
self.trusted_connections.pop(ip, None)
logging.info(
"Trusted Connection Expired, IP: %s" % (ip))
def _token_expire_handler(self, token):
self.access_tokens.pop(token, None)
def is_enabled(self):
return self.auth_enabled
def get_access_token(self):
token = base64.b32encode(os.urandom(20)).decode()
ioloop = IOLoop.current()
self.access_tokens[token] = ioloop.call_later(
TOKEN_TIMEOUT, self._token_expire_handler, token)
return token
def _check_trusted_connection(self, ip):
if ip is not None:
if ip in self.trusted_connections:
self.trusted_connections[ip] = time.time()
return True
elif self._check_authorized_ip(ip):
logging.info(
"Trusted Connection Detected, IP: %s" % (ip))
self.trusted_connections[ip] = time.time()
return True
return False
def _check_access_token(self, token):
if token in self.access_tokens:
token_handler = self.access_tokens.pop(token, None)
IOLoop.current().remove_timeout(token_handler)
return True
else:
return False
def check_authorized(self, request):
# Authorization is disabled, request may pass
if not self.auth_enabled:
return True
# Check if IP is trusted
try:
ip = ipaddress.ip_address(request.remote_ip)
except ValueError:
logging.exception(
"Unable to Create IP Address %s" % (request.remote_ip))
ip = None
if self._check_trusted_connection(ip):
return True
# Check API Key Header
key = request.headers.get("X-Api-Key")
if key and key == self.api_key:
return True
# Check one-shot access token
token = request.arguments.get('token', [b""])[0].decode()
if self._check_access_token(token):
return True
return False
def close(self):
self.prune_handler.stop()
class AuthorizedRequestHandler(tornado.web.RequestHandler):
def initialize(self, server, auth):
self.server = server
self.auth = auth
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def set_default_headers(self):
if self.settings['enable_cors']:
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
self.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.settings['enable_cors']:
self.set_status(204)
self.finish()
else:
super(AuthorizedRequestHandler, self).options()
# Due to the way Python treats multiple inheritance its best
# to create a separate authorized handler for serving files
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
def initialize(self, server, auth, path, default_filename=None):
super(AuthorizedFileHandler, self).initialize(path, default_filename)
self.server = server
self.auth = auth
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def set_default_headers(self):
if self.settings['enable_cors']:
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
self.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.settings['enable_cors']:
self.set_status(204)
self.finish()
else:
super(AuthorizedFileHandler, self).options()
@@ -1,5 +1,5 @@
# Package definition for the plugins directory
# Package definition for the components directory
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
+681
View File
@@ -0,0 +1,681 @@
# API Key Based Authorization
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import base64
import uuid
import hashlib
import secrets
import os
import time
import datetime
import ipaddress
import re
import socket
import logging
import json
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.web import HTTPError
from libnacl.sign import Signer, Verifier
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Tuple,
Set,
Optional,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
from tornado.httputil import HTTPServerRequest
from tornado.web import RequestHandler
from . import database
DBComp = database.MoonrakerDatabase
IPAddr = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
IPNetwork = Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
OneshotToken = Tuple[IPAddr, Optional[Dict[str, Any]], object]
# Helpers for base64url encoding and decoding
def base64url_encode(data: bytes) -> bytes:
return base64.urlsafe_b64encode(data).rstrip(b"=")
def base64url_decode(data: str) -> bytes:
pad_cnt = len(data) % 4
if pad_cnt:
data += "=" * (4 - pad_cnt)
return base64.urlsafe_b64decode(data)
ONESHOT_TIMEOUT = 5
TRUSTED_CONNECTION_TIMEOUT = 3600
PRUNE_CHECK_TIME = 300 * 1000
HASH_ITER = 100000
API_USER = "_API_KEY_USER_"
TRUSTED_USER = "_TRUSTED_USER_"
RESERVED_USERS = [API_USER, TRUSTED_USER]
JWT_EXP_TIME = datetime.timedelta(hours=1)
JWT_HEADER = {
'alg': "EdDSA",
'typ': "JWT"
}
class Authorization:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.login_timeout = config.getint('login_timeout', 90)
self.force_logins = config.getboolean('force_logins', False)
database: DBComp = self.server.lookup_component('database')
database.register_local_namespace('authorized_users', forbidden=True)
self.users = database.wrap_namespace('authorized_users')
api_user: Optional[Dict[str, Any]] = self.users.get(API_USER, None)
if api_user is None:
self.api_key = uuid.uuid4().hex
self.users[API_USER] = {
'username': API_USER,
'api_key': self.api_key,
'created_on': time.time()
}
else:
self.api_key = api_user['api_key']
host_name, port = self.server.get_host_info()
self.issuer = f"http://{host_name}:{port}"
self.public_jwks: Dict[str, Dict[str, Any]] = {}
for username, user_info in list(self.users.items()):
if username == API_USER:
continue
if 'jwt_secret' in user_info:
try:
priv_key = self._load_private_key(user_info['jwt_secret'])
jwk_id = user_info['jwk_id']
except (self.server.error, KeyError):
logging.info("Invalid key found for user, removing")
user_info.pop('jwt_secret', None)
user_info.pop('jwk_id', None)
self.users[username] = user_info
continue
self.public_jwks[jwk_id] = self._generate_public_jwk(priv_key)
self.trusted_users: Dict[IPAddr, Any] = {}
self.oneshot_tokens: Dict[str, OneshotToken] = {}
self.permitted_paths: Set[str] = set()
# Get allowed cors domains
self.cors_domains: List[str] = []
cors_cfg = config.get('cors_domains', "").strip()
cds = [d.strip() for d in cors_cfg.split('\n') if d.strip()]
for domain in cds:
bad_match = re.search(r"^.+\.[^:]*\*", domain)
if bad_match is not None:
raise config.error(
f"Unsafe CORS Domain '{domain}'. Wildcards are not"
" permitted in the top level domain.")
self.cors_domains.append(
domain.replace(".", "\\.").replace("*", ".*"))
# Get Trusted Clients
self.trusted_ips: List[IPAddr] = []
self.trusted_ranges: List[IPNetwork] = []
self.trusted_domains: List[str] = []
tcs = config.get('trusted_clients', "")
trusted_clients = [c.strip() for c in tcs.split('\n') if c.strip()]
for val in trusted_clients:
# Check IP address
try:
tc = ipaddress.ip_address(val)
except ValueError:
pass
else:
self.trusted_ips.append(tc)
continue
# Check ip network
try:
tc = ipaddress.ip_network(val)
except ValueError:
pass
else:
self.trusted_ranges.append(tc)
continue
# Check hostname
self.trusted_domains.append(val.lower())
t_clients = "\n".join(
[str(ip) for ip in self.trusted_ips] +
[str(rng) for rng in self.trusted_ranges] +
self.trusted_domains)
c_domains = "\n".join(self.cors_domains)
logging.info(
f"Authorization Configuration Loaded\n"
f"Trusted Clients:\n{t_clients}\n"
f"CORS Domains:\n{c_domains}")
self.prune_handler = PeriodicCallback(
self._prune_conn_handler, PRUNE_CHECK_TIME)
self.prune_handler.start()
# Register Authorization Endpoints
self.permitted_paths.add("/server/redirect")
self.permitted_paths.add("/access/login")
self.permitted_paths.add("/access/refresh_jwt")
self.server.register_endpoint(
"/access/login", ['POST'], self._handle_login,
transports=['http'])
self.server.register_endpoint(
"/access/logout", ['POST'], self._handle_logout,
transports=['http'])
self.server.register_endpoint(
"/access/refresh_jwt", ['POST'], self._handle_refresh_jwt,
transports=['http'])
self.server.register_endpoint(
"/access/user", ['GET', 'POST', 'DELETE'],
self._handle_user_request, transports=['http'])
self.server.register_endpoint(
"/access/users/list", ['GET'], self._handle_list_request,
transports=['http'])
self.server.register_endpoint(
"/access/user/password", ['POST'], self._handle_password_reset,
transports=['http'])
self.server.register_endpoint(
"/access/api_key", ['GET', 'POST'],
self._handle_apikey_request, transports=['http'])
self.server.register_endpoint(
"/access/oneshot_token", ['GET'],
self._handle_oneshot_request, transports=['http'])
self.server.register_notification("authorization:user_created")
self.server.register_notification("authorization:user_deleted")
async def _handle_apikey_request(self, web_request: WebRequest) -> str:
action = web_request.get_action()
if action.upper() == 'POST':
self.api_key = uuid.uuid4().hex
self.users[f'{API_USER}.api_key'] = self.api_key
return self.api_key
async def _handle_oneshot_request(self, web_request: WebRequest) -> str:
ip = web_request.get_ip_address()
assert ip is not None
user_info = web_request.get_current_user()
return self.get_oneshot_token(ip, user_info)
async def _handle_login(self, web_request: WebRequest) -> Dict[str, Any]:
return self._login_jwt_user(web_request)
async def _handle_logout(self, web_request: WebRequest) -> Dict[str, str]:
user_info = web_request.get_current_user()
if user_info is None:
raise self.server.error("No user logged in")
username: str = user_info['username']
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid log out request for user {username}")
self.users.pop(f"{username}.jwt_secret", None)
jwk_id: str = self.users.pop(f"{username}.jwk_id", "")
self.public_jwks.pop(jwk_id, None)
return {
"username": username,
"action": "user_logged_out"
}
async def _handle_refresh_jwt(self,
web_request: WebRequest
) -> Dict[str, str]:
refresh_token: str = web_request.get_str('refresh_token')
try:
user_info = self._decode_jwt(refresh_token, token_type="refresh")
except Exception:
raise self.server.error("Invalid Refresh Token", 401)
username: str = user_info['username']
if 'jwt_secret' not in user_info or "jwk_id" not in user_info:
raise self.server.error("User not logged in", 401)
private_key = self._load_private_key(user_info['jwt_secret'])
jwk_id: str = user_info['jwk_id']
token = self._generate_jwt(username, jwk_id, private_key)
return {
'username': username,
'token': token,
'action': 'user_jwt_refresh'
}
async def _handle_user_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
if action == "GET":
user = web_request.get_current_user()
if user is None:
return {
'username': None,
'created_on': None,
}
else:
return {
'username': user['username'],
'created_on': user.get('created_on')
}
elif action == "POST":
# Create User
return self._login_jwt_user(web_request, create=True)
elif action == "DELETE":
# Delete User
return self._delete_jwt_user(web_request)
raise self.server.error("Invalid Request Method")
async def _handle_list_request(self,
web_request: WebRequest
) -> Dict[str, List[Dict[str, Any]]]:
user_list = []
for user in self.users.values():
if user['username'] == API_USER:
continue
user_list.append({
'username': user['username'],
'created_on': user['created_on']
})
return {
'users': user_list
}
async def _handle_password_reset(self,
web_request: WebRequest
) -> Dict[str, str]:
password: str = web_request.get_str('password')
new_pass: str = web_request.get_str('new_password')
user_info = web_request.get_current_user()
if user_info is None:
raise self.server.error("No Current User")
username = user_info['username']
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Reset Request for user {username}")
salt = bytes.fromhex(user_info['salt'])
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
if hashed_pass != user_info['password']:
raise self.server.error("Invalid Password")
new_hashed_pass = hashlib.pbkdf2_hmac(
'sha256', new_pass.encode(), salt, HASH_ITER).hex()
self.users[f'{username}.password'] = new_hashed_pass
return {
'username': username,
'action': "user_password_reset"
}
def _login_jwt_user(self,
web_request: WebRequest,
create: bool = False
) -> Dict[str, Any]:
username: str = web_request.get_str('username')
password: str = web_request.get_str('password')
user_info: Dict[str, Any]
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Request for user {username}")
if create:
if username in self.users:
raise self.server.error(f"User {username} already exists")
salt = secrets.token_bytes(32)
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
user_info = {
'username': username,
'password': hashed_pass,
'salt': salt.hex(),
'created_on': time.time()
}
self.users[username] = user_info
action = "user_created"
else:
if username not in self.users:
raise self.server.error(f"Unregistered User: {username}")
user_info = self.users[username]
salt = bytes.fromhex(user_info['salt'])
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
action = "user_logged_in"
if hashed_pass != user_info['password']:
raise self.server.error("Invalid Password")
jwt_secret_hex: Optional[str] = user_info.get('jwt_secret', None)
if jwt_secret_hex is None:
private_key = Signer()
jwk_id = base64url_encode(secrets.token_bytes()).decode()
user_info['jwt_secret'] = private_key.hex_seed().decode()
user_info['jwk_id'] = jwk_id
self.users[username] = user_info
self.public_jwks[jwk_id] = self._generate_public_jwk(private_key)
else:
private_key = self._load_private_key(jwt_secret_hex)
jwk_id = user_info['jwk_id']
token = self._generate_jwt(username, jwk_id, private_key)
refresh_token = self._generate_jwt(
username, jwk_id, private_key, token_type="refresh",
exp_time=datetime.timedelta(days=self.login_timeout))
if create:
IOLoop.current().call_later(
.005, self.server.send_event,
"authorization:user_created",
{'username': username})
return {
'username': username,
'token': token,
'refresh_token': refresh_token,
'action': action
}
def _delete_jwt_user(self, web_request: WebRequest) -> Dict[str, str]:
username: str = web_request.get_str('username')
current_user = web_request.get_current_user()
if current_user is not None:
curname = current_user.get('username', None)
if curname is not None and curname == username:
raise self.server.error(
f"Cannot delete logged in user {curname}")
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Request for reserved user {username}")
user_info: Optional[Dict[str, Any]] = self.users.get(username)
if user_info is None:
raise self.server.error(f"No registered user: {username}")
self.public_jwks.pop(self.users.get(f"{username}.jwk_id"), None)
del self.users[username]
IOLoop.current().call_later(
.005, self.server.send_event,
"authorization:user_deleted",
{'username': username})
return {
"username": username,
"action": "user_deleted"
}
def _generate_jwt(self,
username: str,
jwk_id: str,
private_key: Signer,
token_type: str = "access",
exp_time: datetime.timedelta = JWT_EXP_TIME
) -> str:
curtime = int(time.time())
payload = {
'iss': self.issuer,
'aud': "Moonraker",
'iat': curtime,
'exp': curtime + int(exp_time.total_seconds()),
'username': username,
'token_type': token_type
}
header = {'kid': jwk_id}
header.update(JWT_HEADER)
jwt_header = base64url_encode(json.dumps(header).encode())
jwt_payload = base64url_encode(json.dumps(payload).encode())
jwt_msg = b".".join([jwt_header, jwt_payload])
sig = private_key.signature(jwt_msg)
jwt_sig = base64url_encode(sig)
return b".".join([jwt_msg, jwt_sig]).decode()
def _decode_jwt(self,
token: str,
token_type: str = "access"
) -> Dict[str, Any]:
message, sig = token.rsplit('.', maxsplit=1)
enc_header, enc_payload = message.split('.')
header: Dict[str, Any] = json.loads(base64url_decode(enc_header))
sig_bytes = base64url_decode(sig)
# verify header
if header.get('typ') != "JWT" or header.get('alg') != "EdDSA":
raise self.server.error("Invalid JWT header")
jwk_id = header.get('kid')
if jwk_id not in self.public_jwks:
raise self.server.error("Invalid key ID")
# validate signature
public_key = self._public_key_from_jwk(self.public_jwks[jwk_id])
public_key.verify(sig_bytes + message.encode())
# validate claims
payload: Dict[str, Any] = json.loads(base64url_decode(enc_payload))
if payload['token_type'] != token_type:
raise self.server.error(
f"JWT Token type mismatch: Expected {token_type}, "
f"Recd: {payload['token_type']}", 401)
if payload['iss'] != self.issuer:
raise self.server.error("Invalid JWT Issuer", 401)
if payload['aud'] != "Moonraker":
raise self.server.error("Invalid JWT Audience", 401)
if payload['exp'] < int(time.time()):
raise self.server.error("JWT Expired", 401)
# get user
user_info: Optional[Dict[str, Any]] = self.users.get(
payload.get('username', ""), None)
if user_info is None:
raise self.server.error("Unknown user", 401)
return user_info
def _load_private_key(self, secret: str) -> Signer:
try:
key = Signer(bytes.fromhex(secret))
except Exception:
raise self.server.error(
"Error decoding private key, user data may"
" be corrupt", 500) from None
return key
def _generate_public_jwk(self, private_key: Signer) -> Dict[str, Any]:
public_key = private_key.vk
return {
'x': base64url_encode(public_key).decode(),
'kty': "OKP",
'crv': "Ed25519",
'use': "sig"
}
def _public_key_from_jwk(self, jwk: Dict[str, Any]) -> Verifier:
if jwk.get('kty') != "OKP":
raise self.server.error("Not an Octet Key Pair")
if jwk.get('crv') != "Ed25519":
raise self.server.error("Invalid Curve")
if 'x' not in jwk:
raise self.server.error("No 'x' argument in jwk")
key = base64url_decode(jwk['x'])
return Verifier(key.hex().encode())
def _prune_conn_handler(self) -> None:
cur_time = time.time()
for ip, user_info in list(self.trusted_users.items()):
exp_time: float = user_info['expires_at']
if cur_time >= exp_time:
self.trusted_users.pop(ip, None)
logging.info(
f"Trusted Connection Expired, IP: {ip}")
def _oneshot_token_expire_handler(self, token):
self.oneshot_tokens.pop(token, None)
def get_oneshot_token(self,
ip_addr: IPAddr,
user: Optional[Dict[str, Any]]
) -> str:
token = base64.b32encode(os.urandom(20)).decode()
ioloop = IOLoop.current()
hdl = ioloop.call_later(
ONESHOT_TIMEOUT, self._oneshot_token_expire_handler, token)
self.oneshot_tokens[token] = (ip_addr, user, hdl)
return token
def _check_json_web_token(self,
request: HTTPServerRequest
) -> Optional[Dict[str, Any]]:
auth_token: Optional[str] = request.headers.get("Authorization")
if auth_token is None:
auth_token = request.headers.get("X-Access-Token")
if auth_token and auth_token.startswith("Bearer "):
auth_token = auth_token[7:]
else:
qtoken = request.query_arguments.get('access_token', None)
if qtoken is not None:
auth_token = qtoken[-1].decode()
if auth_token:
try:
return self._decode_jwt(auth_token)
except Exception as e:
raise HTTPError(401, str(e))
return None
def _check_authorized_ip(self, ip: IPAddr) -> bool:
if ip in self.trusted_ips:
return True
for rng in self.trusted_ranges:
if ip in rng:
return True
fqdn = socket.getfqdn(str(ip)).lower()
if fqdn in self.trusted_domains:
return True
return False
def _check_trusted_connection(self,
ip: Optional[IPAddr]
) -> Optional[Dict[str, Any]]:
if ip is not None:
curtime = time.time()
exp_time = curtime + TRUSTED_CONNECTION_TIMEOUT
if ip in self.trusted_users:
self.trusted_users[ip]['expires_at'] = exp_time
return self.trusted_users[ip]
elif self._check_authorized_ip(ip):
logging.info(
f"Trusted Connection Detected, IP: {ip}")
self.trusted_users[ip] = {
'username': TRUSTED_USER,
'password': None,
'created_on': curtime,
'expires_at': exp_time
}
return self.trusted_users[ip]
return None
def _check_oneshot_token(self,
token: str,
cur_ip: IPAddr
) -> Optional[Dict[str, Any]]:
if token in self.oneshot_tokens:
ip_addr, user, hdl = self.oneshot_tokens.pop(token)
IOLoop.current().remove_timeout(hdl)
if cur_ip != ip_addr:
logging.info(f"Oneshot Token IP Mismatch: expected{ip_addr}"
f", Recd: {cur_ip}")
return None
return user
else:
return None
def check_authorized(self,
request: HTTPServerRequest
) -> Optional[Dict[str, Any]]:
if request.path in self.permitted_paths or \
request.method == "OPTIONS":
return None
# Check JSON Web Token
jwt_user = self._check_json_web_token(request)
if jwt_user is not None:
return jwt_user
try:
ip = ipaddress.ip_address(request.remote_ip)
except ValueError:
logging.exception(
f"Unable to Create IP Address {request.remote_ip}")
ip = None
# Check oneshot access token
ost: Optional[List[bytes]] = request.arguments.get('token', None)
if ost is not None:
ost_user = self._check_oneshot_token(ost[-1].decode(), ip)
if ost_user is not None:
return ost_user
# Check API Key Header
key: Optional[str] = request.headers.get("X-Api-Key")
if key and key == self.api_key:
return self.users[API_USER]
# If the force_logins option is enabled and at least one
# user is created this is an unauthorized request
if self.force_logins and len(self.users) > 1:
raise HTTPError(401, "Unauthorized")
# Check if IP is trusted
trusted_user = self._check_trusted_connection(ip)
if trusted_user is not None:
return trusted_user
raise HTTPError(401, "Unauthorized")
def check_cors(self,
origin: Optional[str],
req_hdlr: Optional[RequestHandler] = None
) -> bool:
if origin is None or not self.cors_domains:
return False
for regex in self.cors_domains:
match = re.match(regex, origin)
if match is not None:
if match.group() == origin:
logging.debug(f"CORS Pattern Matched, origin: {origin} "
f" | pattern: {regex}")
self._set_cors_headers(origin, req_hdlr)
return True
else:
logging.debug(f"Partial Cors Match: {match.group()}")
else:
# Check to see if the origin contains an IP that matches a
# current trusted connection
match = re.search(r"^https?://([^/:]+)", origin)
if match is not None:
ip = match.group(1)
try:
ipaddr = ipaddress.ip_address(ip)
except ValueError:
pass
else:
if self._check_authorized_ip(ipaddr):
logging.debug(
f"Cors request matched trusted IP: {ip}")
self._set_cors_headers(origin, req_hdlr)
return True
logging.debug(f"No CORS match for origin: {origin}\n"
f"Patterns: {self.cors_domains}")
return False
def _set_cors_headers(self,
origin: str,
req_hdlr: Optional[RequestHandler]
) -> None:
if req_hdlr is None:
return
req_hdlr.set_header("Access-Control-Allow-Origin", origin)
if req_hdlr.request.method == "OPTIONS":
req_hdlr.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
req_hdlr.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token, Authorization, X-Access-Token, "
"X-Api-Key")
def close(self) -> None:
self.prune_handler.stop()
def load_component(config: ConfigHelper) -> Authorization:
return Authorization(config)
+167
View File
@@ -0,0 +1,167 @@
# Klipper data logging and storage storage
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import time
from collections import deque
from tornado.ioloop import PeriodicCallback
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Dict,
List,
Tuple,
Deque,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
from . import klippy_apis
APIComp = klippy_apis.KlippyAPI
GCQueue = Deque[Dict[str, Any]]
TempStore = Dict[str, Dict[str, Deque[float]]]
TEMPERATURE_UPDATE_MS = 1000
class DataStore:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.temp_store_size = config.getint('temperature_store_size', 1200)
self.gcode_store_size = config.getint('gcode_store_size', 1000)
# Temperature Store Tracking
self.last_temps: Dict[str, Tuple[float, ...]] = {}
self.gcode_queue: GCQueue = deque(maxlen=self.gcode_store_size)
self.temperature_store: TempStore = {}
self.temp_update_cb = PeriodicCallback(
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
# Register status update event
self.server.register_event_handler(
"server:status_update", self._set_current_temps)
self.server.register_event_handler(
"server:gcode_response", self._update_gcode_store)
self.server.register_event_handler(
"server:klippy_ready", self._init_sensors)
# Register endpoints
self.server.register_endpoint(
"/server/temperature_store", ['GET'],
self._handle_temp_store_request)
self.server.register_endpoint(
"/server/gcode_store", ['GET'],
self._handle_gcode_store_request)
async def _init_sensors(self) -> None:
klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
# Fetch sensors
try:
result: Dict[str, Any]
result = await klippy_apis.query_objects({'heaters': None})
except self.server.error as e:
logging.info(f"Error Configuring Sensors: {e}")
return
sensors: List[str]
sensors = result.get("heaters", {}).get("available_sensors", [])
if sensors:
# Add Subscription
sub: Dict[str, Optional[List[str]]] = {s: None for s in sensors}
try:
status: Dict[str, Any]
status = await klippy_apis.subscribe_objects(sub)
except self.server.error as e:
logging.info(f"Error subscribing to sensors: {e}")
return
logging.info(f"Configuring available sensors: {sensors}")
new_store: TempStore = {}
for sensor in sensors:
fields = list(status.get(sensor, {}).keys())
if sensor in self.temperature_store:
new_store[sensor] = self.temperature_store[sensor]
else:
new_store[sensor] = {
'temperatures': deque(maxlen=self.temp_store_size)}
for item in ["target", "power", "speed"]:
if item in fields:
new_store[sensor][f"{item}s"] = deque(
maxlen=self.temp_store_size)
if sensor not in self.last_temps:
self.last_temps[sensor] = (0., 0., 0., 0.)
self.temperature_store = new_store
# Prune unconfigured sensors in self.last_temps
for sensor in list(self.last_temps.keys()):
if sensor not in self.temperature_store:
del self.last_temps[sensor]
# Update initial temperatures
self._set_current_temps(status)
self.temp_update_cb.start()
else:
logging.info("No sensors found")
self.last_temps = {}
self.temperature_store = {}
self.temp_update_cb.stop()
def _set_current_temps(self, data: Dict[str, Any]) -> None:
for sensor in self.temperature_store:
if sensor in data:
last_val = self.last_temps[sensor]
self.last_temps[sensor] = (
round(data[sensor].get('temperature', last_val[0]), 2),
data[sensor].get('target', last_val[1]),
data[sensor].get('power', last_val[2]),
data[sensor].get('speed', last_val[3]))
def _update_temperature_store(self) -> None:
# XXX - If klippy is not connected, set values to zero
# as they are unknown?
for sensor, vals in self.last_temps.items():
self.temperature_store[sensor]['temperatures'].append(vals[0])
for val, item in zip(vals[1:], ["targets", "powers", "speeds"]):
if item in self.temperature_store[sensor]:
self.temperature_store[sensor][item].append(val)
async def _handle_temp_store_request(self,
web_request: WebRequest
) -> Dict[str, Dict[str, List[float]]]:
store = {}
for name, sensor in self.temperature_store.items():
store[name] = {k: list(v) for k, v in sensor.items()}
return store
async def close(self) -> None:
self.temp_update_cb.stop()
def _update_gcode_store(self, response: str) -> None:
curtime = time.time()
self.gcode_queue.append(
{'message': response, 'time': curtime, 'type': "response"})
def store_gcode_command(self, script: str) -> None:
curtime = time.time()
for cmd in script.split('\n'):
cmd = cmd.strip()
if not cmd:
continue
self.gcode_queue.append(
{'message': script, 'time': curtime, 'type': "command"})
async def _handle_gcode_store_request(self,
web_request: WebRequest
) -> Dict[str, List[Dict[str, Any]]]:
count = web_request.get_int("count", None)
if count is not None:
gc_responses = list(self.gcode_queue)[-count:]
else:
gc_responses = list(self.gcode_queue)
return {'gcode_store': gc_responses}
def load_component(config: ConfigHelper) -> DataStore:
return DataStore(config)
+518
View File
@@ -0,0 +1,518 @@
# Mimimal database for moonraker storage
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import json
import struct
import operator
import logging
from io import BytesIO
from functools import reduce
import lmdb
from utils import SentinelClass
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
ItemsView,
ValuesView,
Tuple,
Optional,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
DBRecord = Union[int, float, bool, str, List[Any], Dict[str, Any]]
DBType = Optional[DBRecord]
DATABASE_VERSION = 1
MAX_NAMESPACES = 50
MAX_DB_SIZE = 200 * 2**20
RECORD_ENCODE_FUNCS = {
int: lambda x: b"q" + struct.pack("q", x),
float: lambda x: b"d" + struct.pack("d", x),
bool: lambda x: b"?" + struct.pack("?", x),
str: lambda x: b"s" + x.encode(),
list: lambda x: json.dumps(x).encode(),
dict: lambda x: json.dumps(x).encode(),
}
RECORD_DECODE_FUNCS = {
ord("q"): lambda x: struct.unpack("q", x[1:])[0],
ord("d"): lambda x: struct.unpack("d", x[1:])[0],
ord("?"): lambda x: struct.unpack("?", x[1:])[0],
ord("s"): lambda x: bytes(x[1:]).decode(),
ord("["): lambda x: json.load(BytesIO(x)),
ord("{"): lambda x: json.load(BytesIO(x)),
}
SENTINEL = SentinelClass.get_instance()
def getitem_with_default(item: Dict, field: Any) -> Any:
if field not in item:
item[field] = {}
return item[field]
class MoonrakerDatabase:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.namespaces: Dict[str, object] = {}
self.enable_debug = config.getboolean("enable_database_debug", False)
self.database_path = os.path.expanduser(config.get(
'database_path', "~/.moonraker_database"))
if not os.path.isdir(self.database_path):
os.mkdir(self.database_path)
self.lmdb_env = lmdb.open(self.database_path, map_size=MAX_DB_SIZE,
max_dbs=MAX_NAMESPACES)
with self.lmdb_env.begin(write=True, buffers=True) as txn:
# lookup existing namespaces
cursor = txn.cursor()
remaining = cursor.first()
while remaining:
key = bytes(cursor.key())
self.namespaces[key.decode()] = self.lmdb_env.open_db(key, txn)
remaining = cursor.next()
cursor.close()
if "moonraker" not in self.namespaces:
mrdb = self.lmdb_env.open_db(b"moonraker", txn)
self.namespaces["moonraker"] = mrdb
txn.put(b'database_version',
self._encode_value(DATABASE_VERSION),
db=mrdb)
# Read out all namespaces to remove any invalid keys on init
for ns in self.namespaces.keys():
self._get_namespace(ns)
# Protected Namespaces have read-only API access. Write access can
# be granted by enabling the debug option. Forbidden namespaces
# have no API access. This cannot be overridden.
self.protected_namespaces = set(self.get_item(
"moonraker", "database.protected_namespaces", ["moonraker"]))
self.forbidden_namespaces = set(self.get_item(
"moonraker", "database.forbidden_namespaces", []))
debug_counter: int = self.get_item(
"moonraker", "database.debug_counter", 0)
if self.enable_debug:
debug_counter += 1
self.insert_item("moonraker", "database.debug_counter",
debug_counter)
if debug_counter:
logging.info(f"Database Debug Count: {debug_counter}")
# Track unsafe shutdowns
unsafe_shutdowns: int = self.get_item(
"moonraker", "database.unsafe_shutdowns", 0)
logging.info(f"Unsafe Shutdown Count: {unsafe_shutdowns}")
# Increment unsafe shutdown counter. This will be reset if
# moonraker is safely restarted
self.insert_item("moonraker", "database.unsafe_shutdowns",
unsafe_shutdowns + 1)
self.server.register_endpoint(
"/server/database/list", ['GET'], self._handle_list_request)
self.server.register_endpoint(
"/server/database/item", ["GET", "POST", "DELETE"],
self._handle_item_request)
def insert_item(self,
namespace: str,
key: Union[List[str], str],
value: DBType
) -> None:
key_list = self._process_key(key)
if namespace not in self.namespaces:
self.namespaces[namespace] = self.lmdb_env.open_db(
namespace.encode())
record = value
if len(key_list) > 1:
record = self._get_record(namespace, key_list[0], force=True)
if not isinstance(record, dict):
record = {}
logging.info(
f"Warning: Key {key_list[0]} contains a value of type "
f"{type(record)}. Overwriting with an object.")
item: Dict[str, Any] = reduce(getitem_with_default, key_list[1:-1],
record)
item[key_list[-1]] = value
if not self._insert_record(namespace, key_list[0], record):
logging.info(
f"Error inserting key '{key}' in namespace '{namespace}'")
def update_item(self,
namespace: str,
key: Union[List[str], str],
value: DBType
) -> None:
key_list = self._process_key(key)
record = self._get_record(namespace, key_list[0])
if len(key_list) == 1:
if isinstance(record, dict) and isinstance(value, dict):
record.update(value)
else:
assert value is not None
record = value
else:
try:
assert isinstance(record, dict)
item: Dict[str, Any] = reduce(
operator.getitem, key_list[1:-1], record)
except Exception:
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
if isinstance(item[key_list[-1]], dict) \
and isinstance(value, dict):
item[key_list[-1]].update(value)
else:
item[key_list[-1]] = value
if not self._insert_record(namespace, key_list[0], record):
logging.info(
f"Error updating key '{key}' in namespace '{namespace}'")
def delete_item(self,
namespace: str,
key: Union[List[str], str],
drop_empty_db: bool = False
) -> Any:
key_list = self._process_key(key)
val = record = self._get_record(namespace, key_list[0])
remove_record = True
if len(key_list) > 1:
try:
assert isinstance(record, dict)
item: Dict[str, Any] = reduce(
operator.getitem, key_list[1:-1], record)
val = item.pop(key_list[-1])
except Exception:
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
remove_record = False if record else True
if remove_record:
db = self.namespaces[namespace]
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
ret = txn.delete(key_list[0].encode())
cursor = txn.cursor()
if not cursor.first() and drop_empty_db:
txn.drop(db)
del self.namespaces[namespace]
else:
ret = self._insert_record(namespace, key_list[0], record)
if not ret:
logging.info(
f"Error deleting key '{key}' from namespace '{namespace}'")
return val
def get_item(self,
namespace: str,
key: Optional[Union[List[str], str]] = None,
default: Any = SENTINEL
) -> Any:
try:
if key is None:
return self._get_namespace(namespace)
key_list = self._process_key(key)
ns = self._get_record(namespace, key_list[0])
val = reduce(operator.getitem, key_list[1:], ns) # type: ignore
except Exception:
if not isinstance(default, SentinelClass):
return default
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
return val
def ns_length(self, namespace: str) -> int:
return len(self.ns_keys(namespace))
def ns_keys(self, namespace: str) -> List[str]:
keys: List[str] = []
db = self.namespaces[namespace]
with self.lmdb_env.begin(db=db) as txn:
cursor = txn.cursor()
remaining = cursor.first()
while remaining:
keys.append(cursor.key().decode())
remaining = cursor.next()
return keys
def ns_values(self, namespace: str) -> ValuesView:
ns = self._get_namespace(namespace)
return ns.values()
def ns_items(self, namespace: str) -> ItemsView:
ns = self._get_namespace(namespace)
return ns.items()
def ns_contains(self, namespace: str, key: Union[List[str], str]) -> bool:
try:
key_list = self._process_key(key)
if len(key_list) == 1:
return key_list[0] in self.ns_keys(namespace)
ns = self._get_namespace(namespace)
reduce(operator.getitem, key_list[1:], ns)
except Exception:
return False
return True
def register_local_namespace(self,
namespace: str,
forbidden: bool = False
) -> None:
if namespace not in self.namespaces:
self.namespaces[namespace] = self.lmdb_env.open_db(
namespace.encode())
if forbidden:
if namespace not in self.forbidden_namespaces:
self.forbidden_namespaces.add(namespace)
self.insert_item(
"moonraker", "database.forbidden_namespaces",
list(self.forbidden_namespaces))
elif namespace not in self.protected_namespaces:
self.protected_namespaces.add(namespace)
self.insert_item("moonraker", "database.protected_namespaces",
list(self.protected_namespaces))
def wrap_namespace(self,
namespace: str,
parse_keys: bool = True
) -> NamespaceWrapper:
if namespace not in self.namespaces:
raise self.server.error(
f"Namespace '{namespace}' not found", 404)
return NamespaceWrapper(namespace, self, parse_keys)
def _process_key(self, key: Union[List[str], str]) -> List[str]:
try:
key_list = key if isinstance(key, list) else key.split('.')
except Exception:
key_list = []
if not key_list or "" in key_list:
raise self.server.error(f"Invalid Key Format: '{key}'")
return key_list
def _insert_record(self, namespace: str, key: str, val: DBType) -> bool:
db = self.namespaces[namespace]
if val is None:
return False
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
ret = txn.put(key.encode(), self._encode_value(val))
return ret
def _get_record(self,
namespace: str,
key: str,
force: bool = False
) -> DBRecord:
if namespace not in self.namespaces:
raise self.server.error(
f"Namespace '{namespace}' not found", 404)
db = self.namespaces[namespace]
with self.lmdb_env.begin(buffers=True, db=db) as txn:
value = txn.get(key.encode())
if value is None:
if force:
return {}
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
return self._decode_value(value)
def _get_namespace(self, namespace: str) -> Dict[str, Any]:
if namespace not in self.namespaces:
raise self.server.error(
f"Invalid database namespace '{namespace}'")
db = self.namespaces[namespace]
result = {}
invalid_key_result = None
with self.lmdb_env.begin(buffers=True, db=db) as txn:
cursor = txn.cursor()
cursor.first()
for db_key, value in cursor:
k = bytes(db_key).decode()
if not k:
invalid_key_result = self._decode_value(value)
continue
result[k] = self._decode_value(value)
if invalid_key_result:
logging.info(f"Invalid Key found in namespace '{namespace}', "
f"dropping value: {repr(invalid_key_result)}")
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
txn.delete(b"")
return result
def _encode_value(self, value: DBRecord) -> bytes:
try:
enc_func = RECORD_ENCODE_FUNCS[type(value)]
return enc_func(value)
except Exception:
raise self.server.error(
f"Error encoding val: {value}, type: {type(value)}")
def _decode_value(self, bvalue: bytes) -> DBRecord:
fmt = bvalue[0]
try:
decode_func = RECORD_DECODE_FUNCS[fmt]
return decode_func(bvalue)
except Exception:
raise self.server.error(
f"Error decoding value {bvalue.decode()}, format: {chr(fmt)}")
async def _handle_list_request(self,
web_request: WebRequest
) -> Dict[str, List[str]]:
ns_list = set(self.namespaces.keys()) - self.forbidden_namespaces
return {'namespaces': list(ns_list)}
async def _handle_item_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
namespace = web_request.get_str("namespace")
if namespace in self.forbidden_namespaces:
raise self.server.error(
f"Read/Write access to namespace '{namespace}'"
" is forbidden", 403)
key: Any
valid_types: Tuple[type, ...]
if action != "GET":
if namespace in self.protected_namespaces and \
not self.enable_debug:
raise self.server.error(
f"Write access to namespaces '{namespace}'"
" is forbidden", 403)
key = web_request.get("key")
valid_types = (list, str)
else:
key = web_request.get("key", None)
valid_types = (list, str, type(None))
if not isinstance(key, valid_types):
raise self.server.error(
"Value for argument 'key' is an invalid type: "
f"{type(key).__name__}")
if action == "GET":
val = self.get_item(namespace, key)
elif action == "POST":
val = web_request.get("value")
self.insert_item(namespace, key, val)
elif action == "DELETE":
val = self.delete_item(namespace, key, drop_empty_db=True)
return {'namespace': namespace, 'key': key, 'value': val}
def close(self) -> None:
# Decrement unsafe shutdown counter
unsafe_shutdowns: int = self.get_item(
"moonraker", "database.unsafe_shutdowns", 0)
self.insert_item("moonraker", "database.unsafe_shutdowns",
unsafe_shutdowns - 1)
# log db stats
msg = ""
with self.lmdb_env.begin() as txn:
for db_name, db in self.namespaces.items():
stats = txn.stat(db)
msg += f"\n{db_name}:\n"
msg += "\n".join([f"{k}: {v}" for k, v in stats.items()])
logging.info(f"Database statistics:\n{msg}")
self.lmdb_env.sync()
self.lmdb_env.close()
class NamespaceWrapper:
def __init__(self,
namespace: str,
database: MoonrakerDatabase,
parse_keys: bool
) -> None:
self.namespace = namespace
self.db = database
# If parse keys is true, keys of a string type
# will be passed straight to the DB methods.
self.parse_keys = parse_keys
def insert(self, key: Union[List[str], str], value: DBType) -> None:
if isinstance(key, str) and not self.parse_keys:
key = [key]
self.db.insert_item(self.namespace, key, value)
def update_child(self, key: Union[List[str], str], value: DBType) -> None:
if isinstance(key, str) and not self.parse_keys:
key = [key]
self.db.update_item(self.namespace, key, value)
def update(self, value: Dict[str, Any]) -> None:
val_keys = set(value.keys())
new_keys = val_keys - set(self.keys())
update_keys = val_keys - new_keys
for key in update_keys:
self.update_child([key], value[key])
for key in new_keys:
self.insert([key], value[key])
def get(self,
key: Union[List[str], str],
default: Any = None
) -> Any:
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.get_item(self.namespace, key, default)
def delete(self, key: Union[List[str], str]) -> Any:
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.delete_item(self.namespace, key)
def __len__(self) -> int:
return self.db.ns_length(self.namespace)
def __getitem__(self, key: Union[List[str], str]) -> Any:
return self.get(key, default=SENTINEL)
def __setitem__(self,
key: Union[List[str], str],
value: DBType
) -> None:
self.insert(key, value)
def __delitem__(self, key: Union[List[str], str]):
self.delete(key)
def __contains__(self, key: Union[List[str], str]) -> bool:
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.ns_contains(self.namespace, key)
def keys(self) -> List[str]:
return self.db.ns_keys(self.namespace)
def values(self) -> ValuesView:
return self.db.ns_values(self.namespace)
def items(self) -> ItemsView:
return self.db.ns_items(self.namespace)
def pop(self,
key: Union[List[str], str],
default: Any = SENTINEL
) -> Any:
try:
val = self.delete(key)
except Exception:
if isinstance(default, SentinelClass):
raise
val = default
return val
def clear(self) -> None:
keys = self.keys()
for k in keys:
try:
self.delete([k])
except Exception:
pass
def load_component(config: ConfigHelper) -> MoonrakerDatabase:
return MoonrakerDatabase(config)
@@ -0,0 +1,15 @@
# Package definition for the file_manager
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
from . import file_manager as fm
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from confighelper import ConfigHelper
def load_component(config: ConfigHelper) -> fm.FileManager:
return fm.load_component(config)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,756 @@
#!/usr/bin/env python3
# GCode metadata extraction utility
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import json
import argparse
import re
import os
import sys
import base64
import traceback
import tempfile
import zipfile
import shutil
from PIL import Image
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Dict,
List,
Type,
)
if TYPE_CHECKING:
pass
UFP_MODEL_PATH = "/3D/model.gcode"
UFP_THUMB_PATH = "/Metadata/thumbnail.png"
def log_to_stderr(msg: str) -> None:
sys.stderr.write(f"{msg}\n")
sys.stderr.flush()
# regex helpers
def _regex_find_floats(pattern: str,
data: str,
strict: bool = False
) -> List[float]:
# If strict is enabled, pattern requires a floating point
# value, otherwise it can be an integer value
fptrn = r'\d+\.\d*' if strict else r'\d+\.?\d*'
matches = re.findall(pattern, data)
if matches:
# return the maximum height value found
try:
return [float(h) for h in re.findall(
fptrn, " ".join(matches))]
except Exception:
pass
return []
def _regex_find_ints(pattern: str, data: str) -> List[int]:
matches = re.findall(pattern, data)
if matches:
# return the maximum height value found
try:
return [int(h) for h in re.findall(
r'\d+', " ".join(matches))]
except Exception:
pass
return []
def _regex_find_first(pattern: str, data: str) -> Optional[float]:
match = re.search(pattern, data)
val: Optional[float] = None
if match:
try:
val = float(match.group(1))
except Exception:
return None
return val
# Slicer parsing implementations
class BaseSlicer(object):
def __init__(self, file_path: str) -> None:
self.path = file_path
self.header_data: str = ""
self.footer_data: str = ""
self.layer_height: Optional[float] = None
def set_data(self,
header_data: str,
footer_data: str,
fsize: int) -> None:
self.header_data = header_data
self.footer_data = footer_data
self.size: int = fsize
def _parse_min_float(self,
pattern: str,
data: str,
strict: bool = False
) -> Optional[float]:
result = _regex_find_floats(pattern, data, strict)
if result:
return min(result)
else:
return None
def _parse_max_float(self,
pattern: str,
data: str,
strict: bool = False
) -> Optional[float]:
result = _regex_find_floats(pattern, data, strict)
if result:
return max(result)
else:
return None
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
return None
def parse_gcode_start_byte(self) -> Optional[int]:
m = re.search(r"\n[MG]\d+\s.*\n", self.header_data)
if m is None:
return None
return m.start()
def parse_gcode_end_byte(self) -> Optional[int]:
rev_data = self.footer_data[::-1]
m = re.search(r"\n.*\s\d+[MG]\n", rev_data)
if m is None:
return None
return self.size - m.start()
def parse_first_layer_height(self) -> Optional[float]:
return None
def parse_layer_height(self) -> Optional[float]:
return None
def parse_object_height(self) -> Optional[float]:
return None
def parse_filament_total(self) -> Optional[float]:
return None
def parse_filament_weight_total(self) -> Optional[float]:
return None
def parse_estimated_time(self) -> Optional[float]:
return None
def parse_first_layer_bed_temp(self) -> Optional[float]:
return None
def parse_first_layer_extr_temp(self) -> Optional[float]:
return None
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
return None
class UnknownSlicer(BaseSlicer):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
return {'slicer': "Unknown"}
def parse_first_layer_height(self) -> Optional[float]:
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_object_height(self) -> Optional[float]:
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"M109 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
class PrusaSlicer(BaseSlicer):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"PrusaSlicer\s(.*)\son", data)
if match:
return {
'slicer': "PrusaSlicer",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self) -> Optional[float]:
# Check percentage
pct = _regex_find_first(
r"; first_layer_height = (\d+)%", self.footer_data)
if pct is not None:
if self.layer_height is None:
# Failed to parse the original layer height, so it is not
# possible to calculate a percentage
return None
return round(pct / 100. * self.layer_height, 6)
return _regex_find_first(
r"; first_layer_height = (\d+\.?\d*)", self.footer_data)
def parse_layer_height(self) -> Optional[float]:
self.layer_height = _regex_find_first(
r"; layer_height = (\d+\.?\d*)", self.footer_data)
return self.layer_height
def parse_object_height(self) -> Optional[float]:
matches = re.findall(
r";BEFORE_LAYER_CHANGE\n(?:.*\n)?;(\d+\.?\d*)", self.footer_data)
if matches:
try:
matches = [float(m) for m in matches]
except Exception:
pass
else:
return max(matches)
return self._parse_max_float(r"G1\sZ\d+\.\d*\sF", self.footer_data)
def parse_filament_total(self) -> Optional[float]:
return _regex_find_first(
r"filament\sused\s\[mm\]\s=\s(\d+\.\d*)", self.footer_data)
def parse_filament_weight_total(self) -> Optional[float]:
return _regex_find_first(
r"total\sfilament\sused\s\[g\]\s=\s(\d+\.\d*)", self.footer_data)
def parse_estimated_time(self) -> Optional[float]:
time_match = re.search(
r';\sestimated\sprinting\stime.*', self.footer_data)
if not time_match:
return None
total_time = 0
time_group = time_match.group()
time_patterns = [(r"(\d+)d", 24*60*60), (r"(\d+)h", 60*60),
(r"(\d+)m", 60), (r"(\d+)s", 1)]
try:
for pattern, multiplier in time_patterns:
t = re.search(pattern, time_group)
if t:
total_time += int(t.group(1)) * multiplier
except Exception:
return None
return round(total_time, 2)
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
thumb_matches: List[str] = re.findall(
r"; thumbnail begin[;/\+=\w\s]+?; thumbnail end", self.header_data)
if not thumb_matches:
return None
thumb_dir = os.path.join(os.path.dirname(self.path), ".thumbs")
if not os.path.exists(thumb_dir):
try:
os.mkdir(thumb_dir)
except Exception:
log_to_stderr(f"Unable to create thumb dir: {thumb_dir}")
return None
thumb_base = os.path.splitext(os.path.basename(self.path))[0]
parsed_matches: List[Dict[str, Any]] = []
for match in thumb_matches:
lines = re.split(r"\r?\n", match.replace('; ', ''))
info = _regex_find_ints(r".*", lines[0])
data = "".join(lines[1:-1])
if len(info) != 3:
log_to_stderr(
f"MetadataError: Error parsing thumbnail"
f" header: {lines[0]}")
continue
if len(data) != info[2]:
log_to_stderr(
f"MetadataError: Thumbnail Size Mismatch: "
f"detected {info[2]}, actual {len(data)}")
continue
thumb_name = f"{thumb_base}-{info[0]}x{info[1]}.png"
thumb_path = os.path.join(thumb_dir, thumb_name)
rel_thumb_path = os.path.join(".thumbs", thumb_name)
with open(thumb_path, "wb") as f:
f.write(base64.b64decode(data.encode()))
parsed_matches.append({
'width': info[0], 'height': info[1],
'size': os.path.getsize(thumb_path),
'relative_path': rel_thumb_path})
return parsed_matches
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"; first_layer_temperature = (\d+\.?\d*)", self.footer_data)
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"; first_layer_bed_temperature = (\d+\.?\d*)", self.footer_data)
class Slic3rPE(PrusaSlicer):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"Slic3r\sPrusa\sEdition\s(.*)\son", data)
if match:
return {
'slicer': "Slic3r PE",
'slicer_version': match.group(1)
}
return None
def parse_filament_total(self) -> Optional[float]:
return _regex_find_first(
r"filament\sused\s=\s(\d+\.\d+)mm", self.footer_data)
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
return None
class Slic3r(Slic3rPE):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"Slic3r\s(\d.*)\son", data)
if match:
return {
'slicer': "Slic3r",
'slicer_version': match.group(1)
}
return None
def parse_filament_total(self) -> Optional[float]:
filament = _regex_find_first(
r";\sfilament\_length\_m\s=\s(\d+\.\d*)", self.footer_data)
if filament is not None:
filament *= 1000
return filament
def parse_filament_weight_total(self) -> Optional[float]:
return _regex_find_first(
r";\sfilament\smass\_g\s=\s(\d+\.\d*)", self.footer_data)
def parse_estimated_time(self) -> Optional[float]:
return None
class SuperSlicer(PrusaSlicer):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"SuperSlicer\s(.*)\son", data)
if match:
return {
'slicer': "SuperSlicer",
'slicer_version': match.group(1)
}
return None
class Cura(PrusaSlicer):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"Cura_SteamEngine\s(.*)", data)
if match:
return {
'slicer': "Cura",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self) -> Optional[float]:
return _regex_find_first(r";MINZ:(\d+\.?\d*)", self.header_data)
def parse_layer_height(self) -> Optional[float]:
self.layer_height = _regex_find_first(
r";Layer\sheight:\s(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self) -> Optional[float]:
return _regex_find_first(r";MAXZ:(\d+\.?\d*)", self.header_data)
def parse_filament_total(self) -> Optional[float]:
filament = _regex_find_first(
r";Filament\sused:\s(\d+\.?\d*)m", self.header_data)
if filament is not None:
filament *= 1000
return filament
def parse_filament_weight_total(self) -> Optional[float]:
return _regex_find_first(
r";Filament\sweight\s=\s.(\d+\.\d+).", self.header_data)
def parse_estimated_time(self) -> Optional[float]:
return self._parse_max_float(r";TIME:.*", self.header_data)
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"M109 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
# Attempt to parse thumbnails from file metadata
thumbs = super().parse_thumbnails()
if thumbs is not None:
return thumbs
# Check for thumbnails extracted from the ufp
thumb_dir = os.path.join(os.path.dirname(self.path), ".thumbs")
thumb_base = os.path.splitext(os.path.basename(self.path))[0]
thumb_path = os.path.join(thumb_dir, f"{thumb_base}.png")
rel_path_full = os.path.join(".thumbs", f"{thumb_base}.png")
rel_path_small = os.path.join(".thumbs", f"{thumb_base}-32x32.png")
thumb_path_small = os.path.join(thumb_dir, f"{thumb_base}-32x32.png")
if not os.path.isfile(thumb_path):
return None
# read file
thumbs = []
try:
with Image.open(thumb_path) as im:
thumbs.append({
'width': im.width, 'height': im.height,
'size': os.path.getsize(thumb_path),
'relative_path': rel_path_full
})
# Create 32x32 thumbnail
im.thumbnail((32, 32), Image.ANTIALIAS)
im.save(thumb_path_small, format="PNG")
thumbs.insert(0, {
'width': im.width, 'height': im.height,
'size': os.path.getsize(thumb_path_small),
'relative_path': rel_path_small
})
except Exception as e:
log_to_stderr(str(e))
return None
return thumbs
class Simplify3D(BaseSlicer):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"Simplify3D\(R\)\sVersion\s(.*)", data)
if match:
return {
'slicer': "Simplify3D",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self) -> Optional[float]:
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_layer_height(self) -> Optional[float]:
self.layer_height = _regex_find_first(
r";\s+layerHeight,(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self) -> Optional[float]:
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
def parse_filament_total(self) -> Optional[float]:
return _regex_find_first(
r";\s+Filament\slength:\s(\d+\.?\d*)\smm", self.footer_data)
def parse_filament_weight_total(self) -> Optional[float]:
return _regex_find_first(
r";\s+Plastic\sweight:\s(\d+\.?\d*)\sg", self.footer_data)
def parse_estimated_time(self) -> Optional[float]:
time_match = re.search(
r';\s+Build time:.*', self.footer_data)
if not time_match:
return None
total_time = 0
time_group = time_match.group()
time_patterns = [(r"(\d+)\shours", 60*60), (r"(\d+)\smin", 60),
(r"(\d+)\ssec", 1)]
try:
for pattern, multiplier in time_patterns:
t = re.search(pattern, time_group)
if t:
total_time += int(t.group(1)) * multiplier
except Exception:
return None
return round(total_time, 2)
def _get_temp_items(self, pattern: str) -> List[str]:
match = re.search(pattern, self.header_data)
if match is None:
return []
return match.group().split(",")[1:]
def _get_first_layer_temp(self, heater: str) -> Optional[float]:
heaters = self._get_temp_items(r"temperatureName.*")
temps = self._get_temp_items(r"temperatureSetpointTemperatures.*")
for h, temp in zip(heaters, temps):
if h == heater:
try:
return float(temp)
except Exception:
return None
return None
def parse_first_layer_extr_temp(self) -> Optional[float]:
return self._get_first_layer_temp("Extruder 1")
def parse_first_layer_bed_temp(self) -> Optional[float]:
return self._get_first_layer_temp("Heated Bed")
class KISSlicer(BaseSlicer):
def check_identity(self, data: str) -> Optional[Dict[str, Any]]:
match = re.search(r";\sKISSlicer", data)
if match:
ident = {'slicer': "KISSlicer"}
vmatch = re.search(r";\sversion\s(.*)", data)
if vmatch:
version = vmatch.group(1).replace(" ", "-")
ident['slicer_version'] = version
return ident
return None
def parse_first_layer_height(self) -> Optional[float]:
return _regex_find_first(
r";\s+first_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
def parse_layer_height(self) -> Optional[float]:
self.layer_height = _regex_find_first(
r";\s+max_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self) -> Optional[float]:
return self._parse_max_float(
r";\sEND_LAYER_OBJECT\sz.*", self.footer_data)
def parse_filament_total(self) -> Optional[float]:
filament = _regex_find_floats(
r";\s+Ext\s.*mm", self.footer_data, strict=True)
if filament:
return sum(filament)
return None
def parse_estimated_time(self) -> Optional[float]:
time = _regex_find_first(
r";\sCalculated.*Build\sTime:\s(\d+\.?\d*)\sminutes",
self.footer_data)
if time is not None:
time *= 60
return round(time, 2)
return None
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"; first_layer_C = (\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"; bed_C = (\d+\.?\d*)", self.header_data)
class IdeaMaker(BaseSlicer):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"\sideaMaker\s(.*),", data)
if match:
return {
'slicer': "IdeaMaker",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self) -> Optional[float]:
layer_info = _regex_find_floats(
r";LAYER:0\s*.*\s*;HEIGHT.*", self.header_data)
if len(layer_info) >= 3:
return layer_info[2]
return None
def parse_layer_height(self) -> Optional[float]:
layer_info = _regex_find_floats(
r";LAYER:1\s*.*\s*;HEIGHT.*", self.header_data)
if len(layer_info) >= 3:
self.layer_height = layer_info[2]
return self.layer_height
return None
def parse_object_height(self) -> Optional[float]:
bounds = _regex_find_floats(
r";Bounding Box:.*", self.header_data)
if len(bounds) >= 6:
return bounds[5]
return None
def parse_filament_total(self) -> Optional[float]:
filament = _regex_find_floats(
r";Material.\d\sUsed:.*", self.footer_data, strict=True)
if filament:
return sum(filament)
return None
def parse_filament_weight_total(self) -> Optional[float]:
pi = 3.141592653589793
length = _regex_find_floats(
r";Material.\d\sUsed:.*", self.footer_data, strict=True)
diameter = _regex_find_floats(
r";Filament\sDiameter\s.\d:.*", self.header_data, strict=True)
density = _regex_find_floats(
r";Filament\sDensity\s.\d:.*", self.header_data, strict=True)
if len(length) == len(density) == len(diameter):
# calc individual weight for each filament with m=pi/4*d²*l*rho
weights = [(pi/4 * diameter[i]**2 * length[i] * density[i]/10**6)
for i in range(len(length))]
return sum(weights)
return None
def parse_estimated_time(self) -> Optional[float]:
return _regex_find_first(
r";Print\sTime:\s(\d+\.?\d*)", self.footer_data)
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"M109 T0 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
class IceSL(BaseSlicer):
def check_identity(self, data) -> Optional[Dict[str, Any]]:
match = re.search(r"; <IceSL.*>", data)
if match:
return {'slicer': "IceSL"}
return None
def parse_first_layer_height(self) -> Optional[float]:
return _regex_find_first(
r"; z_layer_height_first_layer_mm :\s+(\d+\.\d+)",
self.header_data)
def parse_layer_height(self) -> Optional[float]:
self.layer_height = _regex_find_first(
r"; z_layer_height_mm :\s+(\d+\.\d+)",
self.header_data)
return self.layer_height
def parse_object_height(self) -> Optional[float]:
return self._parse_max_float(
r"G0 F\d+ Z\d+\.\d+", self.footer_data, strict=True)
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"; extruder_temp_degree_c_0 :\s+(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"; bed_temp_degree_c :\s+(\d+\.?\d*)", self.header_data)
READ_SIZE = 512 * 1024
SUPPORTED_SLICERS: List[Type[BaseSlicer]] = [
PrusaSlicer, Slic3rPE, Slic3r, SuperSlicer,
Cura, Simplify3D, KISSlicer, IdeaMaker, IceSL]
SUPPORTED_DATA = [
'layer_height', 'first_layer_height', 'object_height',
'filament_total', 'filament_weight_total', 'estimated_time',
'thumbnails', 'first_layer_bed_temp', 'first_layer_extr_temp',
'gcode_start_byte', 'gcode_end_byte']
def extract_metadata(file_path: str) -> Dict[str, Any]:
metadata: Dict[str, Any] = {}
slicers = [s(file_path) for s in SUPPORTED_SLICERS]
header_data = footer_data = ""
slicer: Optional[BaseSlicer] = None
size = os.path.getsize(file_path)
metadata['size'] = size
metadata['modified'] = os.path.getmtime(file_path)
with open(file_path, 'r') as f:
# read the default size, which should be enough to
# identify the slicer
header_data = f.read(READ_SIZE)
for s in slicers:
ident = s.check_identity(header_data)
if ident is not None:
slicer = s
metadata.update(ident)
break
if slicer is None:
slicer = UnknownSlicer(file_path)
metadata['slicer'] = "Unknown"
if size > READ_SIZE * 2:
f.seek(size - READ_SIZE)
footer_data = f.read()
elif size > READ_SIZE:
remaining = size - READ_SIZE
footer_data = header_data[remaining - READ_SIZE:] + f.read()
else:
footer_data = header_data
slicer.set_data(header_data, footer_data, size)
for key in SUPPORTED_DATA:
func = getattr(slicer, "parse_" + key)
result = func()
if result is not None:
metadata[key] = result
return metadata
def extract_ufp(ufp_path: str, dest_path: str) -> None:
if not os.path.isfile(ufp_path):
log_to_stderr(f"UFP file Not Found: {ufp_path}")
sys.exit(-1)
thumb_name = os.path.splitext(
os.path.basename(dest_path))[0] + ".png"
dest_thumb_dir = os.path.join(os.path.dirname(dest_path), ".thumbs")
dest_thumb_path = os.path.join(dest_thumb_dir, thumb_name)
try:
with tempfile.TemporaryDirectory() as tmp_dir_name:
tmp_thumb_path = ""
with zipfile.ZipFile(ufp_path) as zf:
tmp_model_path = zf.extract(
UFP_MODEL_PATH, path=tmp_dir_name)
if UFP_THUMB_PATH in zf.namelist():
tmp_thumb_path = zf.extract(
UFP_THUMB_PATH, path=tmp_dir_name)
shutil.move(tmp_model_path, dest_path)
if tmp_thumb_path:
if not os.path.exists(dest_thumb_dir):
os.mkdir(dest_thumb_dir)
shutil.move(tmp_thumb_path, dest_thumb_path)
except Exception:
log_to_stderr(traceback.format_exc())
sys.exit(-1)
try:
os.remove(ufp_path)
except Exception:
log_to_stderr(f"Error removing ufp file: {ufp_path}")
def main(path: str, filename: str, ufp: Optional[str]) -> None:
file_path = os.path.join(path, filename)
if ufp is not None:
extract_ufp(ufp, file_path)
metadata: Dict[str, Any] = {}
if not os.path.isfile(file_path):
log_to_stderr(f"File Not Found: {file_path}")
sys.exit(-1)
try:
metadata = extract_metadata(file_path)
except Exception:
log_to_stderr(traceback.format_exc())
sys.exit(-1)
fd = sys.stdout.fileno()
data = json.dumps(
{'file': filename, 'metadata': metadata}).encode()
while data:
try:
ret = os.write(fd, data)
except OSError:
continue
data = data[ret:]
if __name__ == "__main__":
# Parse start arguments
parser = argparse.ArgumentParser(
description="GCode Metadata Extraction Utility")
parser.add_argument(
"-f", "--filename", metavar='<filename>',
help="name gcode file to parse")
parser.add_argument(
"-p", "--path", default=os.path.abspath(os.path.dirname(__file__)),
metavar='<path>',
help="optional absolute path for file"
)
parser.add_argument(
"-u", "--ufp", metavar="<ufp file>", default=None,
help="optional path of ufp file to extract"
)
args = parser.parse_args()
main(args.path, args.filename, args.ufp)
+362
View File
@@ -0,0 +1,362 @@
# History cache for printer jobs
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import time
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Union,
Optional,
Dict,
List,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
from . import database
from . import klippy_apis
from .file_manager import file_manager
DBComp = database.MoonrakerDatabase
APIComp = klippy_apis.KlippyAPI
FMComp = file_manager.FileManager
HIST_NAMESPACE = "history"
MAX_JOBS = 10000
class History:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.file_manager: FMComp = self.server.lookup_component(
'file_manager')
database: DBComp = self.server.lookup_component("database")
self.gcdb = database.wrap_namespace("gcode_metadata", parse_keys=False)
self.job_totals: Dict[str, float] = database.get_item(
"moonraker", "history.job_totals",
{
'total_jobs': 0,
'total_time': 0.,
'total_print_time': 0.,
'total_filament_used': 0.,
'longest_job': 0.,
'longest_print': 0.
})
self.server.register_event_handler(
"server:klippy_ready", self._init_ready)
self.server.register_event_handler(
"server:status_update", self._status_update)
self.server.register_event_handler(
"server:klippy_disconnect", self._handle_disconnect)
self.server.register_event_handler(
"server:klippy_shutdown", self._handle_shutdown)
self.server.register_notification("history:history_changed")
self.server.register_endpoint(
"/server/history/job", ['GET', 'DELETE'], self._handle_job_request)
self.server.register_endpoint(
"/server/history/list", ['GET'], self._handle_jobs_list)
self.server.register_endpoint(
"/server/history/totals", ['GET'], self._handle_job_totals)
database.register_local_namespace(HIST_NAMESPACE)
self.history_ns = database.wrap_namespace(HIST_NAMESPACE,
parse_keys=False)
self.current_job: Optional[PrinterJob] = None
self.current_job_id: Optional[str] = None
self.print_stats: Dict[str, Any] = {}
self.next_job_id: int = 0
self.cached_job_ids = self.history_ns.keys()
if self.cached_job_ids:
self.next_job_id = int(self.cached_job_ids[-1], 16) + 1
async def _init_ready(self) -> None:
klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
sub: Dict[str, Optional[List[str]]] = {"print_stats": None}
try:
result = await klippy_apis.subscribe_objects(sub)
except self.server.error as e:
logging.info(f"Error subscribing to print_stats")
self.print_stats = result.get("print_stats", {})
async def _handle_job_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
if action == "GET":
job_id = web_request.get_str("uid")
if job_id not in self.cached_job_ids:
raise self.server.error(f"Invalid job uid: {job_id}", 404)
job = self.history_ns[job_id]
return {"job": self._prep_requested_job(job, job_id)}
if action == "DELETE":
all = web_request.get_boolean("all", False)
if all:
deljobs = self.cached_job_ids
self.history_ns.clear()
self.cached_job_ids = []
self.next_job_id = 0
return {'deleted_jobs': deljobs}
job_id = web_request.get_str("uid")
if job_id not in self.cached_job_ids:
raise self.server.error(f"Invalid job uid: {job_id}", 404)
self.delete_job(job_id)
return {'deleted_jobs': [job_id]}
raise self.server.error("Invalid Request Method")
async def _handle_jobs_list(self,
web_request: WebRequest
) -> Dict[str, Any]:
i = 0
count = 0
end_num = len(self.cached_job_ids)
jobs: List[Dict[str, Any]] = []
start_num = 0
before = web_request.get_float("before", -1)
since = web_request.get_float("since", -1)
limit = web_request.get_int("limit", 50)
start = web_request.get_int("start", 0)
order = web_request.get_str("order", "desc")
if order not in ["asc", "desc"]:
raise self.server.error(f"Invalid `order` value: {order}", 400)
reverse_order = (order == "desc")
# cached jobs is asc order, find lower and upper boundary
if since != -1:
while start_num < end_num:
job_id = self.cached_job_ids[start_num]
job: Dict[str, Any] = self.history_ns[job_id]
if job['start_time'] > since:
break
start_num += 1
if before != -1:
while end_num > 0:
job_id = self.cached_job_ids[end_num-1]
job = self.history_ns[job_id]
if job['end_time'] < before:
break
end_num -= 1
if start_num >= end_num or end_num == 0:
return {"count": 0, "jobs": []}
i = start
count = end_num - start_num
if limit == 0:
limit = MAX_JOBS
while i < count and len(jobs) < limit:
if reverse_order:
job_id = self.cached_job_ids[end_num - i - 1]
else:
job_id = self.cached_job_ids[start_num + i]
job = self.history_ns[job_id]
jobs.append(self._prep_requested_job(job, job_id))
i += 1
return {"count": count, "jobs": jobs}
async def _handle_job_totals(self,
web_request: WebRequest
) -> Dict[str, Dict[str, float]]:
return {'job_totals': self.job_totals}
async def _status_update(self, data: Dict[str, Any]) -> None:
ps = data.get("print_stats", {})
if "state" in ps:
old_state: str = self.print_stats['state']
new_state: str = ps['state']
new_ps = dict(self.print_stats)
new_ps.update(ps)
if new_state is not old_state:
if new_state == "printing" and self.current_job is None:
# always add new job if no existing job is present
self.add_job(PrinterJob(new_ps))
elif self.current_job is not None:
if new_state == "complete":
self.finish_job("completed", new_ps)
elif new_state == "cancelled":
self.finish_job("cancelled", new_ps)
elif new_state == "standby":
# Backward compatibility with
# `CLEAR_PAUSE/SDCARD_RESET_FILE` workflow
self.finish_job("cancelled", self.print_stats)
elif new_state == "error":
self.finish_job("error", new_ps)
elif new_state == "printing" and \
self._check_need_cancel(new_ps):
# Finish with the previous state
self.finish_job("cancelled", self.print_stats)
self.add_job(PrinterJob(new_ps))
self.print_stats.update(ps)
def _handle_shutdown(self) -> None:
self.finish_job("klippy_shutdown", self.print_stats)
def _handle_disconnect(self) -> None:
self.finish_job("klippy_disconnect", self.print_stats)
def _check_need_cancel(self, new_stats: Dict[str, Any]) -> bool:
# Cancel if the file name has changed, total duration has
# decreased, or if job is not resuming from a pause
ps = self.print_stats
return ps['filename'] != new_stats['filename'] or \
ps['total_duration'] > new_stats['total_duration'] or \
ps['state'] != "paused"
def add_job(self, job: PrinterJob) -> None:
if len(self.cached_job_ids) >= MAX_JOBS:
self.delete_job(self.cached_job_ids[0])
job_id = f"{self.next_job_id:06X}"
self.current_job = job
self.current_job_id = job_id
self.grab_job_metadata()
self.history_ns[job_id] = job.get_stats()
self.cached_job_ids.append(job_id)
self.next_job_id += 1
self.send_history_event("added")
def delete_job(self, job_id: Union[int, str]) -> None:
if isinstance(job_id, int):
job_id = f"{job_id:06X}"
if job_id in self.cached_job_ids:
del self.history_ns[job_id]
self.cached_job_ids.remove(job_id)
def finish_job(self, status: str, pstats: Dict[str, Any]) -> None:
if self.current_job is None:
return
self.current_job.finish(status, pstats)
# Regrab metadata incase metadata wasn't parsed yet due to file upload
self.grab_job_metadata()
self.save_current_job()
self._update_job_totals()
self.send_history_event("finished")
self.current_job = None
self.current_job_id = None
def get_job(self, job_id: Union[int, str]) -> Optional[Dict[str, Any]]:
if isinstance(job_id, int):
job_id = f"{job_id:06X}"
return self.history_ns.get(job_id, None)
def grab_job_metadata(self) -> None:
if self.current_job is None:
return
filename: str = self.current_job.get("filename")
metadata: Dict[str, Any] = self.gcdb.get(filename, {})
if metadata:
# Add the start time and job id to the
# persistent metadata storage
metadata.update({
'print_start_time': self.current_job.get('start_time'),
'job_id': self.current_job_id
})
self.gcdb[filename] = metadata
# We don't need to store these fields in the
# job metadata, as they are redundant
metadata.pop('print_start_time', None)
metadata.pop('job_id', None)
if "thumbnails" in metadata:
thumb: Dict[str, Any]
for thumb in metadata['thumbnails']:
thumb.pop('data', None)
self.current_job.set("metadata", metadata)
def save_current_job(self) -> None:
if self.current_job is None or self.current_job_id is None:
return
self.history_ns[self.current_job_id] = self.current_job.get_stats()
def _update_job_totals(self) -> None:
if self.current_job is None:
return
job = self.current_job
self.job_totals['total_jobs'] += 1
self.job_totals['total_time'] += job.get('total_duration')
self.job_totals['total_print_time'] += job.get('print_duration')
self.job_totals['total_filament_used'] += job.get('filament_used')
self.job_totals['longest_job'] = max(
self.job_totals['longest_job'], job.get('total_duration'))
self.job_totals['longest_print'] = max(
self.job_totals['longest_print'], job.get('print_duration'))
database: DBComp = self.server.lookup_component("database")
database.insert_item(
"moonraker", "history.job_totals", self.job_totals)
def send_history_event(self, evt_action: str) -> None:
if self.current_job is None or self.current_job_id is None:
return
job = self._prep_requested_job(
self.current_job.get_stats(), self.current_job_id)
self.server.send_event("history:history_changed",
{'action': evt_action, 'job': job})
def _prep_requested_job(self,
job: Dict[str, Any],
job_id: str
) -> Dict[str, Any]:
job['job_id'] = job_id
job['exists'] = self.file_manager.check_file_exists(
"gcodes", job['filename'])
return job
def on_exit(self) -> None:
self.finish_job("server_exit", self.print_stats)
class PrinterJob:
def __init__(self, data: Dict[str, Any] = {}) -> None:
self.end_time: Optional[float] = None
self.filament_used: float = 0
self.filename: Optional[str] = None
self.metadata: Optional[Dict[str, Any]] = None
self.print_duration: float = 0.
self.status: str = "in_progress"
self.start_time = time.time()
self.total_duration: float = 0.
self.update_from_ps(data)
def finish(self,
status: str,
print_stats: Dict[str, Any] = {}
) -> None:
self.end_time = time.time()
self.status = status
self.update_from_ps(print_stats)
def get(self, name: str) -> Any:
if not hasattr(self, name):
return None
return getattr(self, name)
def get_stats(self) -> Dict[str, Any]:
return self.__dict__.copy()
def set(self, name: str, val: Any) -> None:
if not hasattr(self, name):
return
setattr(self, name, val)
def update_from_ps(self, data: Dict[str, Any]) -> None:
for i in data:
if hasattr(self, i):
setattr(self, i, data[i])
def load_component(config: ConfigHelper) -> History:
return History(config)
+201
View File
@@ -0,0 +1,201 @@
# Helper for Moonraker to Klippy API calls.
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
from utils import SentinelClass
from websockets import WebRequest, Subscribable
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Union,
Optional,
Dict,
List,
TypeVar,
Mapping,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
Subscription = Dict[str, Optional[List[Any]]]
_T = TypeVar("_T")
INFO_ENDPOINT = "info"
ESTOP_ENDPOINT = "emergency_stop"
LIST_EPS_ENDPOINT = "list_endpoints"
GC_OUTPUT_ENDPOINT = "gcode/subscribe_output"
GCODE_ENDPOINT = "gcode/script"
SUBSCRIPTION_ENDPOINT = "objects/subscribe"
STATUS_ENDPOINT = "objects/query"
OBJ_LIST_ENDPOINT = "objects/list"
REG_METHOD_ENDPOINT = "register_remote_method"
SENTINEL = SentinelClass.get_instance()
class KlippyAPI(Subscribable):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
app_args = self.server.get_app_args()
self.version = app_args.get('software_version')
# Maintain a subscription for all moonraker requests, as
# we do not want to overwrite them
self.host_subscription: Subscription = {}
# Register GCode Aliases
self.server.register_endpoint(
"/printer/print/pause", ['POST'], self._gcode_pause)
self.server.register_endpoint(
"/printer/print/resume", ['POST'], self._gcode_resume)
self.server.register_endpoint(
"/printer/print/cancel", ['POST'], self._gcode_cancel)
self.server.register_endpoint(
"/printer/print/start", ['POST'], self._gcode_start_print)
self.server.register_endpoint(
"/printer/restart", ['POST'], self._gcode_restart)
self.server.register_endpoint(
"/printer/firmware_restart", ['POST'], self._gcode_firmware_restart)
async def _gcode_pause(self, web_request: WebRequest) -> str:
return await self._send_klippy_request("pause_resume/pause", {})
async def _gcode_resume(self, web_request: WebRequest) -> str:
return await self._send_klippy_request("pause_resume/resume", {})
async def _gcode_cancel(self, web_request: WebRequest) -> str:
return await self._send_klippy_request("pause_resume/cancel", {})
async def _gcode_start_print(self, web_request: WebRequest) -> str:
filename: str = web_request.get_str('filename')
return await self.start_print(filename)
async def _gcode_restart(self, web_request: WebRequest) -> str:
return await self.do_restart("RESTART")
async def _gcode_firmware_restart(self, web_request: WebRequest) -> str:
return await self.do_restart("FIRMWARE_RESTART")
async def _send_klippy_request(self,
method: str,
params: Dict[str, Any],
default: Any = SENTINEL
) -> Any:
try:
result = await self.server.make_request(
WebRequest(method, params, conn=self))
except self.server.error:
if isinstance(default, SentinelClass):
raise
result = default
return result
async def run_gcode(self,
script: str,
default: Any = SENTINEL
) -> str:
params = {'script': script}
result = await self._send_klippy_request(
GCODE_ENDPOINT, params, default)
return result
async def start_print(self, filename: str) -> str:
# XXX - validate that file is on disk
if filename[0] == '/':
filename = filename[1:]
# Escape existing double quotes in the file name
filename = filename.replace("\"", "\\\"")
script = f'SDCARD_PRINT_FILE FILENAME="{filename}"'
return await self.run_gcode(script)
async def do_restart(self, gc: str) -> str:
try:
result = await self.run_gcode(gc)
except self.server.error as e:
if str(e) == "Klippy Disconnected":
result = "ok"
else:
raise
return result
async def list_endpoints(self,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[_T, Dict[str, List[str]]]:
return await self._send_klippy_request(
LIST_EPS_ENDPOINT, {}, default)
async def emergency_stop(self) -> str:
return await self._send_klippy_request(ESTOP_ENDPOINT, {})
async def get_klippy_info(self,
send_id: bool = False,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[_T, Dict[str, Any]]:
params = {}
if send_id:
ver = self.version
params = {'client_info': {'program': "Moonraker", 'version': ver}}
return await self._send_klippy_request(INFO_ENDPOINT, params, default)
async def get_object_list(self,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[_T, List[str]]:
result = await self._send_klippy_request(
OBJ_LIST_ENDPOINT, {}, default)
if isinstance(result, dict) and 'objects' in result:
return result['objects']
return result
async def query_objects(self,
objects: Mapping[str, Optional[List[str]]],
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[_T, Dict[str, Any]]:
params = {'objects': objects}
result = await self._send_klippy_request(
STATUS_ENDPOINT, params, default)
if isinstance(result, dict) and 'status' in result:
return result['status']
return result
async def subscribe_objects(self,
objects: Mapping[str, Optional[List[str]]],
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[_T, Dict[str, Any]]:
for obj, items in objects.items():
if obj in self.host_subscription:
prev = self.host_subscription[obj]
if items is None or prev is None:
self.host_subscription[obj] = None
else:
uitems = list(set(prev) | set(items))
self.host_subscription[obj] = uitems
else:
self.host_subscription[obj] = items
params = {'objects': self.host_subscription}
result = await self._send_klippy_request(
SUBSCRIPTION_ENDPOINT, params, default)
if isinstance(result, dict) and 'status' in result:
return result['status']
return result
async def subscribe_gcode_output(self) -> str:
template = {'response_template':
{'method': "process_gcode_response"}}
return await self._send_klippy_request(GC_OUTPUT_ENDPOINT, template)
async def register_method(self, method_name: str) -> str:
return await self._send_klippy_request(
REG_METHOD_ENDPOINT,
{'response_template': {"method": method_name},
'remote_method': method_name})
def send_status(self,
status: Dict[str, Any],
eventtime: float
) -> None:
self.server.send_event("server:status_update", status)
def load_component(config: ConfigHelper) -> KlippyAPI:
return KlippyAPI(config)
+269
View File
@@ -0,0 +1,269 @@
# Machine manipulation request handlers
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import re
import pathlib
import logging
import platform
import distro
from tornado.ioloop import IOLoop
# Annotation imports
from typing import (
List,
TYPE_CHECKING,
Any,
Dict,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
from . import shell_command
SCMDComp = shell_command.ShellCommandFactory
ALLOWED_SERVICES = [
"moonraker", "klipper", "webcamd", "MoonCord",
"KlipperScreen"]
SYSTEMD_PATH = "/etc/systemd/system"
SD_CID_PATH = "/sys/block/mmcblk0/device/cid"
SD_CSD_PATH = "/sys/block/mmcblk0/device/csd"
SD_MFGRS = {
'1b': "Samsung",
'03': "Sandisk"
}
class Machine:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
dist_info: Dict[str, Any]
dist_info = {'name': distro.name(pretty=True)}
dist_info.update(distro.info())
self.system_info: Dict[str, Any] = {
'cpu_info': self._get_cpu_info(),
'sd_info': self._get_sdcard_info(),
'distribution': dist_info
}
# Add system info to log rollover
sys_info_msg = "\nSystem Info:"
for header, info in self.system_info.items():
sys_info_msg += f"\n\n***{header}***"
for key, val in info.items():
sys_info_msg += f"\n {key}: {val}"
self.server.add_log_rollover_item('system_info', sys_info_msg)
self.available_services: List[str] = []
self.server.register_endpoint(
"/machine/reboot", ['POST'], self._handle_machine_request)
self.server.register_endpoint(
"/machine/shutdown", ['POST'], self._handle_machine_request)
self.server.register_endpoint(
"/machine/services/restart", ['POST'],
self._handle_service_request)
self.server.register_endpoint(
"/machine/services/stop", ['POST'],
self._handle_service_request)
self.server.register_endpoint(
"/machine/services/start", ['POST'],
self._handle_service_request)
self.server.register_endpoint(
"/machine/system_info", ['GET'],
self._handle_sysinfo_request)
# Register remote methods
self.server.register_remote_method(
"shutdown_machine", self.shutdown_machine)
self.server.register_remote_method(
"reboot_machine", self.reboot_machine)
# Retreive list of services
IOLoop.current().spawn_callback(self._find_active_services)
async def _handle_machine_request(self, web_request: WebRequest) -> str:
ep = web_request.get_endpoint()
if ep == "/machine/shutdown":
await self.shutdown_machine()
elif ep == "/machine/reboot":
await self.reboot_machine()
else:
raise self.server.error("Unsupported machine request")
return "ok"
async def shutdown_machine(self) -> None:
await self._execute_cmd("sudo shutdown now")
async def reboot_machine(self) -> None:
await self._execute_cmd("sudo shutdown -r now")
async def do_service_action(self,
action: str,
service_name: str
) -> None:
await self._execute_cmd(
f'sudo systemctl {action} {service_name}')
async def _handle_service_request(self, web_request: WebRequest) -> str:
name: str = web_request.get('service')
action = web_request.get_endpoint().split('/')[-1]
if name == "moonraker":
if action != "restart":
raise self.server.error(
f"Service action '{action}' not available for moonraker")
IOLoop.current().spawn_callback(
self.do_service_action, action, name)
elif name in self.available_services:
await self.do_service_action(action, name)
else:
if name in ALLOWED_SERVICES and \
name not in self.available_services:
raise self.server.error(f"Service '{name}' not installed")
raise self.server.error(
f"Service '{name}' not allowed")
return "ok"
async def _handle_sysinfo_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
return {'system_info': self.system_info}
async def _execute_cmd(self, cmd: str) -> None:
shell_cmd: SCMDComp = self.server.lookup_component('shell_command')
scmd = shell_cmd.build_shell_command(cmd, None)
try:
await scmd.run(timeout=2., verbose=False)
except Exception:
logging.exception(f"Error running cmd '{cmd}'")
raise
def get_system_info(self) -> Dict[str, Dict[str, Any]]:
return self.system_info
def _get_sdcard_info(self) -> Dict[str, Any]:
sd_info: Dict[str, Any] = {}
cid_file = pathlib.Path(SD_CID_PATH)
if not cid_file.exists():
# No SDCard detected at mmcblk0
return {}
try:
cid_text = cid_file.read_text().strip().lower()
mid = cid_text[:2]
sd_info['manufacturer_id'] = mid
sd_info['manufacturer'] = SD_MFGRS.get(mid, "Unknown")
sd_info['oem_id'] = cid_text[2:6]
sd_info['product_name'] = bytes.fromhex(cid_text[6:16]).decode(
encoding="ascii", errors="ignore")
sd_info['product_revision'] = \
f"{int(cid_text[16], 16)}.{int(cid_text[17], 16)}"
sd_info['serial_number'] = cid_text[18:26]
mfg_year = int(cid_text[27:29], 16) + 2000
mfg_month = int(cid_text[29], 16)
sd_info['manufacturer_date'] = f"{mfg_month}/{mfg_year}"
except Exception:
logging.info("Error reading SDCard CID Register")
return {}
sd_info['capacity'] = "Unknown"
sd_info['total_bytes'] = 0
csd_file = pathlib.Path(SD_CSD_PATH)
# Read CSD Register
try:
csd_reg = bytes.fromhex(csd_file.read_text().strip())
csd_type = (csd_reg[0] >> 6) & 0x3
if csd_type == 0:
# Standard Capacity (CSD Version 1.0)
max_block_len: int = 2**(csd_reg[5] & 0xF)
c_size = ((csd_reg[6] & 0x3) << 10) | (csd_reg[7] << 2) | \
((csd_reg[8] >> 6) & 0x3)
c_mult_reg = ((csd_reg[9] & 0x3) << 1) | (csd_reg[10] >> 7)
c_mult = 2**(c_mult_reg + 2)
total_bytes: int = (c_size + 1) * c_mult * max_block_len
sd_info['capacity'] = f"{(total_bytes / (1024.0**2)):.1f} MiB"
elif csd_type == 1:
# High Capacity (CSD Version 2.0)
c_size = ((csd_reg[7] & 0x3F) << 16) | (csd_reg[8] << 8) | \
csd_reg[9]
total_bytes = (c_size + 1) * 512 * 1024
sd_info['capacity'] = f"{(total_bytes / (1024.0**3)):.1f} GiB"
elif csd_type == 2:
# Ultra Capacity (CSD Version 3.0)
c_size = ((csd_reg[6]) & 0xF) << 24 | (csd_reg[7] << 16) | \
(csd_reg[8] << 8) | csd_reg[9]
total_bytes = (c_size + 1) * 512 * 1024
sd_info['capacity'] = f"{(total_bytes / (1024.0**4)):.1f} TiB"
else:
# Invalid CSD, skip capacity check
return sd_info
sd_info['total_bytes'] = total_bytes
except Exception:
logging.info("Error Reading SDCard CSD Register")
return sd_info
def _get_cpu_info(self) -> Dict[str, Any]:
cpu_file = pathlib.Path("/proc/cpuinfo")
mem_file = pathlib.Path("/proc/meminfo")
cpu_info = {
'cpu_count': os.cpu_count(),
'bits': platform.architecture()[0],
'processor': platform.processor() or platform.machine(),
'cpu_desc': "",
'hardware_desc': "",
'model': "",
'total_memory': None,
'memory_units': ""
}
if cpu_file.exists():
try:
cpu_text = cpu_file.read_text().strip()
cpu_items = [item.strip() for item in cpu_text.split("\n\n")
if item.strip()]
for item in cpu_items:
cpu_desc_match = re.search(r"model name\s+:\s+(.+)", item)
if cpu_desc_match is not None:
cpu_info['cpu_desc'] = cpu_desc_match.group(1).strip()
continue
hw_match = re.search(r"Hardware\s+:\s+(.+)", cpu_items[-1])
if hw_match is not None:
cpu_info['hardware_desc'] = hw_match.group(1).strip()
model_match = re.search(r"Model\s+:\s+(.+)", cpu_items[-1])
if model_match is not None:
cpu_info['model'] = model_match.group(1).strip()
except Exception:
logging.info("Error Reading /proc/cpuinfo")
if mem_file.exists():
try:
mem_text = mem_file.read_text().strip()
for line in mem_text.split('\n'):
line = line.strip()
if line.startswith("MemTotal:"):
parts = line.split()
cpu_info['total_memory'] = int(parts[1])
cpu_info['memory_units'] = parts[2]
break
except Exception:
logging.info("Error Reading /proc/meminfo")
return cpu_info
async def _find_active_services(self):
shell_cmd: SCMDComp = self.server.lookup_component('shell_command')
scmd = shell_cmd.build_shell_command(
"systemctl list-units --type=service")
try:
resp = await scmd.run_with_response()
lines = resp.split('\n')
services = [line.split()[0].strip() for line in lines
if ".service" in line.strip()]
except Exception:
services = []
for svc in services:
sname = svc.rsplit('.', 1)[0]
for allowed in ALLOWED_SERVICES:
if sname.startswith(allowed):
self.available_services.append(sname)
self.system_info['available_services'] = self.available_services
def load_component(config: ConfigHelper) -> Machine:
return Machine(config)
+599
View File
@@ -0,0 +1,599 @@
# MQTT client implemenation for Moonraker
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import socket
import asyncio
import logging
import json
import pathlib
from collections import deque
import paho.mqtt.client as paho_mqtt
from tornado.ioloop import IOLoop
from websockets import WebRequest, JsonRPC, APITransport
# Annotation imports
from typing import (
List,
Optional,
TYPE_CHECKING,
Any,
Callable,
Coroutine,
Dict,
Union,
Tuple,
Awaitable,
Deque,
)
if TYPE_CHECKING:
from app import APIDefinition
from confighelper import ConfigHelper
FlexCallback = Callable[[bytes], Optional[Coroutine]]
RPCCallback = Callable[..., Coroutine]
DUP_API_REQ_CODE = -10000
MQTT_PROTOCOLS = {
'v3.1': paho_mqtt.MQTTv31,
'v3.1.1': paho_mqtt.MQTTv311,
'v5': paho_mqtt.MQTTv5
}
class SubscriptionHandle:
def __init__(self, topic: str, callback: FlexCallback) -> None:
self.callback = callback
self.topic = topic
class BrokerAckLogger:
def __init__(self, topics: List[str], action: str) -> None:
self.topics = topics
self.action = action
def __call__(self, fut: asyncio.Future) -> None:
if self.action == "subscribe":
res: Union[List[int], List[paho_mqtt.ReasonCodes]]
res = fut.result()
log_msg = "MQTT Subscriptions Acknowledged"
if len(res) != len(self.topics):
log_msg += "\nTopic / QOS count mismatch, " \
f"\nTopics: {self.topics} " \
f"\nQoS responses: {res}"
else:
for topic, qos in zip(self.topics, res):
log_msg += f"\n Topic: {topic} | "
if isinstance(qos, paho_mqtt.ReasonCodes):
log_msg += qos.getName()
else:
log_msg += f"Granted QoS {qos}"
elif self.action == "unsubscribe":
log_msg = "MQTT Unsubscribe Acknowledged"
for topic in self.topics:
log_msg += f"\n Topic: {topic}"
else:
log_msg = f"Unknown action: {self.action}"
logging.debug(log_msg)
SubscribedDict = Dict[str, Tuple[int, List[SubscriptionHandle]]]
class AIOHelper:
def __init__(self, client: paho_mqtt.Client) -> None:
self.loop = asyncio.get_running_loop()
self.client = client
self.client.on_socket_open = self._on_socket_open
self.client.on_socket_close = self._on_socket_close
self.client._on_socket_register_write = self._on_socket_register_write
self.client._on_socket_unregister_write = \
self._on_socket_unregister_write
self.misc_task: Optional[asyncio.Task] = None
def _on_socket_open(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
logging.info("MQTT Socket Opened")
self.loop.add_reader(sock, client.loop_read)
self.misc_task = self.loop.create_task(self.misc_loop())
def _on_socket_close(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
logging.info("MQTT Socket Closed")
self.loop.remove_reader(sock)
if self.misc_task is not None:
self.misc_task.cancel()
def _on_socket_register_write(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
self.loop.add_writer(sock, client.loop_write)
def _on_socket_unregister_write(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
self.loop.remove_writer(sock)
async def misc_loop(self) -> None:
while self.client.loop_misc() == paho_mqtt.MQTT_ERR_SUCCESS:
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
break
logging.info("MQTT Misc Loop Complete")
class MQTTClient(APITransport):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.address: str = config.get('address')
self.port: int = config.getint('port', 1883)
self.user_name = config.get('username', None)
pw_file_path = config.get('password_file', None)
self.password: Optional[str] = None
if pw_file_path is not None:
pw_file = pathlib.Path(pw_file_path).expanduser().absolute()
if not pw_file.exists():
raise config.error(
f"Password file '{pw_file}' does not exist")
self.password = pw_file.read_text().strip()
protocol = config.get('mqtt_protocol', "v3.1.1")
self.protocol = MQTT_PROTOCOLS.get(protocol, None)
if self.protocol is None:
raise config.error(
f"Invalid value '{protocol}' for option 'mqtt_protocol' "
"in section [mqtt]. Must be one of "
f"{MQTT_PROTOCOLS.values()}")
self.instance_name = config.get('instance_name', socket.gethostname())
if '+' in self.instance_name or '#' in self.instance_name:
raise config.error(
"Option 'instance_name' in section [mqtt] cannot "
"contain a wildcard.")
self.qos = config.getint("default_qos", 0)
if self.qos > 2 or self.qos < 0:
raise config.error(
"Option 'default_qos' in section [mqtt] must be "
"between 0 and 2")
self.client = paho_mqtt.Client(protocol=self.protocol)
self.client.on_connect = self._on_connect
self.client.on_message = self._on_message
self.client.on_disconnect = self._on_disconnect
self.client.on_publish = self._on_publish
self.client.on_subscribe = self._on_subscribe
self.client.on_unsubscribe = self._on_unsubscribe
self.connect_evt: asyncio.Event = asyncio.Event()
self.disconnect_evt: Optional[asyncio.Event] = None
self.reconnect_task: Optional[asyncio.Task] = None
self.subscribed_topics: SubscribedDict = {}
self.pending_responses: List[asyncio.Future] = []
self.pending_acks: Dict[int, asyncio.Future] = {}
self.server.register_endpoint(
"/server/mqtt/publish", ["POST"],
self._handle_publish_request,
transports=["http", "websocket"])
self.server.register_endpoint(
"/server/mqtt/subscribe", ["POST"],
self._handle_subscription_request,
transports=["http", "websocket"])
# Subscribe to API requests
self.json_rpc = JsonRPC(transport="MQTT")
self.api_request_topic = f"{self.instance_name}/moonraker/api/request"
self.api_resp_topic = f"{self.instance_name}/moonraker/api/response"
self.timestamp_deque: Deque = deque(maxlen=20)
self.api_qos = config.getint('api_qos', self.qos)
if config.getboolean("enable_moonraker_api", True):
api_cache = self.server.register_api_transport("mqtt", self)
for api_def in api_cache.values():
if "mqtt" in api_def.supported_transports:
self.register_api_handler(api_def)
self.subscribe_topic(self.api_request_topic,
self._process_api_request,
self.api_qos)
logging.info(
f"Moonraker API topics - Request: {self.api_request_topic}, "
f"Response: {self.api_resp_topic}")
IOLoop.current().spawn_callback(self._initialize)
async def _initialize(self) -> None:
# We must wait for the IOLoop (asyncio event loop) to start
# prior to retreiving it
self.helper = AIOHelper(self.client)
if self.user_name is not None:
self.client.username_pw_set(self.user_name, self.password)
retries = 15
while retries:
try:
self.client.connect(self.address, self.port)
except ConnectionRefusedError:
retries -= 1
if retries:
logging.info("Unable to connect to MQTT broker, "
f"retries remaining: {retries}")
await asyncio.sleep(2.)
continue
self.server.set_failed_component("mqtt")
self.server.add_warning(
f"MQTT Broker Connection at ({self.address}, {self.port}) "
"refused. Check your client and broker configuration.")
return
break
self.client.socket().setsockopt(
socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
def _on_message(self,
client: str,
user_data: Any,
message: paho_mqtt.MQTTMessage
) -> None:
topic = message.topic
if topic in self.subscribed_topics:
cb_hdls = self.subscribed_topics[topic][1]
for hdl in cb_hdls:
IOLoop.current().spawn_callback(
hdl.callback, message.payload) # type: ignore
else:
logging.debug(
f"Unregistered MQTT Topic Received: {topic}, "
f"payload: {message.payload.decode()}")
def _on_connect(self,
client: paho_mqtt.Client,
user_data: Any,
flags: Dict[str, Any],
reason_code: Union[int, paho_mqtt.ReasonCodes],
properties: Optional[paho_mqtt.Properties] = None
) -> None:
logging.info("MQTT Client Connected")
if reason_code == 0:
subs = [(k, v[0]) for k, v in self.subscribed_topics.items()]
if subs:
res, msg_id = client.subscribe(subs)
if msg_id is not None:
sub_fut: asyncio.Future = asyncio.Future()
topics = list(self.subscribed_topics.keys())
sub_fut.add_done_callback(
BrokerAckLogger(topics, "subscribe"))
self.pending_acks[msg_id] = sub_fut
self.connect_evt.set()
else:
if isinstance(reason_code, int):
err_str = paho_mqtt.connack_string(reason_code)
else:
err_str = reason_code.getName()
self.server.set_failed_component("mqtt")
self.server.add_warning(f"MQTT Connection Failed: {err_str}")
def _on_disconnect(self,
client: paho_mqtt.Client,
user_data: Any,
reason_code: int,
properties: Optional[paho_mqtt.Properties] = None
) -> None:
if self.disconnect_evt is not None:
self.disconnect_evt.set()
elif self.is_connected():
# The server connection was dropped, attempt to reconnect
logging.info("MQTT Server Disconnected, reason: "
f"{paho_mqtt.error_string(reason_code)}")
if self.reconnect_task is None:
self.reconnect_task = asyncio.create_task(self._do_reconnect())
self.connect_evt.clear()
def _on_publish(self,
client: paho_mqtt.Client,
user_data: Any,
msg_id: int
) -> None:
pub_fut = self.pending_acks.pop(msg_id, None)
if pub_fut is not None and not pub_fut.done():
pub_fut.set_result(None)
def _on_subscribe(self,
client: paho_mqtt.Client,
user_data: Any,
msg_id: int,
flex: Union[List[int], List[paho_mqtt.ReasonCodes]],
properties: Optional[paho_mqtt.Properties] = None
) -> None:
sub_fut = self.pending_acks.pop(msg_id, None)
if sub_fut is not None and not sub_fut.done():
sub_fut.set_result(flex)
def _on_unsubscribe(self,
client: paho_mqtt.Client,
user_data: Any,
msg_id: int,
properties: Optional[paho_mqtt.Properties] = None,
reasoncodes: Optional[paho_mqtt.ReasonCodes] = None
) -> None:
unsub_fut = self.pending_acks.pop(msg_id, None)
if unsub_fut is not None and not unsub_fut.done():
unsub_fut.set_result(None)
async def _do_reconnect(self) -> None:
logging.info("Attempting MQTT Reconnect")
while True:
try:
await asyncio.sleep(2.)
except asyncio.CancelledError:
break
try:
self.client.reconnect()
except ConnectionRefusedError:
continue
self.client.socket().setsockopt(
socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
break
self.reconnect_task = None
async def wait_connection(self, timeout: Optional[float] = None) -> bool:
try:
await asyncio.wait_for(self.connect_evt.wait(), timeout)
except asyncio.TimeoutError:
return False
return True
def is_connected(self) -> bool:
return self.connect_evt.is_set()
def subscribe_topic(self,
topic: str,
callback: FlexCallback,
qos: Optional[int] = None
) -> SubscriptionHandle:
if '#' in topic or '+' in topic:
raise self.server.error("Wildcards may not be used")
qos = qos or self.qos
if qos > 2 or qos < 0:
raise self.server.error("QOS must be between 0 and 2")
hdl = SubscriptionHandle(topic, callback)
sub_handles = [hdl]
need_sub = True
if topic in self.subscribed_topics:
prev_qos, sub_handles = self.subscribed_topics[topic]
qos = max(qos, prev_qos)
sub_handles.append(hdl)
need_sub = qos != prev_qos
self.subscribed_topics[topic] = (qos, sub_handles)
if self.is_connected() and need_sub:
res, msg_id = self.client.subscribe(topic, qos)
if msg_id is not None:
sub_fut: asyncio.Future = asyncio.Future()
sub_fut.add_done_callback(
BrokerAckLogger([topic], "subscribe"))
self.pending_acks[msg_id] = sub_fut
return hdl
def unsubscribe(self, hdl: SubscriptionHandle) -> None:
topic = hdl.topic
if topic in self.subscribed_topics:
sub_hdls = self.subscribed_topics[topic][1]
try:
sub_hdls.remove(hdl)
except Exception:
pass
if not sub_hdls:
del self.subscribed_topics[topic]
res, msg_id = self.client.unsubscribe(topic)
if msg_id is not None:
unsub_fut: asyncio.Future = asyncio.Future()
unsub_fut.add_done_callback(
BrokerAckLogger([topic], "unsubscribe"))
self.pending_acks[msg_id] = unsub_fut
def publish_topic(self,
topic: str,
payload: Any = None,
qos: Optional[int] = None,
retain: bool = False
) -> Awaitable[None]:
qos = qos or self.qos
if qos > 2 or qos < 0:
raise self.server.error("QOS must be between 0 and 2")
pub_fut: asyncio.Future = asyncio.Future()
if isinstance(payload, (dict, list)):
try:
payload = json.dumps(payload)
except json.JSONDecodeError:
raise self.server.error(
"Dict or List is not json encodable") from None
elif isinstance(payload, bool):
payload = str(payload).lower()
try:
msg_info = self.client.publish(topic, payload, qos, retain)
if msg_info.is_published():
pub_fut.set_result(None)
else:
if qos == 0:
# There is no delivery guarantee for qos == 0, so
# it is possible that the on_publish event will
# not be called if paho mqtt encounters an error
# during publication. Return immediately as
# a workaround.
if msg_info.rc != paho_mqtt.MQTT_ERR_SUCCESS:
err_str = paho_mqtt.error_string(msg_info.rc)
pub_fut.set_exception(self.server.error(
f"MQTT Publish Error: {err_str}", 503))
else:
pub_fut.set_result(None)
return pub_fut
self.pending_acks[msg_info.mid] = pub_fut
except ValueError:
pub_fut.set_exception(self.server.error(
"MQTT Message Queue Full", 529))
except Exception as e:
pub_fut.set_exception(self.server.error(
f"MQTT Publish Error: {e}", 503))
return pub_fut
async def publish_topic_with_response(self,
topic: str,
response_topic: str,
payload: Any = None,
qos: Optional[int] = None,
retain: bool = False,
timeout: Optional[float] = None
) -> bytes:
qos = qos or self.qos
if qos > 2 or qos < 0:
raise self.server.error("QOS must be between 0 and 2")
resp_fut: asyncio.Future = asyncio.Future()
resp_hdl = self.subscribe_topic(
response_topic, resp_fut.set_result, qos)
self.pending_responses.append(resp_fut)
try:
await asyncio.wait_for(self.publish_topic(
topic, payload, qos, retain), timeout)
await asyncio.wait_for(resp_fut, timeout)
except asyncio.TimeoutError:
logging.info(f"Response to request {topic} timed out")
raise self.server.error("MQTT Request Timed Out", 504)
finally:
try:
self.pending_responses.remove(resp_fut)
except Exception:
pass
self.unsubscribe(resp_hdl)
return resp_fut.result()
async def _handle_publish_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
topic: str = web_request.get_str("topic")
payload: Any = web_request.get("payload", None)
qos: int = web_request.get_int("qos", self.qos)
retain: bool = web_request.get_boolean("retain", False)
timeout: Optional[float] = web_request.get_float('timeout', None)
try:
await asyncio.wait_for(self.publish_topic(
topic, payload, qos, retain), timeout)
except asyncio.TimeoutError:
raise self.server.error("MQTT Publish Timed Out", 504)
return {
"topic": topic
}
async def _handle_subscription_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
topic: str = web_request.get_str("topic")
qos: int = web_request.get_int("qos", self.qos)
timeout: Optional[float] = web_request.get_float('timeout', None)
resp: asyncio.Future = asyncio.Future()
hdl: Optional[SubscriptionHandle] = None
try:
hdl = self.subscribe_topic(topic, resp.set_result, qos)
self.pending_responses.append(resp)
await asyncio.wait_for(resp, timeout)
ret: bytes = resp.result()
except asyncio.TimeoutError:
raise self.server.error("MQTT Subscribe Timed Out", 504)
finally:
try:
self.pending_responses.remove(resp)
except Exception:
pass
if hdl is not None:
self.unsubscribe(hdl)
try:
payload = json.loads(ret)
except json.JSONDecodeError:
payload = ret.decode()
return {
'topic': topic,
'payload': payload
}
async def _process_api_request(self, payload: bytes) -> None:
response = await self.json_rpc.dispatch(payload.decode())
if response is not None:
await self.publish_topic(self.api_resp_topic, response,
self.api_qos)
def register_api_handler(self, api_def: APIDefinition) -> None:
if api_def.callback is None:
# Remote API, uses RPC to reach out to Klippy
mqtt_method = api_def.jrpc_methods[0]
rpc_cb = self._generate_remote_callback(api_def.endpoint)
self.json_rpc.register_method(mqtt_method, rpc_cb)
else:
# Local API, uses local callback
for mqtt_method, req_method in \
zip(api_def.jrpc_methods, api_def.request_methods):
rpc_cb = self._generate_local_callback(
api_def.endpoint, req_method, api_def.callback)
self.json_rpc.register_method(mqtt_method, rpc_cb)
logging.info(
"Registering MQTT JSON-RPC methods: "
f"{', '.join(api_def.jrpc_methods)}")
def remove_api_handler(self, api_def: APIDefinition) -> None:
for jrpc_method in api_def.jrpc_methods:
self.json_rpc.remove_method(jrpc_method)
def _generate_local_callback(self,
endpoint: str,
request_method: str,
callback: Callable[[WebRequest], Coroutine]
) -> RPCCallback:
async def func(**kwargs) -> Any:
self._check_timestamp(kwargs)
result = await callback(
WebRequest(endpoint, kwargs, request_method))
return result
return func
def _generate_remote_callback(self, endpoint: str) -> RPCCallback:
async def func(**kwargs) -> Any:
self._check_timestamp(kwargs)
result = await self.server.make_request(
WebRequest(endpoint, kwargs))
return result
return func
def _check_timestamp(self, args: Dict[str, Any]) -> None:
ts = args.pop("mqtt_timestamp", None)
if ts is not None:
if ts in self.timestamp_deque:
logging.debug("Duplicate MQTT API request received")
raise self.server.error(
"Duplicate MQTT Request", DUP_API_REQ_CODE)
else:
self.timestamp_deque.append(ts)
async def close(self) -> None:
if self.reconnect_task is not None:
self.reconnect_task.cancel()
self.reconnect_task = None
if not self.is_connected():
return
self.disconnect_evt = asyncio.Event()
self.client.disconnect()
try:
await asyncio.wait_for(self.disconnect_evt.wait(), 2.)
except asyncio.TimeoutError:
logging.info("MQTT Disconnect Timeout")
futs = list(self.pending_acks.values())
futs.extend(self.pending_responses)
for fut in futs:
if fut.done():
continue
fut.set_exception(
self.server.error("Moonraker Shutdown", 503))
def load_component(config: ConfigHelper) -> MQTTClient:
return MQTTClient(config)
+329
View File
@@ -0,0 +1,329 @@
# Octoprint API compatibility
#
# Copyright (C) 2021 Nickolas Grigoriadis <nagrigoriadis@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
from . import klippy_apis
APIComp = klippy_apis.KlippyAPI
OCTO_VERSION = '1.5.0'
class OctoprintCompat:
"""
Minimal implementation of the REST API as described here:
https://docs.octoprint.org/en/master/api/index.html
So that Cura Octoprint plugin will function for:
* Handshake
* Upload gcode/ufp
* Webcam config
* Manual GCode submission
* Heater temperatures
"""
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.software_version = self.server.get_app_args().get(
'software_version')
# Local variables
self.klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
self.heaters: Dict[str, Dict[str, Any]] = {}
self.last_print_stats: Dict[str, Any] = {}
# Register status update event
self.server.register_event_handler(
'server:klippy_ready', self._init)
self.server.register_event_handler(
'server:status_update', self._handle_status_update)
# Version & Server information
self.server.register_endpoint(
'/api/version', ['GET'], self._get_version,
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/server', ['GET'], self._get_server,
transports=['http'], wrap_result=False)
# Login, User & Settings
self.server.register_endpoint(
'/api/login', ['POST'], self._post_login_user,
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/currentuser', ['GET'], self._post_login_user,
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/settings', ['GET'], self._get_settings,
transports=['http'], wrap_result=False)
# File operations
# Note that file upload is handled in file_manager.py
# TODO: List/info/select/delete files
# Job operations
self.server.register_endpoint(
'/api/job', ['GET'], self._get_job,
transports=['http'], wrap_result=False)
# TODO: start/cancel/restart/pause jobs
# Printer operations
self.server.register_endpoint(
'/api/printer', ['GET'], self._get_printer,
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/printer/command', ['POST'], self._post_command,
transports=['http'], wrap_result=False)
# TODO: head/tool/bed/chamber specific read/issue
# Printer profiles
self.server.register_endpoint(
'/api/printerprofiles', ['GET'], self._get_printerprofiles,
transports=['http'], wrap_result=False)
# System
# TODO: shutdown/reboot/restart operations
async def _init(self) -> None:
self.heaters = {}
# Fetch heaters
try:
result: Dict[str, Any]
sensors: List[str]
result = await self.klippy_apis.query_objects({'heaters': None})
sensors = result.get('heaters', {}).get('available_sensors', [])
except self.server.error as e:
logging.info(f'Error Configuring heaters: {e}')
sensors = []
# subscribe objects
sub: Dict[str, Any] = {s: None for s in sensors}
sub['print_stats'] = None
result = await self.klippy_apis.subscribe_objects(sub)
self.last_print_stats = result.get('print_stats', {})
if sensors:
self.heaters = {name: result.get(name, {}) for name in sensors}
def _handle_status_update(self, status: Dict[str, Any]) -> None:
if 'print_stats' in status:
self.last_print_stats.update(status['print_stats'])
for heater_name, data in self.heaters.items():
if heater_name in status:
data.update(status[heater_name])
def printer_state(self) -> str:
klippy_state = self.server.get_klippy_state()
if klippy_state in ["disconnected", "startup"]:
return 'Offline'
elif klippy_state != 'ready':
return 'Error'
return {
'standby': 'Operational',
'printing': 'Printing',
'paused': 'Paused',
'complete': 'Operational'
}.get(self.last_print_stats.get('state', 'standby'), 'Error')
def printer_temps(self) -> Dict[str, Any]:
temps: Dict[str, Any] = {}
for heater, data in self.heaters.items():
name = 'bed'
if heater.startswith('extruder'):
try:
tool_no = int(heater[8:])
except ValueError:
tool_no = 0
name = f'tool{tool_no}'
elif heater != "heater_bed":
continue
temps[name] = {
'actual': round(data.get('temperature', 0.), 2),
'offset': 0,
'target': data.get('target', 0.),
}
return temps
async def _get_version(self,
web_request: WebRequest
) -> Dict[str, str]:
"""
Version information
"""
return {
'server': OCTO_VERSION,
'api': '0.1',
'text': f'OctoPrint (Moonraker {self.software_version})',
}
async def _get_server(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Server status
"""
klippy_state = self.server.get_klippy_state()
return {
'server': OCTO_VERSION,
'safemode': (
None if klippy_state == 'ready' else 'settings')
}
async def _post_login_user(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Confirm session login.
Since we only support apikey auth, do nothing.
Report hardcoded user called _api
"""
return {
'_is_external_client': False,
'_login_mechanism': 'apikey',
'name': '_api',
'active': True,
'user': True,
'admin': True,
'apikey': None,
'permissions': [],
'groups': ['admins', 'users'],
}
async def _get_settings(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Used to parse Octoprint capabilities
Hardcode capabilities to be basically there and use default
fluid/mainsail webcam path.
"""
return {
'plugins': {
'UltimakerFormatPackage': {
'align_inline_thumbnail': False,
'inline_thumbnail': False,
'inline_thumbnail_align_value': 'left',
'inline_thumbnail_scale_value': '50',
'installed': True,
'installed_version': '0.2.2',
'scale_inline_thumbnail': False,
'state_panel_thumbnail': True,
},
},
'feature': {
'sdSupport': False,
'temperatureGraph': False
},
# TODO: Get webcam settings from config file to allow user
# to customise this.
'webcam': {
'flipH': False,
'flipV': False,
'rotate90': False,
'streamUrl': '/webcam/?action=stream',
'webcamEnabled': True,
},
}
async def _get_job(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Get current job status
"""
return {
'job': {
'file': {'name': None},
'estimatedPrintTime': None,
'filament': {'length': None},
'user': None,
},
'progress': {
'completion': None,
'filepos': None,
'printTime': None,
'printTimeLeft': None,
'printTimeOrigin': None,
},
'state': self.printer_state()
}
async def _get_printer(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Get Printer status
"""
state = self.printer_state()
return {
'temperature': self.printer_temps(),
'state': {
'text': state,
'flags': {
'operational': state not in ['Error', 'Offline'],
'paused': state == 'Paused',
'printing': state == 'Printing',
'cancelling': state == 'Cancelling',
'pausing': False,
'error': state == 'Error',
'ready': state == 'Operational',
'closedOrError': state in ['Error', 'Offline'],
},
},
}
async def _post_command(self,
web_request: WebRequest
) -> Dict:
"""
Request to run some gcode command
"""
commands: List[str] = web_request.get('commands', [])
for command in commands:
logging.info(f'Executing GCode: {command}')
try:
await self.klippy_apis.run_gcode(command)
except self.server.error:
msg = f"Error executing GCode {command}"
logging.exception(msg)
return {}
async def _get_printerprofiles(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Get Printer profiles
"""
return {
'profiles': {
'_default': {
'id': '_default',
'name': 'Default',
'color': 'default',
'model': 'Default',
'default': True,
'current': True,
'heatedBed': 'heater_bed' in self.heaters,
'heatedChamber': 'chamber' in self.heaters,
}
}
}
def load_component(config: ConfigHelper) -> OctoprintCompat:
return OctoprintCompat(config)
+837
View File
@@ -0,0 +1,837 @@
# PanelDue LCD display support
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import serial
import os
import time
import json
import errno
import logging
from collections import deque
from utils import ServerError
from tornado import gen
from tornado.ioloop import IOLoop
# Annotation imports
from typing import (
TYPE_CHECKING,
Deque,
Any,
Tuple,
Optional,
Dict,
List,
Callable,
Coroutine,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from . import klippy_apis
from .file_manager import file_manager
APIComp = klippy_apis.KlippyAPI
FMComp = file_manager.FileManager
FlexCallback = Callable[..., Optional[Coroutine]]
MIN_EST_TIME = 10.
INITIALIZE_TIMEOUT = 10.
class PanelDueError(ServerError):
pass
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
class SerialConnection:
def __init__(self,
config: ConfigHelper,
paneldue: PanelDue
) -> None:
self.ioloop = IOLoop.current()
self.paneldue = paneldue
self.port: str = config.get('serial')
self.baud = config.getint('baud', 57600)
self.partial_input: bytes = b""
self.ser: Optional[serial.Serial] = None
self.fd: Optional[int] = None
self.connected: bool = False
self.send_busy: bool = False
self.send_buffer: bytes = b""
self.attempting_connect: bool = True
self.ioloop.spawn_callback(self._connect)
def disconnect(self, reconnect: bool = False) -> None:
if self.connected:
if self.fd is not None:
self.ioloop.remove_handler(self.fd)
self.fd = None
self.connected = False
if self.ser is not None:
self.ser.close()
self.ser = None
self.partial_input = b""
self.send_buffer = b""
self.paneldue.initialized = False
logging.info("PanelDue Disconnected")
if reconnect and not self.attempting_connect:
self.attempting_connect = True
self.ioloop.call_later(1., self._connect) # type: ignore
async def _connect(self) -> None:
start_time = connect_time = time.time()
while not self.connected:
if connect_time > start_time + 30.:
logging.info("Unable to connect, aborting")
break
logging.info(f"Attempting to connect to: {self.port}")
try:
# XXX - sometimes the port cannot be exclusively locked, this
# would likely be due to a restart where the serial port was
# not correctly closed. Maybe don't use exclusive mode?
self.ser = serial.Serial(
self.port, self.baud, timeout=0, exclusive=True)
except (OSError, IOError, serial.SerialException):
logging.exception(f"Unable to open port: {self.port}")
await gen.sleep(2.)
connect_time += time.time()
continue
self.fd = self.ser.fileno()
fd = self.fd = self.ser.fileno()
os.set_blocking(fd, False)
self.ioloop.add_handler(fd, self._handle_incoming,
IOLoop.READ | IOLoop.ERROR)
self.connected = True
logging.info("PanelDue Connected")
self.attempting_connect = False
def _handle_incoming(self, fd: int, events: int) -> None:
if events & IOLoop.ERROR:
logging.info("PanelDue Connection Error")
self.disconnect(reconnect=True)
return
# Process incoming data using same method as gcode.py
try:
data = os.read(fd, 4096)
except os.error:
return
if not data:
# possibly an error, disconnect
self.disconnect(reconnect=True)
logging.info("serial_display: No data received, disconnecting")
return
# Remove null bytes, separate into lines
data = data.strip(b'\x00')
lines = data.split(b'\n')
lines[0] = self.partial_input + lines[0]
self.partial_input = lines.pop()
for line in lines:
try:
decoded_line = line.strip().decode('utf-8', 'ignore')
self.paneldue.process_line(decoded_line)
except ServerError:
logging.exception(
f"GCode Processing Error: {decoded_line}")
self.paneldue.handle_gcode_response(
f"!! GCode Processing Error: {decoded_line}")
except Exception:
logging.exception("Error during gcode processing")
def send(self, data: bytes) -> None:
self.send_buffer += data
if not self.send_busy:
self.send_busy = True
self.ioloop.spawn_callback(self._do_send)
async def _do_send(self) -> None:
assert self.fd is not None
while self.send_buffer:
if not self.connected:
break
try:
sent = os.write(self.fd, self.send_buffer)
except os.error as e:
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
sent = 0
else:
await gen.sleep(.001)
continue
if sent:
self.send_buffer = self.send_buffer[sent:]
else:
logging.exception(
"Error writing data, closing serial connection")
self.disconnect(reconnect=True)
return
self.send_busy = False
class PanelDue:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.ioloop = IOLoop.current()
self.file_manager: FMComp = \
self.server.lookup_component('file_manager')
self.klippy_apis: APIComp = \
self.server.lookup_component('klippy_apis')
self.kinematics: str = "none"
self.machine_name = config.get('machine_name', "Klipper")
self.firmware_name: str = "Repetier | Klipper"
self.last_message: Optional[str] = None
self.last_gcode_response: Optional[str] = None
self.current_file: str = ""
self.file_metadata: Dict[str, Any] = {}
self.enable_checksum = config.getboolean('enable_checksum', True)
self.debug_queue: Deque[str] = deque(maxlen=100)
# Initialize tracked state.
self.printer_state: Dict[str, Dict[str, Any]] = {
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
'fan': {}, 'display_status': {}, 'print_stats': {},
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
self.extruder_count: int = 0
self.heaters: List[str] = []
self.is_ready: bool = False
self.is_shutdown: bool = False
self.initialized: bool = False
self.cq_busy: bool = False
self.gq_busy: bool = False
self.command_queue: List[Tuple[FlexCallback, Any, Any]] = []
self.gc_queue: List[str] = []
self.last_printer_state: str = 'O'
self.last_update_time: float = 0.
# Set up macros
self.confirmed_gcode: str = ""
self.mbox_sequence: int = 0
self.available_macros: Dict[str, str] = {}
self.confirmed_macros = {
"RESTART": "RESTART",
"FIRMWARE_RESTART": "FIRMWARE_RESTART"}
macros = config.get('macros', None)
if macros is not None:
# The macro's configuration name is the key, whereas the full
# command is the value
macro_list = [m for m in macros.split('\n') if m.strip()]
self.available_macros = {m.split()[0]: m for m in macro_list}
conf_macros = config.get('confirmed_macros', None)
if conf_macros is not None:
# The macro's configuration name is the key, whereas the full
# command is the value
macro_list = [m for m in conf_macros.split('\n') if m.strip()]
self.confirmed_macros = {m.split()[0]: m for m in macro_list}
self.available_macros.update(self.confirmed_macros)
ntkeys = config.get('non_trivial_keys', "Klipper state")
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
self.ser_conn = SerialConnection(config, self)
logging.info("PanelDue Configured")
# Register server events
self.server.register_event_handler(
"server:klippy_ready", self._process_klippy_ready)
self.server.register_event_handler(
"server:klippy_shutdown", self._process_klippy_shutdown)
self.server.register_event_handler(
"server:klippy_disconnect", self._process_klippy_disconnect)
self.server.register_event_handler(
"server:status_update", self.handle_status_update)
self.server.register_event_handler(
"server:gcode_response", self.handle_gcode_response)
self.server.register_remote_method(
"paneldue_beep", self.paneldue_beep)
# These commands are directly executued on the server and do not to
# make a request to Klippy
self.direct_gcodes: Dict[str, FlexCallback] = {
'M20': self._run_paneldue_M20,
'M30': self._run_paneldue_M30,
'M36': self._run_paneldue_M36,
'M408': self._run_paneldue_M408
}
# These gcodes require special parsing or handling prior to being
# sent via Klippy's "gcode/script" api command.
self.special_gcodes: Dict[str, Callable[[List[str]], str]] = {
'M0': lambda args: "CANCEL_PRINT",
'M23': self._prepare_M23,
'M24': lambda args: "RESUME",
'M25': lambda args: "PAUSE",
'M32': self._prepare_M32,
'M98': self._prepare_M98,
'M120': lambda args: "SAVE_GCODE_STATE STATE=PANELDUE",
'M121': lambda args: "RESTORE_GCODE_STATE STATE=PANELDUE",
'M290': self._prepare_M290,
'M292': self._prepare_M292,
'M999': lambda args: "FIRMWARE_RESTART"
}
async def _process_klippy_ready(self) -> None:
# Request "info" and "configfile" status
retries = 10
printer_info = cfg_status = {}
while retries:
try:
printer_info = await self.klippy_apis.get_klippy_info()
cfg_status = await self.klippy_apis.query_objects(
{'configfile': None})
except self.server.error:
logging.exception("PanelDue initialization request failed")
retries -= 1
if not retries:
raise
await gen.sleep(1.)
continue
break
self.firmware_name = "Repetier | Klipper " + \
printer_info['software_version']
config: Dict[str, Any] = cfg_status.get(
'configfile', {}).get('config', {})
printer_cfg: Dict[str, Any] = config.get('printer', {})
self.kinematics = printer_cfg.get('kinematics', "none")
logging.info(
f"PanelDue Config Received:\n"
f"Firmware Name: {self.firmware_name}\n"
f"Kinematics: {self.kinematics}\n"
f"Printer Config: {config}\n")
# Initalize printer state and make subscription request
self.printer_state = {
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
'fan': {}, 'display_status': {}, 'print_stats': {},
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
sub_args = {k: None for k in self.printer_state.keys()}
self.extruder_count = 0
self.heaters = []
for cfg in config:
if cfg.startswith("extruder"):
self.extruder_count += 1
self.printer_state[cfg] = {}
self.heaters.append(cfg)
sub_args[cfg] = None
elif cfg == "heater_bed":
self.printer_state[cfg] = {}
self.heaters.append(cfg)
sub_args[cfg] = None
try:
status: Dict[str, Any]
status = await self.klippy_apis.subscribe_objects(sub_args)
except self.server.error:
logging.exception("Unable to complete subscription request")
else:
self.printer_state.update(status)
self.is_shutdown = False
self.is_ready = True
def _process_klippy_shutdown(self) -> None:
self.is_shutdown = True
def _process_klippy_disconnect(self) -> None:
# Tell the PD that the printer is "off"
self.write_response({'status': 'O'})
self.last_printer_state = 'O'
self.is_shutdown = self.is_shutdown = False
def handle_status_update(self, status: Dict[str, Any]) -> None:
for obj, items in status.items():
if obj in self.printer_state:
self.printer_state[obj].update(items)
else:
self.printer_state[obj] = items
def paneldue_beep(self, frequency: int, duration: float) -> None:
duration = int(duration * 1000.)
self.write_response(
{'beep_freq': frequency, 'beep_length': duration})
def process_line(self, line: str) -> None:
self.debug_queue.append(line)
# If we find M112 in the line then skip verification
if "M112" in line.upper():
self.ioloop.spawn_callback(self.klippy_apis.emergency_stop)
return
if self.enable_checksum:
# Get line number
line_index = line.find(' ')
try:
line_no: Optional[int] = int(line[1:line_index])
except Exception:
line_index = -1
line_no = None
# Verify checksum
cs_index = line.rfind('*')
try:
checksum = int(line[cs_index+1:])
except Exception:
# Invalid checksum, do not process
msg = "!! Invalid Checksum"
if line_no is not None:
msg += f" Line Number: {line_no}"
logging.exception("PanelDue: " + msg)
raise PanelDueError(msg)
# Checksum is calculated by XORing every byte in the line other
# than the checksum itself
calculated_cs = 0
for c in line[:cs_index]:
calculated_cs ^= ord(c)
if calculated_cs & 0xFF != checksum:
msg = "!! Invalid Checksum"
if line_no is not None:
msg += f" Line Number: {line_no}"
logging.info("PanelDue: " + msg)
raise PanelDueError(msg)
script = line[line_index+1:cs_index]
else:
script = line
# Execute the gcode. Check for special RRF gcodes that
# require special handling
parts = script.split()
cmd = parts[0].strip()
if cmd in ["M23", "M30", "M32", "M36", "M37", "M98"]:
arg = script[len(cmd):].strip()
parts = [cmd, arg]
# Check for commands that query state and require immediate response
if cmd in self.direct_gcodes:
params: Dict[str, Any] = {}
for p in parts[1:]:
if p[0] not in "PSR":
params["arg_p"] = p.strip(" \"\t\n")
continue
arg = p[0].lower()
try:
val = int(p[1:].strip()) if arg in "sr" \
else p[1:].strip(" \"\t\n")
except Exception:
msg = f"paneldue: Error parsing direct gcode {script}"
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
return
params[f"arg_{arg}"] = val
func = self.direct_gcodes[cmd]
self.queue_command(func, **params)
return
# Prepare GCodes that require special handling
if cmd in self.special_gcodes:
sgc_func = self.special_gcodes[cmd]
script = sgc_func(parts[1:])
if not script:
return
self.queue_gcode(script)
def queue_gcode(self, script: str) -> None:
self.gc_queue.append(script)
if not self.gq_busy:
self.gq_busy = True
self.ioloop.spawn_callback(self._process_gcode_queue)
async def _process_gcode_queue(self) -> None:
while self.gc_queue:
script = self.gc_queue.pop(0)
try:
if script in RESTART_GCODES:
await self.klippy_apis.do_restart(script)
else:
await self.klippy_apis.run_gcode(script)
except self.server.error:
msg = f"Error executing script {script}"
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
self.gq_busy = False
def queue_command(self, cmd: FlexCallback, *args, **kwargs) -> None:
self.command_queue.append((cmd, args, kwargs))
if not self.cq_busy:
self.cq_busy = True
self.ioloop.spawn_callback(self._process_command_queue)
async def _process_command_queue(self) -> None:
while self.command_queue:
cmd, args, kwargs = self.command_queue.pop(0)
try:
ret = cmd(*args, **kwargs)
if ret is not None:
await ret
except Exception:
logging.exception("Error processing command")
self.cq_busy = False
def _clean_filename(self, filename: str) -> str:
# Remove quotes and whitespace
filename.strip(" \"\t\n")
# Remove drive number
if filename.startswith("0:/"):
filename = filename[3:]
# Remove initial "gcodes" folder. This is necessary
# due to the HACK in the paneldue_M20 gcode.
if filename.startswith("gcodes/"):
filename = filename[6:]
elif filename.startswith("/gcodes/"):
filename = filename[7:]
# Start with a "/" so the gcode parser can correctly
# handle files that begin with digits or special chars
if filename[0] != "/":
filename = "/" + filename
return filename
def _prepare_M23(self, args: List[str]) -> str:
filename = self._clean_filename(args[0])
return f"M23 {filename}"
def _prepare_M32(self, args: List[str]) -> str:
filename = self._clean_filename(args[0])
# Escape existing double quotes in the file name
filename = filename.replace("\"", "\\\"")
return f"SDCARD_PRINT_FILE FILENAME=\"{filename}\""
def _prepare_M98(self, args: List[str]) -> str:
macro = args[0][1:].strip(" \"\t\n")
name_start = macro.rfind('/') + 1
macro = macro[name_start:]
cmd = self.available_macros.get(macro)
if cmd is None:
raise PanelDueError(f"Macro {macro} invalid")
if macro in self.confirmed_macros:
self._create_confirmation(macro, cmd)
cmd = ""
return cmd
def _prepare_M290(self, args: List[str]) -> str:
# args should in in the format Z0.02
offset = args[0][1:].strip()
return f"SET_GCODE_OFFSET Z_ADJUST={offset} MOVE=1"
def _prepare_M292(self, args: List[str]) -> str:
p_val = int(args[0][1])
if p_val == 0:
cmd = self.confirmed_gcode
self.confirmed_gcode = ""
return cmd
return ""
def _create_confirmation(self, name: str, gcode: str) -> None:
self.mbox_sequence += 1
self.confirmed_gcode = gcode
title = "Confirmation Dialog"
msg = f"Please confirm your intent to run {name}." \
" Press OK to continue, or CANCEL to abort."
mbox: Dict[str, Any] = {}
mbox['msgBox.mode'] = 3
mbox['msgBox.msg'] = msg
mbox['msgBox.seq'] = self.mbox_sequence
mbox['msgBox.title'] = title
mbox['msgBox.controls'] = 0
mbox['msgBox.timeout'] = 0
logging.debug(f"Creating PanelDue Confirmation: {mbox}")
self.write_response(mbox)
def handle_gcode_response(self, response: str) -> None:
# Only queue up "non-trivial" gcode responses. At the
# moment we'll handle state changes and errors
if "Klipper state" in response \
or response.startswith('!!'):
self.last_gcode_response = response
else:
for key in self.non_trivial_keys:
if key in response:
self.last_gcode_response = response
return
def write_response(self, response: Dict[str, Any]) -> None:
byte_resp = json.dumps(response) + "\r\n"
self.ser_conn.send(byte_resp.encode())
def _get_printer_status(self) -> str:
# PanelDue States applicable to Klipper:
# I = idle, P = printing from SD, S = stopped (shutdown),
# C = starting up (not ready), A = paused, D = pausing,
# B = busy
if self.is_shutdown:
return 'S'
printer_state = self.printer_state
sd_state: str
sd_state = printer_state['print_stats'].get('state', "standby")
if sd_state == "printing":
if self.last_printer_state == 'A':
# Resuming
return 'R'
# Printing
return 'P'
elif sd_state == "paused":
p_active = printer_state['idle_timeout'].get(
'state', 'Idle') == "Printing"
if p_active and self.last_printer_state != 'A':
# Pausing
return 'D'
else:
# Paused
return 'A'
return 'I'
def _run_paneldue_M408(self,
arg_r: Optional[int] = None,
arg_s: int = 1
) -> None:
response: Dict[str, Any] = {}
sequence = arg_r
response_type = arg_s
curtime = self.ioloop.time()
if curtime - self.last_update_time > INITIALIZE_TIMEOUT:
self.initialized = False
self.last_update_time = curtime
if not self.initialized:
response['dir'] = "/macros"
response['files'] = list(self.available_macros.keys())
self.initialized = True
if not self.is_ready:
self.last_printer_state = 'O'
response['status'] = self.last_printer_state
self.write_response(response)
return
if sequence is not None and self.last_gcode_response:
# Send gcode responses
response['seq'] = sequence + 1
response['resp'] = self.last_gcode_response
self.last_gcode_response = None
if response_type == 1:
# Extended response Request
response['myName'] = self.machine_name
response['firmwareName'] = self.firmware_name
response['numTools'] = self.extruder_count
response['geometry'] = self.kinematics
response['axes'] = 3
p_state = self.printer_state
self.last_printer_state = self._get_printer_status()
response['status'] = self.last_printer_state
response['babystep'] = round(p_state['gcode_move'].get(
'homing_origin', [0., 0., 0., 0.])[2], 3)
# Current position
pos: List[float]
homed_pos: str
sfactor: float
pos = p_state['toolhead'].get('position', [0., 0., 0., 0.])
response['pos'] = [round(p, 2) for p in pos[:3]]
homed_pos = p_state['toolhead'].get('homed_axes', "")
response['homed'] = [int(a in homed_pos) for a in "xyz"]
sfactor = round(p_state['gcode_move'].get('speed_factor', 1.) * 100, 2)
response['sfactor'] = sfactor
# Print Progress Tracking
sd_status = p_state['virtual_sdcard']
print_stats = p_state['print_stats']
fname: str = print_stats.get('filename', "")
sd_print_state: Optional[str] = print_stats.get('state')
if sd_print_state in ['printing', 'paused']:
# We know a file has been loaded, initialize metadata
if self.current_file != fname:
self.current_file = fname
self.file_metadata = self.file_manager.get_file_metadata(fname)
progress: float = sd_status.get('progress', 0)
# progress and print tracking
if progress:
response['fraction_printed'] = round(progress, 3)
est_time: float = self.file_metadata.get('estimated_time', 0)
if est_time > MIN_EST_TIME:
# file read estimate
times_left = [int(est_time - est_time * progress)]
# filament estimate
est_total_fil: Optional[float]
est_total_fil = self.file_metadata.get('filament_total')
if est_total_fil:
cur_filament: float = print_stats.get(
'filament_used', 0.)
fpct = min(1., cur_filament / est_total_fil)
times_left.append(int(est_time - est_time * fpct))
# object height estimate
obj_height: Optional[float]
obj_height = self.file_metadata.get('object_height')
if obj_height:
cur_height: float = p_state['gcode_move'].get(
'gcode_position', [0., 0., 0., 0.])[2]
hpct = min(1., cur_height / obj_height)
times_left.append(int(est_time - est_time * hpct))
else:
# The estimated time is not in the metadata, however we
# can still provide an estimate based on file progress
duration: float = print_stats.get('print_duration', 0.)
times_left = [int(duration / progress - duration)]
response['timesLeft'] = times_left
else:
# clear filename and metadata
self.current_file = ""
self.file_metadata = {}
fan_speed: Optional[float] = p_state['fan'].get('speed')
if fan_speed is not None:
response['fanPercent'] = [round(fan_speed * 100, 1)]
if self.extruder_count > 0:
extruder_name: Optional[str]
extruder_name = p_state['toolhead'].get('extruder')
if extruder_name is not None:
tool = 0
if extruder_name != "extruder":
tool = int(extruder_name[-1])
response['tool'] = tool
# Report Heater Status
efactor: float = round(p_state['gcode_move'].get(
'extrude_factor', 1.) * 100., 2)
for name in self.heaters:
temp: float = round(p_state[name].get('temperature', 0.0), 1)
target: float = round(p_state[name].get('target', 0.0), 1)
response.setdefault('heaters', []).append(temp)
response.setdefault('active', []).append(target)
response.setdefault('standby', []).append(target)
response.setdefault('hstat', []).append(2 if target else 0)
if name.startswith('extruder'):
response.setdefault('efactor', []).append(efactor)
response.setdefault('extr', []).append(round(pos[3], 2))
# Display message (via M117)
msg: str = p_state['display_status'].get('message', "")
if msg and msg != self.last_message:
response['message'] = msg
# reset the message so it only shows once. The paneldue
# is strange about this, and displays it as a full screen
# notification
self.last_message = msg
self.write_response(response)
def _run_paneldue_M20(self, arg_p: str, arg_s: int = 0) -> None:
response_type = arg_s
if response_type != 2:
logging.info(
f"Cannot process response type {response_type} in M20")
return
path = arg_p
# Strip quotes if they exist
path = path.strip('\"')
# Path should come in as "0:/macros, or 0:/<gcode_folder>". With
# repetier compatibility enabled, the default folder is root,
# ie. "0:/"
if path.startswith("0:/"):
path = path[2:]
response: Dict[str, Any] = {'dir': path}
response['files'] = []
if path == "/macros":
response['files'] = list(self.available_macros.keys())
else:
# HACK: The PanelDue has a bug where it does not correctly detect
# subdirectories if we return the root as "/". Moonraker can
# support a "gcodes" directory, however we must choose between this
# support or disabling RRF specific gcodes (this is done by
# identifying as Repetier).
# The workaround below converts both "/" and "/gcodes" paths to
# "gcodes".
if path == "/":
response['dir'] = "/gcodes"
path = "gcodes"
elif path.startswith("/gcodes"):
path = path[1:]
flist = self.file_manager.list_dir(path, simple_format=True)
if flist:
response['files'] = flist
self.write_response(response)
async def _run_paneldue_M30(self, arg_p: str = "") -> None:
# Delete a file. Clean up the file name and make sure
# it is relative to the "gcodes" root.
path = arg_p
path = path.strip('\"')
if path.startswith("0:/"):
path = path[3:]
elif path[0] == "/":
path = path[1:]
if not path.startswith("gcodes/"):
path = "gcodes/" + path
await self.file_manager.delete_file(path)
def _run_paneldue_M36(self, arg_p: Optional[str] = None) -> None:
response: Dict[str, Any] = {}
filename: Optional[str] = arg_p
sd_status = self.printer_state.get('virtual_sdcard', {})
print_stats = self.printer_state.get('print_stats', {})
if filename is None:
# PanelDue is requesting file information on a
# currently printed file
active = False
if sd_status and print_stats:
filename = print_stats['filename']
active = sd_status['is_active']
if not filename or not active:
# Either no file printing or no virtual_sdcard
response['err'] = 1
self.write_response(response)
return
else:
response['fileName'] = filename.split("/")[-1]
# For consistency make sure that the filename begins with the
# "gcodes/" root. The M20 HACK should add this in some cases.
# Ideally we would add support to the PanelDue firmware that
# indicates Moonraker supports a "gcodes" directory.
if filename[0] == "/":
filename = filename[1:]
if not filename.startswith("gcodes/"):
filename = "gcodes/" + filename
metadata: Dict[str, Any] = \
self.file_manager.get_file_metadata(filename)
if metadata:
response['err'] = 0
response['size'] = metadata['size']
# workaround for PanelDue replacing the first "T" found
response['lastModified'] = "T" + time.ctime(metadata['modified'])
slicer: Optional[str] = metadata.get('slicer')
if slicer is not None:
response['generatedBy'] = slicer
height: Optional[float] = metadata.get('object_height')
if height is not None:
response['height'] = round(height, 2)
layer_height: Optional[float] = metadata.get('layer_height')
if layer_height is not None:
response['layerHeight'] = round(layer_height, 2)
filament: Optional[float] = metadata.get('filament_total')
if filament is not None:
response['filament'] = [round(filament, 1)]
est_time: Optional[float] = metadata.get('estimated_time')
if est_time is not None:
response['printTime'] = int(est_time + .5)
else:
response['err'] = 1
self.write_response(response)
def close(self) -> None:
self.ser_conn.disconnect()
msg = "\nPanelDue GCode Dump:"
for i, gc in enumerate(self.debug_queue):
msg += f"\nSequence {i}: {gc}"
logging.debug(msg)
def load_component(config: ConfigHelper) -> PanelDue:
return PanelDue(config)
+761
View File
@@ -0,0 +1,761 @@
# Raspberry Pi Power Control
#
# Copyright (C) 2020 Jordan Ruthe <jordanruthe@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import sys
import logging
import json
import struct
import socket
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado.locks import Lock
from tornado.httpclient import AsyncHTTPClient
from tornado.escape import json_decode
# Annotation imports
from typing import (
TYPE_CHECKING,
Type,
List,
Any,
Optional,
Dict,
Coroutine,
Tuple,
Union,
)
# Special handling for gpiod import
HAS_GPIOD = True
DIST_PATH = "/usr/lib/python3/dist-packages"
if os.path.exists(DIST_PATH):
sys.path.insert(0, DIST_PATH)
try:
import gpiod
except ImportError:
HAS_GPIOD = False
sys.path.pop(0)
else:
HAS_GPIOD = False
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
from . import klippy_apis
APIComp = klippy_apis.KlippyAPI
class PrinterPower:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
if not HAS_GPIOD:
self.server.add_warning(
"Unable to load gpiod library, GPIO power "
"devices will not be loaded")
self.chip_factory = GpioChipFactory()
self.devices: Dict[str, PowerDevice] = {}
prefix_sections = config.get_prefix_sections("power")
logging.info(f"Power component loading devices: {prefix_sections}")
dev_types = {
"gpio": GpioDevice,
"tplink_smartplug": TPLinkSmartPlug,
"tasmota": Tasmota,
"shelly": Shelly,
"homeseer": HomeSeer,
"homeassistant": HomeAssistant,
"loxonev1": Loxonev1
}
try:
for section in prefix_sections:
cfg = config[section]
dev_type: str = cfg.get("type")
dev_class: Optional[Type[PowerDevice]]
dev_class = dev_types.get(dev_type)
if dev_class is None:
raise config.error(f"Unsupported Device Type: {dev_type}")
dev = dev_class(cfg)
if isinstance(dev, GpioDevice):
if not HAS_GPIOD:
continue
dev.configure_line(cfg, self.chip_factory)
self.devices[dev.get_name()] = dev
except Exception:
self.chip_factory.close()
raise
self.server.register_endpoint(
"/machine/device_power/devices", ['GET'],
self._handle_list_devices)
self.server.register_endpoint(
"/machine/device_power/status", ['GET'],
self._handle_batch_power_request)
self.server.register_endpoint(
"/machine/device_power/on", ['POST'],
self._handle_batch_power_request)
self.server.register_endpoint(
"/machine/device_power/off", ['POST'],
self._handle_batch_power_request)
self.server.register_endpoint(
"/machine/device_power/device", ['GET', 'POST'],
self._handle_single_power_request)
self.server.register_remote_method(
"set_device_power", self.set_device_power)
self.server.register_event_handler(
"server:klippy_shutdown", self._handle_klippy_shutdown)
self.server.register_notification("power:power_changed")
IOLoop.current().spawn_callback(
self._initalize_devices, list(self.devices.values()))
async def _check_klippy_printing(self) -> bool:
kapis: APIComp = self.server.lookup_component('klippy_apis')
result: Dict[str, Any] = await kapis.query_objects(
{'print_stats': None}, default={})
pstate = result.get('print_stats', {}).get('state', "").lower()
return pstate == "printing"
async def _initalize_devices(self,
inital_devs: List[PowerDevice]
) -> None:
for dev in inital_devs:
ret = dev.initialize()
if ret is not None:
await ret
async def _handle_klippy_shutdown(self) -> None:
for name, dev in self.devices.items():
if dev.has_off_when_shutdown():
logging.info(
f"Powering off device [{name}] due to"
" klippy shutdown")
await self._process_request(dev, "off")
async def _handle_list_devices(self,
web_request: WebRequest
) -> Dict[str, Any]:
dev_list = [d.get_device_info() for d in self.devices.values()]
output = {"devices": dev_list}
return output
async def _handle_single_power_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
dev_name: str = web_request.get_str('device')
req_action = web_request.get_action()
if dev_name not in self.devices:
raise self.server.error(f"No valid device named {dev_name}")
dev = self.devices[dev_name]
if req_action == 'GET':
action = "status"
elif req_action == "POST":
action = web_request.get_str('action').lower()
if action not in ["on", "off", "toggle"]:
raise self.server.error(
f"Invalid requested action '{action}'")
result = await self._process_request(dev, action)
return {dev_name: result}
async def _handle_batch_power_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
args = web_request.get_args()
ep = web_request.get_endpoint()
if not args:
raise self.server.error("No arguments provided")
requested_devs = {k: self.devices.get(k, None) for k in args}
result = {}
req = ep.split("/")[-1]
for name, device in requested_devs.items():
if device is not None:
result[name] = await self._process_request(device, req)
else:
result[name] = "device_not_found"
return result
async def _process_request(self,
device: PowerDevice,
req: str
) -> str:
ret = device.refresh_status()
if ret is not None:
await ret
dev_info = device.get_device_info()
if req == "toggle":
req = "on" if dev_info['status'] == "off" else "off"
if req in ["on", "off"]:
cur_state: str = dev_info['status']
if req == cur_state:
# device is already in requested state, do nothing
return cur_state
printing = await self._check_klippy_printing()
if device.get_locked_while_printing() and printing:
raise self.server.error(
f"Unable to change power for {device.get_name()} "
"while printing")
ret = device.set_power(req)
if ret is not None:
await ret
dev_info = device.get_device_info()
self.server.send_event("power:power_changed", dev_info)
device.run_power_changed_action()
elif req != "status":
raise self.server.error(f"Unsupported power request: {req}")
return dev_info['status']
def set_device_power(self, device: str, state: str) -> None:
status: Optional[str] = None
if isinstance(state, bool):
status = "on" if state else "off"
elif isinstance(state, str):
status = state.lower()
if status in ["true", "false"]:
status = "on" if status == "true" else "off"
if status not in ["on", "off"]:
logging.info(f"Invalid state received: {state}")
return
if device not in self.devices:
logging.info(f"No device found: {device}")
return
ioloop = IOLoop.current()
ioloop.spawn_callback(
self._process_request, self.devices[device], status)
async def add_device(self, name: str, device: PowerDevice) -> None:
if name in self.devices:
raise self.server.error(
f"Device [{name}] already configured")
ret = device.initialize()
if ret is not None:
await ret
self.devices[name] = device
async def close(self) -> None:
for device in self.devices.values():
ret = device.close()
if ret is not None:
await ret
self.chip_factory.close()
class PowerDevice:
def __init__(self, config: ConfigHelper) -> None:
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.server = config.get_server()
self.name = name_parts[1]
self.type: str = config.get('type')
self.state: str = "init"
self.locked_while_printing = config.getboolean(
'locked_while_printing', False)
self.off_when_shutdown = config.getboolean('off_when_shutdown', False)
self.restart_delay = 1.
self.klipper_restart = config.getboolean(
'restart_klipper_when_powered', False)
if self.klipper_restart:
self.restart_delay = config.getfloat('restart_delay', 1.)
if self.restart_delay < .000001:
raise config.error("Option 'restart_delay' must be above 0.0")
def get_name(self) -> str:
return self.name
def get_device_info(self) -> Dict[str, Any]:
return {
'device': self.name,
'status': self.state,
'locked_while_printing': self.locked_while_printing,
'type': self.type
}
def get_locked_while_printing(self) -> bool:
return self.locked_while_printing
def run_power_changed_action(self) -> None:
if self.state == "on" and self.klipper_restart:
ioloop = IOLoop.current()
kapis: APIComp = self.server.lookup_component("klippy_apis")
ioloop.call_later(
self.restart_delay, kapis.do_restart, # type:ignore
"FIRMWARE_RESTART")
def has_off_when_shutdown(self) -> bool:
return self.off_when_shutdown
def initialize(self) -> Optional[Coroutine]:
raise NotImplementedError
def refresh_status(self) -> Optional[Coroutine]:
raise NotImplementedError
def set_power(self, state: str) -> Optional[Coroutine]:
raise NotImplementedError
def close(self) -> Optional[Coroutine]:
pass
class HTTPDevice(PowerDevice):
def __init__(self,
config: ConfigHelper,
default_port: int = -1,
default_user: str = "",
default_password: str = "",
default_protocol: str = "http"
) -> None:
super().__init__(config)
self.client = AsyncHTTPClient()
self.request_mutex = Lock()
self.addr: str = config.get("address")
self.port = config.getint("port", default_port)
self.user = config.get("user", default_user)
self.password = config.get("password", default_password)
self.protocol = config.get("protocol", default_protocol)
async def initialize(self) -> None:
await self.refresh_status()
async def _send_http_command(self,
url: str,
command: str
) -> Dict[str, Any]:
try:
response = await self.client.fetch(url)
data = json_decode(response.body)
except Exception:
msg = f"Error sending '{self.type}' command: {command}"
logging.exception(msg)
raise self.server.error(msg)
return data
async def _send_power_request(self, state: str) -> str:
raise NotImplementedError(
"_send_power_request must be implemented by children")
async def _send_status_request(self) -> str:
raise NotImplementedError(
"_send_status_request must be implemented by children")
async def refresh_status(self) -> None:
async with self.request_mutex:
try:
state = await self._send_status_request()
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
async def set_power(self, state):
async with self.request_mutex:
try:
state = await self._send_power_request(state)
except Exception:
self.state = "error"
msg = f"Error Setting Device Status: {self.name} to {state}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
class GpioChipFactory:
def __init__(self) -> None:
self.chips: Dict[str, gpiod.Chip] = {}
def get_gpio_chip(self, chip_name) -> gpiod.Chip:
if chip_name in self.chips:
return self.chips[chip_name]
chip = gpiod.Chip(chip_name, gpiod.Chip.OPEN_BY_NAME)
self.chips[chip_name] = chip
return chip
def close(self) -> None:
for chip in self.chips.values():
chip.close()
class GpioDevice(PowerDevice):
def __init__(self, config: ConfigHelper):
super().__init__(config)
self.initial_state = config.getboolean('initial_state', False)
def configure_line(self,
config: ConfigHelper,
chip_factory: GpioChipFactory
) -> None:
pin, chip_id, invert = self._parse_pin(config)
try:
chip = chip_factory.get_gpio_chip(chip_id)
self.line = chip.get_line(pin)
if invert:
self.line.request(
consumer="moonraker", type=gpiod.LINE_REQ_DIR_OUT,
flags=gpiod.LINE_REQ_FLAG_ACTIVE_LOW)
else:
self.line.request(
consumer="moonraker", type=gpiod.LINE_REQ_DIR_OUT)
except Exception:
self.state = "error"
logging.exception(
f"Unable to init {pin}. Make sure the gpio is not in "
"use by another program or exported by sysfs.")
raise config.error("Power GPIO Config Error")
def _parse_pin(self, config: ConfigHelper) -> Tuple[int, str, bool]:
pin = cfg_pin = config.get("pin")
invert = False
if pin[0] == "!":
pin = pin[1:]
invert = True
chip_id: str = "gpiochip0"
pin_parts = pin.split("/")
if len(pin_parts) == 2:
chip_id, pin = pin_parts
elif len(pin_parts) == 1:
pin = pin_parts[0]
# Verify pin
if not chip_id.startswith("gpiochip") or \
not chip_id[-1].isdigit() or \
not pin.startswith("gpio") or \
not pin[4:].isdigit():
raise config.error(
f"Invalid Power Pin configuration: {cfg_pin}")
pin_id = int(pin[4:])
return pin_id, chip_id, invert
def initialize(self) -> None:
self.set_power("on" if self.initial_state else "off")
def refresh_status(self) -> None:
pass
def set_power(self, state) -> None:
try:
self.line.set_value(int(state == "on"))
except Exception:
self.state = "error"
msg = f"Error Toggling Device Power: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
def close(self) -> None:
self.line.release()
# This implementation based off the work tplink_smartplug
# script by Lubomir Stroetmann available at:
#
# https://github.com/softScheck/tplink-smartplug
#
# Copyright 2016 softScheck GmbH
class TPLinkSmartPlug(PowerDevice):
START_KEY = 0xAB
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config)
self.request_mutex = Lock()
self.addr: List[str] = config.get("address").split('/')
self.port = config.getint("port", 9999)
async def _send_tplink_command(self,
command: str
) -> Dict[str, Any]:
out_cmd: Dict[str, Any] = {}
if command in ["on", "off"]:
out_cmd = {
'system': {'set_relay_state': {'state': int(command == "on")}}
}
# TPLink device controls multiple devices
if len(self.addr) == 2:
sysinfo = await self._send_tplink_command("info")
dev_id = sysinfo["system"]["get_sysinfo"]["deviceId"]
out_cmd["context"] = {
'child_ids': [f"{dev_id}{int(self.addr[1]):02}"]
}
elif command == "info":
out_cmd = {'system': {'get_sysinfo': {}}}
else:
raise self.server.error(f"Invalid tplink command: {command}")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
stream = IOStream(s)
try:
await stream.connect((self.addr[0], self.port))
await stream.write(self._encrypt(out_cmd))
data = await stream.read_bytes(2048, partial=True)
length: int = struct.unpack(">I", data[:4])[0]
data = data[4:]
retries = 5
remaining = length - len(data)
while remaining and retries:
data += await stream.read_bytes(remaining)
remaining = length - len(data)
retries -= 1
if not retries:
raise self.server.error("Unable to read tplink packet")
except Exception:
msg = f"Error sending tplink command: {command}"
logging.exception(msg)
raise self.server.error(msg)
finally:
stream.close()
return json.loads(self._decrypt(data))
def _encrypt(self, outdata: Dict[str, Any]) -> bytes:
data = json.dumps(outdata)
key = self.START_KEY
res = struct.pack(">I", len(data))
for c in data:
val = key ^ ord(c)
key = val
res += bytes([val])
return res
def _decrypt(self, data: bytes) -> str:
key: int = self.START_KEY
res: str = ""
for c in data:
val = key ^ c
key = c
res += chr(val)
return res
async def initialize(self) -> None:
await self.refresh_status()
async def refresh_status(self) -> None:
async with self.request_mutex:
try:
state: str
res = await self._send_tplink_command("info")
if len(self.addr) == 2:
# TPLink device controls multiple devices
children: Dict[int, Any]
children = res['system']['get_sysinfo']['children']
state = children[int(self.addr[1])]['state']
else:
state = res['system']['get_sysinfo']['relay_state']
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = "on" if state else "off"
async def set_power(self, state) -> None:
async with self.request_mutex:
err: int
try:
res = await self._send_tplink_command(state)
err = res['system']['set_relay_state']['err_code']
except Exception:
err = 1
logging.exception(f"Power Toggle Error: {self.name}")
if err:
self.state = "error"
raise self.server.error(
f"Error Toggling Device Power: {self.name}")
self.state = state
class Tasmota(HTTPDevice):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config, default_password="")
self.output_id = config.getint("output_id", 1)
self.timer = config.get("timer", "")
async def _send_tasmota_command(self,
command: str,
password: Optional[str] = None
) -> Dict[str, Any]:
if command in ["on", "off"]:
out_cmd = f"Power{self.output_id}%20{command}"
if self.timer != "" and command == "off":
out_cmd = f"Backlog%20Delay%20{self.timer}0%3B%20{out_cmd}"
elif command == "info":
out_cmd = f"Power{self.output_id}"
else:
raise self.server.error(f"Invalid tasmota command: {command}")
url = f"http://{self.addr}/cm?user=admin&password=" \
f"{self.password}&cmnd={out_cmd}"
return await self._send_http_command(url, command)
async def _send_status_request(self) -> str:
res = await self._send_tasmota_command("info")
try:
state: str = res[f"POWER{self.output_id}"].lower()
except KeyError as e:
if self.output_id == 1:
state = res[f"POWER"].lower()
else:
raise KeyError(e)
return state
async def _send_power_request(self, state: str) -> str:
res = await self._send_tasmota_command(state)
if self.timer == "" or state != "off":
try:
state = res[f"POWER{self.output_id}"].lower()
except KeyError as e:
if self.output_id == 1:
state = res[f"POWER"].lower()
else:
raise KeyError(e)
return state
class Shelly(HTTPDevice):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config, default_user="admin", default_password="")
self.output_id = config.getint("output_id", 0)
self.timer = config.get("timer", "")
async def _send_shelly_command(self, command: str) -> Dict[str, Any]:
if command == "on":
out_cmd = f"relay/{self.output_id}?turn={command}"
elif command == "off":
if self.timer != "":
out_cmd = f"relay/{self.output_id}?turn=on&timer={self.timer}"
else:
out_cmd = f"relay/{self.output_id}?turn={command}"
elif command == "info":
out_cmd = f"relay/{self.output_id}"
else:
raise self.server.error(f"Invalid shelly command: {command}")
if self.password != "":
out_pwd = f"{self.user}:{self.password}@"
else:
out_pwd = f""
url = f"http://{out_pwd}{self.addr}/{out_cmd}"
return await self._send_http_command(url, command)
async def _send_status_request(self) -> str:
res = await self._send_shelly_command("info")
state: str = res[f"ison"]
timer_remaining = res[f"timer_remaining"] if self.timer != "" else 0
return "on" if state and timer_remaining == 0 else "off"
async def _send_power_request(self, state: str) -> str:
res = await self._send_shelly_command(state)
state = res[f"ison"]
timer_remaining = res[f"timer_remaining"] if self.timer != "" else 0
return "on" if state and timer_remaining == 0 else "off"
class HomeSeer(HTTPDevice):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config, default_user="admin", default_password="")
self.device = config.getint("device")
async def _send_homeseer(self,
request: str,
additional: str = ""
) -> Dict[str, Any]:
url = (f"http://{self.user}:{self.password}@{self.addr}"
f"/JSON?user={self.user}&pass={self.password}"
f"&request={request}&ref={self.device}&{additional}")
return await self._send_http_command(url, request)
async def _send_status_request(self) -> str:
res = await self._send_homeseer("getstatus")
return res[f"Devices"][0]["status"].lower()
async def _send_power_request(self, state: str) -> str:
if state == "on":
state_hs = "On"
elif state == "off":
state_hs = "Off"
res = await self._send_homeseer("controldevicebylabel",
f"label={state_hs}")
return state
class HomeAssistant(HTTPDevice):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config, default_port=8123)
self.device: str = config.get("device")
self.token: str = config.get("token")
self.domain: str = config.get("domain", "switch")
async def _send_homeassistant_command(self,
command: str
) -> Dict[Union[str, int], Any]:
if command == "on":
out_cmd = f"api/services/{self.domain}/turn_on"
body = {"entity_id": self.device}
method = "POST"
elif command == "off":
out_cmd = f"api/services/{self.domain}/turn_off"
body = {"entity_id": self.device}
method = "POST"
elif command == "info":
out_cmd = f"api/states/{self.device}"
method = "GET"
else:
raise self.server.error(
f"Invalid homeassistant command: {command}")
url = f"{self.protocol}://{self.addr}:{self.port}/{out_cmd}"
headers = {
'Authorization': f'Bearer {self.token}',
'Content-Type': 'application/json'
}
try:
if (method == "POST"):
response = await self.client.fetch(
url, method="POST", body=json.dumps(body), headers=headers)
else:
response = await self.client.fetch(
url, method="GET", headers=headers)
data: Dict[Union[str, int], Any] = json_decode(response.body)
except Exception:
msg = f"Error sending homeassistant command: {command}"
logging.exception(msg)
raise self.server.error(msg)
return data
async def _send_status_request(self) -> str:
res = await self._send_homeassistant_command("info")
return res[f"state"]
async def _send_power_request(self, state: str) -> str:
await self._send_homeassistant_command(state)
res = await self._send_status_request()
return res
class Loxonev1(HTTPDevice):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config, default_user="admin",
default_password="admin")
self.output_id = config.get("output_id", "")
async def _send_loxonev1_command(self, command: str) -> Dict[str, Any]:
if command in ["on", "off"]:
out_cmd = f"jdev/sps/io/{self.output_id}/{command}"
elif command == "info":
out_cmd = f"jdev/sps/io/{self.output_id}"
else:
raise self.server.error(f"Invalid loxonev1 command: {command}")
if self.password != "":
out_pwd = f"{self.user}:{self.password}@"
else:
out_pwd = f""
url = f"http://{out_pwd}{self.addr}/{out_cmd}"
return await self._send_http_command(url, command)
async def _send_status_request(self) -> str:
res = await self._send_loxonev1_command("info")
state = res[f"LL"][f"value"]
return "on" if int(state) == 1 else "off"
async def _send_power_request(self, state: str) -> str:
res = await self._send_loxonev1_command(state)
state = res[f"LL"][f"value"]
return "on" if int(state) == 1 else "off"
# The power component has multiple configuration sections
def load_component_multi(config: ConfigHelper) -> PrinterPower:
return PrinterPower(config)
+189
View File
@@ -0,0 +1,189 @@
# Moonraker Process Stat Tracking
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import time
import re
import os
import pathlib
import logging
from collections import deque
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.locks import Lock
# Annotation imports
from typing import (
TYPE_CHECKING,
Deque,
Any,
Tuple,
Optional,
Dict,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
from . import shell_command
VC_GEN_CMD_FILE = "/usr/bin/vcgencmd"
STATM_FILE_PATH = "/proc/self/smaps_rollup"
TEMPERATURE_PATH = "/sys/class/thermal/thermal_zone0/temp"
STAT_UPDATE_TIME_MS = 1000
REPORT_QUEUE_SIZE = 30
THROTTLE_CHECK_INTERVAL = 10
REPORT_BLOCKED_TIME = 5.
THROTTLED_FLAGS = {
1: "Under-Voltage Detected",
1 << 1: "Frequency Capped",
1 << 2: "Currently Throttled",
1 << 3: "Temperature Limit Active",
1 << 16: "Previously Under-Volted",
1 << 17: "Previously Frequency Capped",
1 << 18: "Previously Throttled",
1 << 19: "Previously Temperature Limited"
}
class ProcStats:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.ioloop = IOLoop.current()
self.stat_update_cb = PeriodicCallback(
self._handle_stat_update, STAT_UPDATE_TIME_MS) # type: ignore
self.vcgencmd: Optional[shell_command.ShellCommand] = None
if os.path.exists(VC_GEN_CMD_FILE):
logging.info("Detected 'vcgencmd', throttle checking enabled")
shell_cmd: shell_command.ShellCommandFactory
shell_cmd = self.server.load_component(config, "shell_command")
self.vcgencmd = shell_cmd.build_shell_command(
"vcgencmd get_throttled")
self.server.register_notification("proc_stats:cpu_throttled")
else:
logging.info("Unable to find 'vcgencmd', throttle checking "
"disabled")
self.temp_file = pathlib.Path(TEMPERATURE_PATH)
self.smaps = pathlib.Path(STATM_FILE_PATH)
self.server.register_endpoint(
"/machine/proc_stats", ["GET"], self._handle_stat_request)
self.server.register_event_handler(
"server:klippy_shutdown", self._handle_shutdown)
self.server.register_notification("proc_stats:proc_stat_update")
self.proc_stat_queue: Deque[Dict[str, Any]] = deque(maxlen=30)
self.last_update_time = time.time()
self.last_proc_time = time.process_time()
self.throttle_check_lock = Lock()
self.total_throttled: int = 0
self.last_throttled: int = 0
self.update_sequence: int = 0
self.stat_update_cb.start()
async def _handle_stat_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
ts: Optional[Dict[str, Any]] = None
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
return {
'moonraker_stats': list(self.proc_stat_queue),
'throttled_state': ts,
'cpu_temp': self._get_cpu_temperature()
}
async def _handle_shutdown(self) -> None:
msg = "\nMoonraker System Usage Statistics:"
for stats in self.proc_stat_queue:
msg += f"\n{self._format_stats(stats)}"
msg += f"\nCPU Temperature: {self._get_cpu_temperature()}"
logging.info(msg)
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
logging.info(f"Throttled Flags: {' '.join(ts['flags'])}")
async def _handle_stat_update(self) -> None:
update_time = time.time()
proc_time = time.process_time()
time_diff = update_time - self.last_update_time
usage = round((proc_time - self.last_proc_time) / time_diff * 100, 2)
if time_diff > REPORT_BLOCKED_TIME:
logging.info(
f"EVENT LOOP BLOCKED: {round(time_diff, 2)} seconds, "
f"Moonraker Process Usage: {usage}%")
mem, mem_units = self._get_memory_usage()
cpu_temp = self._get_cpu_temperature()
result = {
"time": update_time,
"cpu_usage": usage,
"memory": mem,
"mem_units": mem_units,
}
self.proc_stat_queue.append(result)
self.server.send_event("proc_stats:proc_stat_update", {
'moonraker_stats': result,
'cpu_temp': cpu_temp
})
self.last_update_time = update_time
self.last_proc_time = proc_time
self.update_sequence += 1
if self.update_sequence == THROTTLE_CHECK_INTERVAL:
self.update_sequence = 0
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
cur_throttled = ts['bits']
if cur_throttled & ~self.total_throttled:
self.server.add_log_rollover_item(
'throttled', f"CPU Throttled Flags: {ts['flags']}")
if cur_throttled != self.last_throttled:
self.server.send_event("proc_stats:cpu_throttled", ts)
self.last_throttled = cur_throttled
self.total_throttled |= cur_throttled
async def _check_throttled_state(self) -> Dict[str, Any]:
async with self.throttle_check_lock:
assert self.vcgencmd is not None
try:
resp = await self.vcgencmd.run_with_response(
timeout=.5, log_complete=False)
ts = int(resp.strip().split("=")[-1], 16)
except Exception:
return {'bits': 0, 'flags': ["?"]}
flags = []
for flag, desc in THROTTLED_FLAGS.items():
if flag & ts:
flags.append(desc)
return {'bits': ts, 'flags': flags}
def _get_memory_usage(self) -> Tuple[Optional[int], Optional[str]]:
try:
mem_data = self.smaps.read_text()
rss_match = re.search(r"Rss:\s+(\d+)\s+(\w+)", mem_data)
if rss_match is None:
return None, None
mem = int(rss_match.group(1))
units = rss_match.group(2)
except Exception:
return None, None
return mem, units
def _get_cpu_temperature(self) -> Optional[float]:
temp = None
if self.temp_file.exists():
try:
res = int(self.temp_file.read_text().strip())
temp = res / 1000.
except Exception:
return None
return temp
def _format_stats(self, stats: Dict[str, Any]) -> str:
return f"System Time: {stats['time']:2f}, " \
f"Usage: {stats['cpu_usage']}%, " \
f"Memory: {stats['memory']} {stats['mem_units']}"
def close(self) -> None:
self.stat_update_cb.stop()
def load_component(config: ConfigHelper) -> ProcStats:
return ProcStats(config)
+319
View File
@@ -0,0 +1,319 @@
# linux shell command execution utility
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import shlex
import logging
import signal
import asyncio
from tornado import gen
from tornado.locks import Lock
from utils import ServerError
# Annotation imports
from typing import (
TYPE_CHECKING,
Optional,
Callable,
Coroutine,
Dict,
Set,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from asyncio import BaseTransport
OutputCallback = Optional[Callable[[bytes], None]]
class ShellCommandError(ServerError):
def __init__(self,
message: str,
return_code: Optional[int],
stdout: Optional[bytes] = b"",
stderr: Optional[bytes] = b"",
status_code: int = 500
) -> None:
super().__init__(message, status_code=status_code)
self.stdout = stdout or b""
self.stderr = stderr or b""
self.return_code = return_code
class SCProcess(asyncio.subprocess.Process):
def initialize(self,
program_name: str,
std_out_cb: OutputCallback,
std_err_cb: OutputCallback,
log_stderr: bool
) -> None:
self.program_name = program_name
self.std_out_cb = std_out_cb
self.std_err_cb = std_err_cb
self.log_stderr = log_stderr
self.cancel_requested = False
async def _read_stream_with_cb(self, fd: int) -> bytes:
transport: BaseTransport = \
self._transport.get_pipe_transport(fd) # type: ignore
if fd == 2:
stream = self.stderr
cb = self.std_err_cb
else:
assert fd == 1
stream = self.stdout
cb = self.std_out_cb
assert stream is not None
while not stream.at_eof():
output = await stream.readline()
if not output:
break
if fd == 2 and self.log_stderr:
logging.info(
f"{self.program_name}: "
f"{output.decode(errors='ignore')}")
output = output.rstrip(b'\n')
if output and cb is not None:
cb(output)
transport.close()
return output
async def cancel(self, sig_idx: int = 1) -> None:
if self.cancel_requested:
return
self.cancel_requested = True
exit_success = False
sig_idx = min(2, max(0, sig_idx))
sigs = [signal.SIGINT, signal.SIGTERM, signal.SIGKILL][sig_idx:]
for sig in sigs:
self.send_signal(sig)
try:
ret = self.wait()
await asyncio.wait_for(ret, timeout=2.)
except asyncio.TimeoutError:
continue
logging.debug(f"Command '{self.program_name}' exited with "
f"signal: {sig.name}")
exit_success = True
break
if not exit_success:
logging.info(f"WARNING: {self.program_name} did not cleanly exit")
if self.stdout is not None:
self.stdout.feed_eof()
if self.stderr is not None:
self.stderr.feed_eof()
async def communicate_with_cb(self,
input: Optional[bytes] = None
) -> None:
if input is not None:
stdin: Coroutine = self._feed_stdin(input) # type: ignore
else:
stdin = self._noop() # type: ignore
if self.stdout is not None and self.std_out_cb is not None:
stdout: Coroutine = self._read_stream_with_cb(1)
else:
stdout = self._noop() # type: ignore
has_err_output = self.std_err_cb is not None or self.log_stderr
if self.stderr is not None and has_err_output:
stderr: Coroutine = self._read_stream_with_cb(2)
else:
stderr = self._noop() # type: ignore
stdin, stdout, stderr = await asyncio.tasks.gather(
stdin, stdout, stderr, loop=self._loop) # type: ignore
await self.wait()
class ShellCommand:
IDX_SIGINT = 0
IDX_SIGTERM = 1
IDX_SIGKILL = 2
def __init__(self,
factory: ShellCommandFactory,
cmd: str,
std_out_callback: OutputCallback,
std_err_callback: OutputCallback,
env: Optional[Dict[str, str]] = None,
log_stderr: bool = False,
cwd: Optional[str] = None
) -> None:
self.factory = factory
self.name = cmd
self.std_out_cb = std_out_callback
self.std_err_cb = std_err_callback
cmd = os.path.expanduser(cmd)
self.command = shlex.split(cmd)
self.log_stderr = log_stderr
self.env = env
self.cwd = cwd
self.proc: Optional[SCProcess] = None
self.cancelled = False
self.return_code: Optional[int] = None
self.run_lock = Lock()
async def cancel(self, sig_idx: int = 1) -> None:
self.cancelled = True
if self.proc is not None:
await self.proc.cancel(sig_idx)
def get_return_code(self) -> Optional[int]:
return self.return_code
def _reset_command_data(self) -> None:
self.return_code = self.proc = None
self.cancelled = False
async def run(self,
timeout: float = 2.,
verbose: bool = True,
log_complete: bool = True,
sig_idx: int = 1
) -> bool:
async with self.run_lock:
self.factory.add_running_command(self)
self._reset_command_data()
if not timeout:
# Never timeout
timeout = 9999999999999999.
if self.std_out_cb is None and self.std_err_cb is None and \
not self.log_stderr:
# No callbacks set so output cannot be verbose
verbose = False
if not await self._create_subprocess():
self.factory.remove_running_command(self)
return False
assert self.proc is not None
try:
if verbose:
ret: Coroutine = self.proc.communicate_with_cb()
else:
ret = self.proc.wait()
await asyncio.wait_for(ret, timeout=timeout)
except asyncio.TimeoutError:
complete = False
await self.proc.cancel(sig_idx)
else:
complete = not self.cancelled
self.factory.remove_running_command(self)
return self._check_proc_success(complete, log_complete)
async def run_with_response(self,
timeout: float = 2.,
retries: int = 1,
log_complete: bool = True,
sig_idx: int = 1
) -> str:
async with self.run_lock:
self.factory.add_running_command(self)
retries = max(1, retries)
while retries > 0:
self._reset_command_data()
timed_out = False
stdout = stderr = b""
if await self._create_subprocess():
assert self.proc is not None
try:
ret = self.proc.communicate()
stdout, stderr = await asyncio.wait_for(
ret, timeout=timeout)
except asyncio.TimeoutError:
complete = False
timed_out = True
await self.proc.cancel(sig_idx)
else:
complete = not self.cancelled
if self.log_stderr and stderr:
logging.info(
f"{self.command[0]}: "
f"{stderr.decode(errors='ignore')}")
if self._check_proc_success(complete, log_complete):
self.factory.remove_running_command(self)
return stdout.decode(errors='ignore').rstrip("\n")
if stdout:
logging.debug(
f"Shell command '{self.name}' output:"
f"\n{stdout.decode(errors='ignore')}")
if self.cancelled and not timed_out:
break
retries -= 1
await gen.sleep(.5)
self.factory.remove_running_command(self)
raise ShellCommandError(
f"Error running shell command: '{self.command}'",
self.return_code, stdout, stderr)
async def _create_subprocess(self) -> bool:
loop = asyncio.get_event_loop()
def protocol_factory():
return asyncio.subprocess.SubprocessStreamProtocol(
limit=2**20, loop=loop)
try:
if self.std_err_cb is not None or self.log_stderr:
errpipe = asyncio.subprocess.PIPE
else:
errpipe = asyncio.subprocess.STDOUT
transport, protocol = await loop.subprocess_exec(
protocol_factory, *self.command,
stdout=asyncio.subprocess.PIPE,
stderr=errpipe, env=self.env, cwd=self.cwd)
self.proc = SCProcess(transport, protocol, loop)
self.proc.initialize(self.command[0], self.std_out_cb,
self.std_err_cb, self.log_stderr)
except Exception:
logging.exception(
f"shell_command: Command ({self.name}) failed")
return False
return True
def _check_proc_success(self,
complete: bool,
log_complete: bool
) -> bool:
assert self.proc is not None
self.return_code = self.proc.returncode
success = self.return_code == 0 and complete
if success:
msg = f"Command ({self.name}) successfully finished"
elif self.cancelled:
msg = f"Command ({self.name}) cancelled"
elif not complete:
msg = f"Command ({self.name}) timed out"
else:
msg = f"Command ({self.name}) exited with return code" \
f" {self.return_code}"
if log_complete:
logging.info(msg)
return success
class ShellCommandFactory:
error = ShellCommandError
def __init__(self, config: ConfigHelper) -> None:
self.running_commands: Set[ShellCommand] = set()
def add_running_command(self, cmd: ShellCommand) -> None:
self.running_commands.add(cmd)
def remove_running_command(self, cmd: ShellCommand) -> None:
try:
self.running_commands.remove(cmd)
except KeyError:
pass
def build_shell_command(self,
cmd: str,
callback: OutputCallback = None,
std_err_callback: OutputCallback = None,
env: Optional[Dict[str, str]] = None,
log_stderr: bool = False,
cwd: Optional[str] = None
) -> ShellCommand:
return ShellCommand(self, cmd, callback, std_err_callback, env,
log_stderr, cwd)
async def close(self) -> None:
for cmd in self.running_commands:
await cmd.cancel()
def load_component(config: ConfigHelper) -> ShellCommandFactory:
return ShellCommandFactory(config)
@@ -0,0 +1,15 @@
# Package definition for the update_manager
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
from . import update_manager as um
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from confighelper import ConfigHelper
def load_component(config: ConfigHelper) -> um.UpdateManager:
return um.load_component(config)
@@ -0,0 +1,249 @@
# Deploy updates for applications managed by Moonraker
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import pathlib
import shutil
import hashlib
from concurrent.futures.thread import ThreadPoolExecutor
from tornado.ioloop import IOLoop
from .base_deploy import BaseDeploy
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from .update_manager import CommandHelper
CHANNEL_TO_TYPE = {
"stable": "zip",
"beta": "zip_beta",
"dev": "git_repo"
}
TYPE_TO_CHANNEL = {
"zip": "stable",
"zip_beta": "beta",
"dev": "git_repo"
}
class AppDeploy(BaseDeploy):
def __init__(self,
config: ConfigHelper,
cmd_helper: CommandHelper,
app_params: Optional[Dict[str, Any]]
) -> None:
super().__init__(config, cmd_helper)
self.config = config
self.app_params = app_params
self.debug = self.cmd_helper.is_debug_enabled()
if app_params is not None:
self.channel: str = app_params['channel']
self.path: pathlib.Path = pathlib.Path(
app_params['path']).expanduser().resolve()
executable: Optional[str] = app_params['executable']
self.type = CHANNEL_TO_TYPE[self.channel]
else:
self.type = config.get('type')
self.channel = TYPE_TO_CHANNEL[self.type]
self.path = pathlib.Path(
config.get('path')).expanduser().resolve()
executable = config.get('env', None)
if self.channel not in CHANNEL_TO_TYPE.keys():
raise config.error(
f"Invalid Channel '{self.channel}' for config "
f"section [{config.get_name()}]")
self._verify_path(config, 'path', self.path)
self.executable: Optional[pathlib.Path] = None
self.venv_args: Optional[str] = None
if executable is not None:
self.executable = pathlib.Path(executable).expanduser().resolve()
self._verify_path(config, 'env', self.executable)
self.venv_args = config.get('venv_args', None)
self.need_channel_update = False
self._is_valid = False
# We need to fetch all potential options for an Application. Not
# all options apply to each subtype, however we can't limit the
# options in children if we want to switch between channels and
# satisfy the confighelper's requirements.
self.origin: str = config.get('origin')
self.primary_branch = config.get("primary_branch", "master")
self.npm_pkg_json: Optional[pathlib.Path] = None
if config.get("enable_node_updates", False):
self.npm_pkg_json = self.path.joinpath("package-lock.json")
self._verify_path(config, 'enable_node_updates', self.npm_pkg_json)
self.python_reqs: Optional[pathlib.Path] = None
if self.executable is not None:
self.python_reqs = self.path.joinpath(config.get("requirements"))
self._verify_path(config, 'requirements', self.python_reqs)
self.install_script: Optional[pathlib.Path] = None
install_script = config.get('install_script', None)
if install_script is not None:
self.install_script = self.path.joinpath(install_script).resolve()
self._verify_path(config, 'install_script', self.install_script)
@staticmethod
def _is_git_repo(app_path: Union[str, pathlib.Path]) -> bool:
if isinstance(app_path, str):
app_path = pathlib.Path(app_path).expanduser()
return app_path.joinpath('.git').exists()
def _verify_path(self,
config: ConfigHelper,
option: str,
file_path: pathlib.Path
) -> None:
if not file_path.exists():
raise config.error(
f"Invalid path for option `{option}` in section "
f"[{config.get_name()}]: Path `{file_path}` does not exist")
def check_need_channel_swap(self) -> bool:
return self.need_channel_update
def get_configured_type(self) -> str:
return self.type
def check_same_paths(self,
app_path: Union[str, pathlib.Path],
executable: Union[str, pathlib.Path]
) -> bool:
if isinstance(app_path, str):
app_path = pathlib.Path(app_path)
if isinstance(executable, str):
executable = pathlib.Path(executable)
app_path = app_path.expanduser()
executable = executable.expanduser()
if self.executable is None:
return False
return self.path.samefile(app_path) and \
self.executable.samefile(executable)
async def recover(self,
hard: bool = False,
force_dep_update: bool = False
) -> None:
raise NotImplementedError
async def reinstall(self):
raise NotImplementedError
async def restart_service(self):
if self.name == "moonraker":
# Launch restart async so the request can return
# before the server restarts
IOLoop.current().call_later(
.1, self._do_restart) # type: ignore
else:
await self._do_restart()
async def _do_restart(self) -> None:
self.notify_status("Restarting Service...")
try:
await self.cmd_helper.run_cmd(
f"sudo systemctl restart {self.name}")
except Exception:
if self.name == "moonraker":
# We will always get an error when restarting moonraker
# from within the child process, so ignore it
return
raise self.log_exc("Error restarting service")
def get_update_status(self) -> Dict[str, Any]:
return {
'channel': self.channel,
'debug_enabled': self.debug,
'need_channel_update': self.need_channel_update,
'is_valid': self._is_valid,
'configured_type': self.type
}
async def _get_file_hash(self,
filename: Optional[pathlib.Path]
) -> Optional[str]:
if filename is None or not filename.is_file():
return None
def hash_func(f: pathlib.Path) -> str:
return hashlib.sha256(f.read_bytes()).hexdigest()
try:
with ThreadPoolExecutor(max_workers=1) as tpe:
return await IOLoop.current().run_in_executor(
tpe, hash_func, filename)
except Exception:
return None
async def _check_need_update(self,
prev_hash: Optional[str],
filename: Optional[pathlib.Path]
) -> bool:
cur_hash = await self._get_file_hash(filename)
if prev_hash is None or cur_hash is None:
return False
return prev_hash != cur_hash
async def _install_packages(self, package_list: List[str]) -> None:
self.notify_status("Installing system dependencies...")
# Install packages with apt-get
try:
await self.cmd_helper.install_packages(
package_list, timeout=3600., notify=True)
except Exception:
self.log_exc("Error updating packages")
return
async def _update_virtualenv(self,
requirements: Union[pathlib.Path, List[str]]
) -> None:
if self.executable is None:
return
# Update python dependencies
bin_dir = self.executable.parent
if isinstance(requirements, pathlib.Path):
if not requirements.is_file():
self.log_info(
f"Invalid path to requirements_file '{requirements}'")
return
args = f"-r {requirements}"
else:
args = " ".join(requirements)
pip = bin_dir.joinpath("pip")
self.notify_status("Updating python packages...")
try:
# First attempt to update pip
await self.cmd_helper.run_cmd(
f"{pip} install -U pip", timeout=1200., notify=True,
retries=3)
await self.cmd_helper.run_cmd(
f"{pip} install {args}", timeout=1200., notify=True,
retries=3)
except Exception:
self.log_exc("Error updating python requirements")
async def _build_virtualenv(self) -> None:
if self.executable is None or self.venv_args is None:
return
bin_dir = self.executable.parent
env_path = bin_dir.joinpath("..").resolve()
self.notify_status(f"Creating virtualenv at: {env_path}...")
if env_path.exists():
shutil.rmtree(env_path)
try:
await self.cmd_helper.run_cmd(
f"virtualenv {self.venv_args} {env_path}", timeout=300.)
except Exception:
self.log_exc(f"Error creating virtualenv")
return
if not self.executable.exists():
raise self.log_exc("Failed to create new virtualenv", False)
@@ -0,0 +1,56 @@
# Base Deployment Interface
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Dict, Any
if TYPE_CHECKING:
from confighelper import ConfigHelper
from utils import ServerError
from .update_manager import CommandHelper
class BaseDeploy:
def __init__(self,
config: ConfigHelper,
cmd_helper: CommandHelper
) -> None:
name_parts = config.get_name().split()
self.name = name_parts[-1]
self.server = config.get_server()
self.cmd_helper = cmd_helper
if name_parts == 1:
self.prefix: str = ""
if config.get('type', "") == "web":
self.prefix = f"Web Client {self.name}: "
else:
self.prefix = f"Application {self.name}: "
async def refresh(self) -> None:
pass
async def update(self) -> bool:
return False
def get_update_status(self) -> Dict[str, Any]:
return {}
def log_exc(self, msg: str, traceback: bool = True) -> ServerError:
log_msg = f"{self.prefix}{msg}"
if traceback:
logging.exception(log_msg)
else:
logging.info(log_msg)
return self.server.error(msg)
def log_info(self, msg: str) -> None:
log_msg = f"{self.prefix}{msg}"
logging.info(log_msg)
def notify_status(self, msg: str, is_complete: bool = False) -> None:
log_msg = f"{self.prefix}{msg}"
logging.debug(log_msg)
self.cmd_helper.notify_update_response(log_msg, is_complete)
@@ -0,0 +1,747 @@
# Git Deployment implementation
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import asyncio
import os
import pathlib
import shutil
import re
import logging
from concurrent.futures import ThreadPoolExecutor
from tornado.ioloop import IOLoop
from .app_deploy import AppDeploy
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Tuple,
Optional,
Dict,
List,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from components import database
from components import shell_command
from .update_manager import CommandHelper
DBComp = database.MoonrakerDatabase
class GitDeploy(AppDeploy):
def __init__(self,
config: ConfigHelper,
cmd_helper: CommandHelper,
app_params: Optional[Dict[str, Any]] = None
) -> None:
super().__init__(config, cmd_helper, app_params)
self.repo = GitRepo(cmd_helper, self.path, self.name, self.origin)
if self.type != 'git_repo':
self.need_channel_update = True
@staticmethod
async def from_application(app: AppDeploy) -> GitDeploy:
new_app = GitDeploy(app.config, app.cmd_helper, app.app_params)
await new_app.reinstall()
return new_app
async def refresh(self) -> None:
try:
await self._update_repo_state()
except Exception:
logging.exception("Error Refreshing git state")
async def _update_repo_state(self, need_fetch: bool = True) -> None:
self._is_valid = False
await self.repo.initialize(need_fetch=need_fetch)
self.log_info(
f"Channel: {self.channel}, "
f"Need Channel Update: {self.need_channel_update}"
)
invalids = self.repo.report_invalids(self.primary_branch)
if invalids:
msgs = '\n'.join(invalids)
self.log_info(
f"Repo validation checks failed:\n{msgs}")
if self.debug:
self._is_valid = True
self.log_info(
"Repo debug enabled, overriding validity checks")
else:
self.log_info("Updates on repo disabled")
else:
self._is_valid = True
self.log_info("Validity check for git repo passed")
async def update(self) -> bool:
await self.repo.wait_for_init()
if not self._is_valid:
raise self.log_exc("Update aborted, repo not valid", False)
if self.repo.is_dirty():
raise self.log_exc(
"Update aborted, repo has been modified", False)
if self.repo.is_current():
# No need to update
return False
self.cmd_helper.notify_update_response(
f"Updating Application {self.name}...")
inst_hash = await self._get_file_hash(self.install_script)
pyreqs_hash = await self._get_file_hash(self.python_reqs)
npm_hash = await self._get_file_hash(self.npm_pkg_json)
await self._pull_repo()
# Check Semantic Versions
await self._update_dependencies(inst_hash, pyreqs_hash, npm_hash)
# Refresh local repo state
await self._update_repo_state(need_fetch=False)
await self.restart_service()
self.notify_status("Update Finished...", is_complete=True)
return True
async def recover(self,
hard: bool = False,
force_dep_update: bool = False
) -> None:
self.notify_status("Attempting Repo Recovery...")
inst_hash = await self._get_file_hash(self.install_script)
pyreqs_hash = await self._get_file_hash(self.python_reqs)
npm_hash = await self._get_file_hash(self.npm_pkg_json)
if hard:
await self.repo.clone()
await self._update_repo_state()
else:
self.notify_status("Resetting Git Repo...")
await self.repo.reset()
await self._update_repo_state()
if self.repo.is_dirty() or not self._is_valid:
raise self.server.error(
"Recovery attempt failed, repo state not pristine", 500)
await self._update_dependencies(inst_hash, pyreqs_hash, npm_hash,
force=force_dep_update)
await self.restart_service()
self.notify_status("Reinstall Complete", is_complete=True)
async def reinstall(self):
await self.recover(True, True)
def get_update_status(self) -> Dict[str, Any]:
status = super().get_update_status()
status.update(self.repo.get_repo_status())
return status
async def _pull_repo(self) -> None:
self.notify_status("Updating Repo...")
try:
if self.repo.is_detached():
await self.repo.fetch()
await self.repo.checkout()
else:
await self.repo.pull()
except Exception:
raise self.log_exc("Error running 'git pull'")
async def _update_dependencies(self,
inst_hash: Optional[str],
pyreqs_hash: Optional[str],
npm_hash: Optional[str],
force: bool = False
) -> None:
ret = await self._check_need_update(inst_hash, self.install_script)
if force or ret:
package_list = await self._parse_install_script()
if package_list is not None:
await self._install_packages(package_list)
ret = await self._check_need_update(pyreqs_hash, self.python_reqs)
if force or ret:
if self.python_reqs is not None:
await self._update_virtualenv(self.python_reqs)
ret = await self._check_need_update(npm_hash, self.npm_pkg_json)
if force or ret:
if self.npm_pkg_json is not None:
self.notify_status("Updating Node Packages...")
try:
await self.cmd_helper.run_cmd(
"npm ci --only=prod", notify=True, timeout=600.,
cwd=str(self.path))
except Exception:
self.notify_status("Node Package Update failed")
async def _parse_install_script(self) -> Optional[List[str]]:
if self.install_script is None:
return None
# Open install file file and read
inst_path: pathlib.Path = self.install_script
if not inst_path.is_file():
self.log_info(f"Unable to open install script: {inst_path}")
return None
with ThreadPoolExecutor(max_workers=1) as tpe:
data = await IOLoop.current().run_in_executor(
tpe, inst_path.read_text)
packages: List[str] = re.findall(r'PKGLIST="(.*)"', data)
packages = [p.lstrip("${PKGLIST}").strip() for p in packages]
if not packages:
self.log_info(f"No packages found in script: {inst_path}")
return None
logging.debug(f"Repo {self.name}: Detected Packages: {repr(packages)}")
return packages
GIT_ASYNC_TIMEOUT = 300.
GIT_ENV_VARS = {
'GIT_HTTP_LOW_SPEED_LIMIT': "1000",
'GIT_HTTP_LOW_SPEED_TIME ': "20"
}
GIT_MAX_LOG_CNT = 100
GIT_LOG_FMT = \
"\"sha:%H%x1Dauthor:%an%x1Ddate:%ct%x1Dsubject:%s%x1Dmessage:%b%x1E\""
GIT_OBJ_ERR = "fatal: loose object"
class GitRepo:
def __init__(self,
cmd_helper: CommandHelper,
git_path: pathlib.Path,
alias: str,
origin_url: str
) -> None:
self.server = cmd_helper.get_server()
self.cmd_helper = cmd_helper
self.alias = alias
self.git_path = git_path
git_dir = git_path.parent
git_base = git_path.name
self.backup_path = git_dir.joinpath(f".{git_base}_repo_backup")
self.origin_url = origin_url
self.valid_git_repo: bool = False
self.git_owner: str = "?"
self.git_remote: str = "?"
self.git_branch: str = "?"
self.current_version: str = "?"
self.upstream_version: str = "?"
self.current_commit: str = "?"
self.upstream_commit: str = "?"
self.upstream_url: str = "?"
self.full_version_string: str = "?"
self.branches: List[str] = []
self.dirty: bool = False
self.head_detached: bool = False
self.git_messages: List[str] = []
self.commits_behind: List[Dict[str, Any]] = []
self.recovery_message = \
f"""
Manually restore via SSH with the following commands:
sudo service {self.alias} stop
cd {git_dir}
rm -rf {git_base}
git clone {self.origin_url}
sudo service {self.alias} start
"""
self.init_evt: Optional[asyncio.Event] = None
self.initialized: bool = False
self.git_operation_lock = asyncio.Lock()
self.fetch_timeout_handle: Optional[object] = None
self.fetch_input_recd: bool = False
async def initialize(self, need_fetch: bool = True) -> None:
if self.init_evt is not None:
# No need to initialize multiple requests
await self.init_evt.wait()
if self.initialized:
return
self.initialized = False
self.init_evt = asyncio.Event()
self.git_messages.clear()
try:
await self.update_repo_status()
self._verify_repo()
if not self.head_detached:
# lookup remote via git config
self.git_remote = await self.get_config_item(
f"branch.{self.git_branch}.remote")
# Populate list of current branches
blist = await self.list_branches()
self.branches = []
for branch in blist:
branch = branch.strip()
if branch[0] == "*":
branch = branch[2:]
if branch[0] == "(":
continue
self.branches.append(branch)
if need_fetch:
await self.fetch()
self.upstream_url = await self.remote(f"get-url {self.git_remote}")
self.current_commit = await self.rev_parse("HEAD")
self.upstream_commit = await self.rev_parse(
f"{self.git_remote}/{self.git_branch}")
current_version = await self.describe(
"--always --tags --long --dirty")
self.full_version_string = current_version.strip()
upstream_version = await self.describe(
f"{self.git_remote}/{self.git_branch} "
"--always --tags --long")
# Store current remote in the database if in a detached state
if self.head_detached:
mrdb: DBComp = self.server.lookup_component("database")
db_key = f"update_manager.git_repo_{self.alias}" \
".detached_remote"
mrdb.insert_item(
"moonraker", db_key,
[self.current_commit, self.git_remote, self.git_branch])
# Parse GitHub Owner from URL
owner_match = re.match(r"https?://[^/]+/([^/]+)", self.upstream_url)
self.git_owner = "?"
if owner_match is not None:
self.git_owner = owner_match.group(1)
self.dirty = current_version.endswith("dirty")
# Parse Version Info
versions = []
for ver in [current_version, upstream_version]:
tag_version = "?"
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver)
if ver_match:
tag_version = ver_match.group()
versions.append(tag_version)
self.current_version, self.upstream_version = versions
# Get Commits Behind
self.commits_behind = []
cbh = await self.get_commits_behind()
if cbh:
tagged_commits = await self.get_tagged_commits()
debug_msg = '\n'.join([f"{k}: {v}" for k, v in
tagged_commits.items()])
logging.debug(f"Git Repo {self.alias}: Tagged Commits\n"
f"{debug_msg}")
for i, commit in enumerate(cbh):
tag = tagged_commits.get(commit['sha'], None)
if i < 30 or tag is not None:
commit['tag'] = tag
self.commits_behind.append(commit)
self.log_repo_info()
except Exception:
logging.exception(f"Git Repo {self.alias}: Initialization failure")
raise
else:
self.initialized = True
finally:
self.init_evt.set()
self.init_evt = None
async def wait_for_init(self) -> None:
if self.init_evt is not None:
await self.init_evt.wait()
if not self.initialized:
raise self.server.error(
f"Git Repo {self.alias}: Initialization failure")
async def update_repo_status(self) -> bool:
async with self.git_operation_lock:
if not self.git_path.joinpath(".git").is_dir():
logging.info(
f"Git Repo {self.alias}: path '{self.git_path}'"
" is not a valid git repo")
return False
await self._wait_for_lock_release()
self.valid_git_repo = False
retries = 3
while retries:
self.git_messages.clear()
try:
resp: Optional[str] = await self._run_git_cmd(
"status -u no", retries=1)
except Exception:
retries -= 1
resp = None
# Attempt to recover from "loose object" error
if retries and GIT_OBJ_ERR in "\n".join(self.git_messages):
ret = await self._repair_loose_objects()
if not ret:
# Since we are unable to recover, immediately
# return
return False
else:
break
if resp is None:
return False
resp = resp.strip().split('\n', 1)[0]
self.head_detached = resp.startswith("HEAD detached")
branch_info = resp.split()[-1]
if self.head_detached:
bparts = branch_info.split("/", 1)
if len(bparts) == 2:
self.git_remote, self.git_branch = bparts
else:
mrdb: DBComp = self.server.lookup_component("database")
db_key = f"update_manager.git_repo_{self.alias}" \
".detached_remote"
detached_remote: List[str] = mrdb.get_item(
"moonraker", db_key, ["", "?", "?"])
if detached_remote[0].startswith(branch_info):
self.git_remote = detached_remote[1]
self.git_branch = detached_remote[2]
msg = "Using remote stored in database:"\
f" {self.git_remote}/{self.git_branch}"
elif self.git_remote == "?":
msg = "Resolve by manually checking out" \
" a branch via SSH."
else:
msg = "Defaulting to previously tracked " \
f"{self.git_remote}/{self.git_branch}."
logging.info(
f"Git Repo {self.alias}: HEAD detached on untracked "
f"commit {branch_info}. {msg}")
else:
self.git_branch = branch_info
self.valid_git_repo = True
return True
def log_repo_info(self) -> None:
logging.info(
f"Git Repo {self.alias} Detected:\n"
f"Owner: {self.git_owner}\n"
f"Path: {self.git_path}\n"
f"Remote: {self.git_remote}\n"
f"Branch: {self.git_branch}\n"
f"Remote URL: {self.upstream_url}\n"
f"Current Commit SHA: {self.current_commit}\n"
f"Upstream Commit SHA: {self.upstream_commit}\n"
f"Current Version: {self.current_version}\n"
f"Upstream Version: {self.upstream_version}\n"
f"Is Dirty: {self.dirty}\n"
f"Is Detached: {self.head_detached}\n"
f"Commits Behind: {len(self.commits_behind)}")
def report_invalids(self, primary_branch: str) -> List[str]:
invalids: List[str] = []
upstream_url = self.upstream_url.lower()
if upstream_url[-4:] != ".git":
upstream_url += ".git"
if upstream_url != self.origin_url:
invalids.append(f"Unofficial remote url: {self.upstream_url}")
if self.git_branch != primary_branch or self.git_remote != "origin":
invalids.append(
"Repo not on valid remote branch, expected: "
f"origin/{primary_branch}, detected: "
f"{self.git_remote}/{self.git_branch}")
if self.head_detached:
invalids.append("Detached HEAD detected")
return invalids
def _verify_repo(self, check_remote: bool = False) -> None:
if not self.valid_git_repo:
raise self.server.error(
f"Git Repo {self.alias}: repo not initialized")
if check_remote:
if self.git_remote == "?":
raise self.server.error(
f"Git Repo {self.alias}: No valid git remote detected")
async def reset(self) -> None:
if self.git_remote == "?" or self.git_branch == "?":
raise self.server.error("Cannot reset, unknown remote/branch")
async with self.git_operation_lock:
await self._run_git_cmd("clean -d -f", retries=2)
await self._run_git_cmd(
f"reset --hard {self.git_remote}/{self.git_branch}",
retries=2)
async def fetch(self) -> None:
self._verify_repo(check_remote=True)
async with self.git_operation_lock:
await self._run_git_cmd_async(
f"fetch {self.git_remote} --prune --progress")
async def pull(self) -> None:
self._verify_repo()
if self.head_detached:
raise self.server.error(
f"Git Repo {self.alias}: Cannot perform pull on a "
"detached HEAD")
async with self.git_operation_lock:
await self._run_git_cmd_async("pull --progress")
async def list_branches(self) -> List[str]:
self._verify_repo()
async with self.git_operation_lock:
resp = await self._run_git_cmd("branch --list")
return resp.strip().split("\n")
async def remote(self, command: str) -> str:
self._verify_repo(check_remote=True)
async with self.git_operation_lock:
resp = await self._run_git_cmd(
f"remote {command}")
return resp.strip()
async def describe(self, args: str = "") -> str:
self._verify_repo()
async with self.git_operation_lock:
resp = await self._run_git_cmd(f"describe {args}".strip())
return resp.strip()
async def rev_parse(self, args: str = "") -> str:
self._verify_repo()
async with self.git_operation_lock:
resp = await self._run_git_cmd(f"rev-parse {args}".strip())
return resp.strip()
async def get_config_item(self, item: str) -> str:
self._verify_repo()
async with self.git_operation_lock:
resp = await self._run_git_cmd(f"config --get {item}")
return resp.strip()
async def checkout(self, branch: Optional[str] = None) -> None:
self._verify_repo()
async with self.git_operation_lock:
branch = branch or f"{self.git_remote}/{self.git_branch}"
await self._run_git_cmd(f"checkout {branch} -q")
async def run_fsck(self) -> None:
async with self.git_operation_lock:
await self._run_git_cmd("fsck --full", timeout=300., retries=1)
async def clone(self) -> None:
async with self.git_operation_lock:
self.cmd_helper.notify_update_response(
f"Git Repo {self.alias}: Starting Clone Recovery...")
if self.backup_path.exists():
shutil.rmtree(self.backup_path)
self._check_lock_file_exists(remove=True)
git_cmd = f"clone {self.origin_url} {self.backup_path}"
try:
await self._run_git_cmd_async(git_cmd, 1, False, False)
except Exception as e:
self.cmd_helper.notify_update_response(
f"Git Repo {self.alias}: Git Clone Failed")
raise self.server.error("Git Clone Error") from e
if self.git_path.exists():
shutil.rmtree(self.git_path)
shutil.move(str(self.backup_path), str(self.git_path))
self.cmd_helper.notify_update_response(
f"Git Repo {self.alias}: Git Clone Complete")
async def get_commits_behind(self) -> List[Dict[str, Any]]:
self._verify_repo()
if self.is_current():
return []
async with self.git_operation_lock:
branch = f"{self.git_remote}/{self.git_branch}"
resp = await self._run_git_cmd(
f"log {self.current_commit}..{branch} "
f"--format={GIT_LOG_FMT} --max-count={GIT_MAX_LOG_CNT}")
commits_behind: List[Dict[str, Any]] = []
for log_entry in resp.split('\x1E'):
log_entry = log_entry.strip()
if not log_entry:
continue
log_items = [li.strip() for li in log_entry.split('\x1D')
if li.strip()]
cbh = [li.split(':', 1) for li in log_items]
commits_behind.append(dict(cbh)) # type: ignore
return commits_behind
async def get_tagged_commits(self) -> Dict[str, Any]:
self._verify_repo()
async with self.git_operation_lock:
resp = await self._run_git_cmd(f"show-ref --tags -d")
tagged_commits: Dict[str, Any] = {}
tags = [tag.strip() for tag in resp.split('\n') if tag.strip()]
for tag in tags:
sha, ref = tag.split(' ', 1)
ref = ref.split('/')[-1]
if ref[-3:] == "^{}":
# Dereference this commit and overwrite any existing tag
ref = ref[:-3]
tagged_commits[ref] = sha
elif ref not in tagged_commits:
# This could be a lightweight tag pointing to a commit. If
# it is an annotated tag it will be overwritten by the
# dereferenced tag
tagged_commits[ref] = sha
# Return tagged commits as SHA keys mapped to tag values
return {v: k for k, v in tagged_commits.items()}
def get_repo_status(self) -> Dict[str, Any]:
return {
'detected_type': "git_repo",
'remote_alias': self.git_remote,
'branch': self.git_branch,
'owner': self.git_owner,
'version': self.current_version,
'remote_version': self.upstream_version,
'current_hash': self.current_commit,
'remote_hash': self.upstream_commit,
'is_dirty': self.dirty,
'detached': self.head_detached,
'commits_behind': self.commits_behind,
'git_messages': self.git_messages,
'full_version_string': self.full_version_string,
'pristine': not self.dirty
}
def get_version(self, upstream: bool = False) -> Tuple[Any, ...]:
version = self.upstream_version if upstream else self.current_version
return tuple(re.findall(r"\d+", version))
def is_detached(self) -> bool:
return self.head_detached
def is_dirty(self) -> bool:
return self.dirty
def is_current(self) -> bool:
return self.current_commit == self.upstream_commit
def _check_lock_file_exists(self, remove: bool = False) -> bool:
lock_path = self.git_path.joinpath(".git/index.lock")
if lock_path.is_file():
if remove:
logging.info(f"Git Repo {self.alias}: Git lock file found "
"after git process exited, removing")
try:
os.remove(lock_path)
except Exception:
pass
return True
return False
async def _wait_for_lock_release(self, timeout: int = 60) -> None:
while timeout:
if self._check_lock_file_exists():
if not timeout % 10:
logging.info(f"Git Repo {self.alias}: Git lock file "
f"exists, {timeout} seconds remaining "
"before removal.")
await asyncio.sleep(1.)
timeout -= 1
else:
return
self._check_lock_file_exists(remove=True)
async def _repair_loose_objects(self) -> bool:
try:
await self.cmd_helper.run_cmd_with_response(
"find .git/objects/ -type f -empty | xargs rm",
timeout=10., retries=1, cwd=str(self.git_path))
await self._run_git_cmd_async(
"fetch --all -p", retries=1, fix_loose=False)
await self._run_git_cmd("fsck --full", timeout=300., retries=1)
except Exception:
logging.exception("Attempt to repair loose objects failed")
return False
return True
async def _run_git_cmd_async(self,
cmd: str,
retries: int = 5,
need_git_path: bool = True,
fix_loose: bool = True
) -> None:
# Fetch and pull require special handling. If the request
# gets delayed we do not want to terminate it while the command
# is processing.
await self._wait_for_lock_release()
env = os.environ.copy()
env.update(GIT_ENV_VARS)
if need_git_path:
git_cmd = f"git -C {self.git_path} {cmd}"
else:
git_cmd = f"git {cmd}"
scmd = self.cmd_helper.build_shell_command(
git_cmd, callback=self._handle_process_output,
env=env)
while retries:
self.git_messages.clear()
ioloop = IOLoop.current()
self.fetch_input_recd = False
self.fetch_timeout_handle = ioloop.call_later(
GIT_ASYNC_TIMEOUT, self._check_process_active, # type: ignore
scmd, cmd)
try:
await scmd.run(timeout=0)
except Exception:
pass
ioloop.remove_timeout(self.fetch_timeout_handle)
ret = scmd.get_return_code()
if ret == 0:
self.git_messages.clear()
return
elif fix_loose:
if GIT_OBJ_ERR in "\n".join(self.git_messages):
ret = await self._repair_loose_objects()
if ret:
break
# since the attept to repair failed, bypass retries
# and immediately raise an exception
raise self.server.error(
f"Unable to repair loose objects, use hard recovery")
retries -= 1
await asyncio.sleep(.5)
self._check_lock_file_exists(remove=True)
raise self.server.error(f"Git Command '{cmd}' failed")
def _handle_process_output(self, output: bytes) -> None:
self.fetch_input_recd = True
out = output.decode().strip()
if out:
self.git_messages.append(out)
self.cmd_helper.notify_update_response(out)
logging.debug(
f"Git Repo {self.alias}: {out}")
async def _check_process_active(self,
scmd: shell_command.ShellCommand,
cmd_name: str
) -> None:
ret = scmd.get_return_code()
if ret is not None:
logging.debug(f"Git Repo {self.alias}: {cmd_name} returned")
return
if self.fetch_input_recd:
# Received some input, reschedule timeout
logging.debug(
f"Git Repo {self.alias}: {cmd_name} active, rescheduling")
ioloop = IOLoop.current()
self.fetch_input_recd = False
self.fetch_timeout_handle = ioloop.call_later(
GIT_ASYNC_TIMEOUT, self._check_process_active, # type: ignore
scmd, cmd_name)
else:
# Request has timed out with no input, terminate it
logging.debug(f"Git Repo {self.alias}: {cmd_name} timed out")
# Cancel with SIGKILL
await scmd.cancel(2)
async def _run_git_cmd(self,
git_args: str,
timeout: float = 20.,
retries: int = 5,
env: Optional[Dict[str, str]] = None
) -> str:
try:
return await self.cmd_helper.run_cmd_with_response(
f"git -C {self.git_path} {git_args}",
timeout=timeout, retries=retries, env=env, sig_idx=2)
except self.cmd_helper.scmd_error as e:
stdout = e.stdout.decode().strip()
stderr = e.stderr.decode().strip()
if stdout:
self.git_messages.append(stdout)
if stderr:
self.git_messages.append(stderr)
raise
@@ -0,0 +1,16 @@
# Supplemental configuration for Moonraker's Update Manager
# component. This file should not be modified.
[update_manager moonraker]
origin: https://github.com/arksine/moonraker.git
requirements: scripts/moonraker-requirements.txt
venv_args: -p python3
install_script: scripts/install-moonraker.sh
host_repo: arksine/moonraker
[update_manager klipper]
origin: https://github.com/kevinoconnor/klipper.git
requirements: scripts/klippy-requirements.txt
venv_args: -p python2
install_script: scripts/install-octopi.sh
host_repo: arksine/moonraker
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,416 @@
# Zip Application Deployment implementation
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import asyncio
import os
import pathlib
import json
import shutil
import re
import time
import tempfile
import zipfile
from concurrent.futures import ThreadPoolExecutor
from tornado.ioloop import IOLoop
from .app_deploy import AppDeploy
from utils import verify_source
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Tuple,
Optional,
Dict,
List,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from .update_manager import CommandHelper
RINFO_KEYS = [
"git_version", "long_version", "commit_hash", "source_checksum",
"ignored_exts", "ignored_dirs", "build_date", "channel",
"owner_repo", "host_repo", "release_tag"
]
class ZipDeploy(AppDeploy):
def __init__(self,
config: ConfigHelper,
cmd_helper: CommandHelper,
app_params: Optional[Dict[str, Any]]
) -> None:
super().__init__(config, cmd_helper, app_params)
self.official_repo: str = "?"
self.owner: str = "?"
# Extract repo from origin for validation
match = re.match(r"https?://(?:www\.)?github.com/([^/]+/[^.]+)",
self.origin)
if match is not None:
self.official_repo = match.group(1)
self.owner = self.official_repo.split('/')[0]
else:
raise config.error(
"Invalid url set for 'origin' option in section "
f"[{config.get_name()}]. Unable to extract owner/repo.")
self.host_repo: str = config.get('host_repo', self.official_repo)
self.detected_type: str = "?"
self.source_checksum: str = ""
self.pristine = False
self.verified = False
self.build_date: int = 0
self.full_version: str = "?"
self.short_version: str = "?"
self.commit_hash: str = "?"
self.lastest_hash: str = "?"
self.latest_version: str = "?"
self.latest_checksum: str = "?"
self.latest_build_date: int = 0
self.commit_log: List[Dict[str, Any]] = []
self.package_list: List[str] = []
self.python_pkg_list: List[str] = []
self.release_download_info: Tuple[str, str, int] = ("?", "?", 0)
self.errors: List[str] = []
self.mutex: asyncio.Lock = asyncio.Lock()
self.refresh_event: Optional[asyncio.Event] = None
@staticmethod
async def from_application(app: AppDeploy) -> ZipDeploy:
new_app = ZipDeploy(app.config, app.cmd_helper, app.app_params)
await new_app.reinstall()
return new_app
async def _parse_info_file(self, file_name: str) -> Dict[str, Any]:
try:
info_file = self.path.joinpath(file_name)
with ThreadPoolExecutor(max_workers=1) as tpe:
info_bytes = await IOLoop.current().run_in_executor(
tpe, info_file.read_text)
info: Dict[str, Any] = json.loads(info_bytes)
except Exception:
self.log_exc(f"Unable to parse info file {file_name}")
info = {}
return info
def _get_tag_version(self, version_string: str) -> str:
tag_version: str = "?"
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", version_string)
if ver_match:
tag_version = ver_match.group()
return tag_version
async def refresh(self) -> None:
if self.refresh_event is not None:
await self.refresh_event.wait()
return
async with self.mutex:
self.refresh_event = asyncio.Event()
try:
await self._update_repo_state()
except Exception:
self.verified = False
self.log_exc("Error refreshing application state")
self.refresh_event.set()
self.refresh_event = None
async def _update_repo_state(self) -> None:
self.errors = []
self._is_valid = False
self.verified = False
release_info = await self._parse_info_file(".release_info")
dep_info = await self._parse_info_file(".dependencies")
for key in RINFO_KEYS:
if key not in release_info:
self._add_error(f"Missing release info item: {key}")
self.detected_type = "?"
self.need_channel_update = False
if 'channel' in release_info:
local_channel = release_info['channel']
self.need_channel_update = self.channel != local_channel
self.detected_type = "zip"
if local_channel == "beta":
self.detected_type = "zip_beta"
self.full_version = release_info.get('long_version', "?")
self.short_version = self._get_tag_version(
release_info.get('git_version', ""))
self.commit_hash = release_info.get('commit_hash', "?")
self.build_date = release_info.get('build_date', 0)
owner_repo = release_info.get('owner_repo', "?")
if self.official_repo != owner_repo:
self._add_error(
f"Owner repo mismatch. Received {owner_repo}, "
f"official: {self.official_repo}")
# validate the local source code
with ThreadPoolExecutor(max_workers=1) as tpe:
res = await IOLoop.current().run_in_executor(
tpe, verify_source, self.path)
if res is not None:
self.source_checksum, self.pristine = res
if self.name in ["moonraker", "klipper"]:
self.server.add_log_rollover_item(
f"{self.name}_validation",
f"{self.name} checksum: {self.source_checksum}, "
f"pristine: {self.pristine}")
else:
self._add_error("Unable to validate source checksum")
self.source_checksum = ""
self.pristine = False
self.package_list = sorted(dep_info.get(
'debian', {}).get('packages', []))
self.python_pkg_list = sorted(dep_info.get('python', []))
# Retreive version info from github to check for updates and
# validate local release info
host_repo = release_info.get('host_repo', "?")
release_tag = release_info.get('release_tag', "?")
if host_repo != self.host_repo:
self._add_error(
f"Host repo mismatch, received: {host_repo}, "
f"expected: {self.host_repo}. This could result in "
" a failed update.")
url = f"https://api.github.com/repos/{self.host_repo}/releases"
current_release, latest_release = await self._fetch_github_releases(
url, release_tag)
await self._validate_current_release(release_info, current_release)
if not self.errors:
self.verified = True
await self._process_latest_release(latest_release)
self._log_zipapp_info()
async def _fetch_github_releases(self,
release_url: str,
current_tag: Optional[str] = None
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
try:
releases = await self.cmd_helper.github_api_request(release_url)
assert isinstance(releases, list)
except Exception:
self.log_exc("Error fetching releases from GitHub")
return {}, {}
release: Dict[str, Any]
latest_release: Dict[str, Any] = {}
current_release: Dict[str, Any] = {}
for release in releases:
if not latest_release:
if release['prerelease']:
if self.channel != "stable":
latest_release = release
elif self.channel == "stable":
latest_release = release
if current_tag is not None:
if not current_release and release['tag_name'] == current_tag:
current_release = release
if latest_release and current_release:
break
elif latest_release:
break
return current_release, latest_release
async def _validate_current_release(self,
release_info: Dict[str, Any],
release: Dict[str, Any]
) -> None:
if not release:
self._add_error("Unable to find current release on GitHub")
return
asset_info = self._get_asset_urls(release, ["RELEASE_INFO"])
if "RELEASE_INFO" not in asset_info:
self._add_error(
"RELEASE_INFO not found in current release assets")
info_url, content_type, size = asset_info['RELEASE_INFO']
rinfo_bytes = await self.cmd_helper.http_download_request(
info_url, content_type)
github_rinfo: Dict[str, Any] = json.loads(rinfo_bytes)
if github_rinfo.get(self.name, {}) != release_info:
self._add_error(
"Local release info does not match the remote")
else:
self.log_info("Current Release Info Validated")
async def _process_latest_release(self, release: Dict[str, Any]):
if not release:
self._add_error("Unable to find latest release on GitHub")
return
zip_file_name = f"{self.name}.zip"
asset_names = ["RELEASE_INFO", "COMMIT_LOG", zip_file_name]
asset_info = self._get_asset_urls(release, asset_names)
if "RELEASE_INFO" in asset_info:
asset_url, content_type, size = asset_info['RELEASE_INFO']
rinfo_bytes = await self.cmd_helper.http_download_request(
asset_url, content_type)
update_release_info: Dict[str, Any] = json.loads(rinfo_bytes)
update_info = update_release_info.get(self.name, {})
self.lastest_hash = update_info.get('commit_hash', "?")
self.latest_checksum = update_info.get('source_checksum', "?")
self.latest_version = self._get_tag_version(
update_info.get('git_version', "?"))
self.latest_build_date = update_info.get('build_date', 0)
else:
self._add_error(
"RELEASE_INFO not found in latest release assets")
self.commit_log = []
if self.short_version == self.latest_version:
# No need to report the commit log when versions match
return
if "COMMIT_LOG" in asset_info:
asset_url, content_type, size = asset_info['COMMIT_LOG']
commit_bytes = await self.cmd_helper.http_download_request(
asset_url, content_type)
commit_info: Dict[str, Any] = json.loads(commit_bytes)
self.commit_log = commit_info.get(self.name, [])
if zip_file_name in asset_info:
self.release_download_info = asset_info[zip_file_name]
self._is_valid = True
else:
self.release_download_info = ("?", "?", 0)
self._add_error(f"Release asset {zip_file_name} not found")
def _get_asset_urls(self,
release: Dict[str, Any],
filenames: List[str]
) -> Dict[str, Tuple[str, str, int]]:
asset_info: Dict[str, Tuple[str, str, int]] = {}
asset: Dict[str, Any]
for asset in release.get('assets', []):
name = asset['name']
if name in filenames:
rinfo_url = asset['browser_download_url']
content_type = asset['content_type']
size = asset['size']
asset_info[name] = (rinfo_url, content_type, size)
filenames.remove(name)
if not filenames:
break
return asset_info
def _add_error(self, warning: str):
self.log_info(warning)
self.errors.append(warning)
def _log_zipapp_info(self):
self.log_info(
"\nZip Application Distribution Detected\n"
f" Valid: {self._is_valid}\n"
f" Verified: {self.verified}\n"
f" Channel: {self.channel}\n"
f" Repo: {self.official_repo}\n"
f" Path: {self.path}\n"
f" Pristine: {self.pristine}\n"
f" Need Channel Update: {self.need_channel_update}\n"
f" Commits Behind: {len(self.commit_log)}\n"
f"Current Release Info:\n"
f" Source Checksum: {self.source_checksum}\n"
f" Commit SHA: {self.commit_hash}\n"
f" Long Version: {self.full_version}\n"
f" Short Version: {self.short_version}\n"
f" Build Date: {time.ctime(self.build_date)}\n"
f"Latest Available Release Info:\n"
f" Source Checksum: {self.latest_checksum}\n"
f" Commit SHA: {self.lastest_hash}\n"
f" Version: {self.latest_version}\n"
f" Build Date: {time.ctime(self.latest_build_date)}\n"
f" Download URL: {self.release_download_info[0]}\n"
f" Content Type: {self.release_download_info[1]}\n"
f" Download Size: {self.release_download_info[2]}"
)
async def _update_dependencies(self,
npm_hash,
force: bool = False
) -> None:
new_deps = await self._parse_info_file('.dependencies')
system_pkgs = sorted(
new_deps.get('debian', {}).get('packages', []))
python_pkgs = sorted(new_deps.get('python', []))
if system_pkgs:
if force or system_pkgs != self.package_list:
await self._install_packages(system_pkgs)
if python_pkgs:
if force or python_pkgs != self.python_pkg_list:
await self._update_virtualenv(python_pkgs)
ret = await self._check_need_update(npm_hash, self.npm_pkg_json)
if force or ret:
if self.npm_pkg_json is not None:
self.notify_status("Updating Node Packages...")
try:
await self.cmd_helper.run_cmd(
"npm ci --only=prod", notify=True, timeout=600.,
cwd=str(self.path))
except Exception:
self.notify_status("Node Package Update failed")
def _extract_release(self, release_zip: pathlib.Path) -> None:
if self.path.is_dir():
shutil.rmtree(self.path)
os.mkdir(self.path)
with zipfile.ZipFile(release_zip) as zf:
zf.extractall(self.path)
async def update(self, force_dep_update: bool = False) -> bool:
async with self.mutex:
if not self._is_valid:
raise self.log_exc("Update aborted, repo not valid", False)
if self.short_version == self.latest_version:
# already up to date
return False
self.cmd_helper.notify_update_response(
f"Updating Application {self.name}...")
npm_hash = await self._get_file_hash(self.npm_pkg_json)
dl_url, content_type, size = self.release_download_info
self.notify_status("Starting Download...")
with tempfile.TemporaryDirectory(
suffix=self.name, prefix="app") as tempdirname:
tempdir = pathlib.Path(tempdirname)
temp_download_file = tempdir.joinpath(f"{self.name}.zip")
await self.cmd_helper.streaming_download_request(
dl_url, temp_download_file, content_type, size)
self.notify_status(
f"Download Complete, extracting release to '{self.path}'")
with ThreadPoolExecutor(max_workers=1) as tpe:
await IOLoop.current().run_in_executor(
tpe, self._extract_release, temp_download_file)
await self._update_dependencies(npm_hash, force=force_dep_update)
await self._update_repo_state()
await self.restart_service()
self.notify_status("Update Finished...", is_complete=True)
return True
async def recover(self,
hard: bool = False,
force_dep_update: bool = False
) -> None:
async with self.mutex:
url = f"https://api.github.com/repos/{self.host_repo}/releases"
releases = await self._fetch_github_releases(url)
await self._process_latest_release(releases[1])
await self.update(force_dep_update=force_dep_update)
async def reinstall(self) -> None:
await self.recover(force_dep_update=True)
def get_update_status(self) -> Dict[str, Any]:
status = super().get_update_status()
# XXX - Currently this reports status matching
# that of the git repo so as to not break existing
# client functionality. In the future it would be
# good to report values that are specifc
status.update({
'detected_type': self.detected_type,
'remote_alias': "origin",
'branch': "master",
'owner': self.owner,
'version': self.short_version,
'remote_version': self.latest_version,
'current_hash': self.commit_hash,
'remote_hash': self.lastest_hash,
'is_dirty': False,
'detached': not self.verified,
'commits_behind': self.commit_log,
'git_messages': self.errors,
'full_version_string': self.full_version,
'pristine': self.pristine,
})
return status
+188
View File
@@ -0,0 +1,188 @@
# Configuration Helper
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import configparser
import os
from utils import SentinelClass
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Callable,
IO,
TypeVar,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from moonraker import Server
_T = TypeVar("_T")
ConfigVal = Union[None, int, float, bool, str]
SENTINEL = SentinelClass.get_instance()
class ConfigError(Exception):
pass
class ConfigHelper:
error = ConfigError
def __init__(self,
server: Server,
config: configparser.ConfigParser,
section: str,
orig_sects: List[str],
parsed: Dict[str, Dict[str, ConfigVal]] = {}
) -> None:
self.server = server
self.config = config
self.section = section
self.orig_sections = orig_sects
self.parsed = parsed
if self.section not in self.parsed:
self.parsed[self.section] = {}
self.sections = config.sections
self.has_section = config.has_section
def get_server(self) -> Server:
return self.server
def __getitem__(self, key: str) -> ConfigHelper:
return self.getsection(key)
def __contains__(self, key: str) -> bool:
return key in self.config
def get_name(self) -> str:
return self.section
def get_options(self) -> Dict[str, str]:
return dict(self.config[self.section])
def get_prefix_sections(self, prefix: str) -> List[str]:
return [s for s in self.sections() if s.startswith(prefix)]
def getsection(self, section: str) -> ConfigHelper:
if section not in self.config:
raise ConfigError(f"No section [{section}] in config")
return ConfigHelper(self.server, self.config, section,
self.orig_sections, self.parsed)
def _get_option(self,
func: Callable[..., Any],
option: str,
default: Union[SentinelClass, _T]
) -> _T:
try:
val = func(option, default)
except Exception:
raise ConfigError(
f"Error parsing option ({option}) from "
f"section [{self.section}]")
if isinstance(val, SentinelClass):
raise ConfigError(
f"No option found ({option}) in section [{self.section}]")
if self.section in self.orig_sections:
# Only track sections included in the original config
self.parsed[self.section][option] = val
return val
def get(self,
option: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[str, _T]:
return self._get_option(
self.config[self.section].get, option, default)
def getint(self,
option: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[int, _T]:
return self._get_option(
self.config[self.section].getint, option, default)
def getboolean(self,
option: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[bool, _T]:
return self._get_option(
self.config[self.section].getboolean, option, default)
def getfloat(self,
option: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[float, _T]:
return self._get_option(
self.config[self.section].getfloat, option, default)
def read_supplemental_config(self, file_name: str) -> ConfigHelper:
cfg_file_path = os.path.normpath(os.path.expanduser(file_name))
if not os.path.isfile(cfg_file_path):
raise ConfigError(
f"Configuration File Not Found: '{cfg_file_path}''")
try:
sup_cfg = configparser.ConfigParser(interpolation=None)
sup_cfg.read(cfg_file_path)
except Exception:
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'")
sections = sup_cfg.sections()
return ConfigHelper(self.server, sup_cfg, sections[0], sections)
def write_config(self, file_obj: IO[str]) -> None:
self.config.write(file_obj)
def get_parsed_config(self) -> Dict[str, Dict[str, ConfigVal]]:
return dict(self.parsed)
def validate_config(self) -> None:
for sect in self.orig_sections:
if sect not in self.parsed:
self.server.add_warning(
f"Unparsed config section [{sect}] detected. This "
"may be the result of a component that failed to "
"load. In the future this will result in a startup "
"error.")
continue
parsed_opts = self.parsed[sect]
for opt, val in self.config.items(sect):
if opt not in parsed_opts:
self.server.add_warning(
f"Invalid config option '{opt}' detected in section "
f"[{sect}]. Remove the option to resolve this issue. "
"In the future this will result in a startup error.")
def get_configuration(server: Server,
app_args: Dict[str, Any]
) -> ConfigHelper:
cfg_file_path: str = os.path.normpath(os.path.expanduser(
app_args['config_file']))
if not os.path.isfile(cfg_file_path):
raise ConfigError(
f"Configuration File Not Found: '{cfg_file_path}''")
if not os.access(cfg_file_path, os.R_OK | os.W_OK):
raise ConfigError(
"Moonraker does not have Read/Write permission for "
f"config file at path '{cfg_file_path}'")
config = configparser.ConfigParser(interpolation=None)
try:
config.read(cfg_file_path)
except Exception as e:
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'") from e
try:
server_cfg = config['server']
except KeyError:
raise ConfigError("No section [server] in config")
orig_sections = config.sections()
try:
orig_sections.remove("DEFAULT")
except Exception:
pass
return ConfigHelper(server, config, 'server', orig_sections)
Regular → Executable
+662 -363
View File
File diff suppressed because it is too large. Load diff
-490
View File
@@ -1,490 +0,0 @@
# Enhanced gcode file management and analysis
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import os
import sys
import shutil
import time
import logging
import json
from tornado.ioloop import IOLoop
from tornado.locks import Lock
VALID_GCODE_EXTS = ['gcode', 'g', 'gco']
FULL_ACCESS_ROOTS = ["gcodes", "config"]
METADATA_SCRIPT = os.path.join(
os.path.dirname(__file__), "../../scripts/extract_metadata.py")
class FileManager:
def __init__(self, server):
self.server = server
self.file_paths = {}
self.file_lists = {}
self.gcode_metadata = {}
self.metadata_lock = Lock()
self.server.register_endpoint(
"/server/files/list", "file_list", ['GET'],
self._handle_filelist_request)
self.server.register_endpoint(
"/server/files/metadata", "file_metadata", ['GET'],
self._handle_metadata_request)
self.server.register_endpoint(
"/server/files/directory", "directory", ['GET', 'POST', 'DELETE'],
self._handle_directory_request)
self.server.register_endpoint(
"/server/files/move", "file_move", ['POST'],
self._handle_file_move_copy)
self.server.register_endpoint(
"/server/files/copy", "file_copy", ['POST'],
self._handle_file_move_copy)
# Register APIs to handle file uploads
self.server.register_upload_handler("/server/files/upload")
self.server.register_upload_handler("/api/files/local")
def load_config(self, config):
# Gcode Files
sd = config.get('sd_path', None)
if sd is not None:
sd = os.path.normpath(os.path.expanduser(sd))
if sd != self.file_paths.get('gcodes', ""):
self.file_paths['gcodes'] = sd
self.server.register_static_file_handler(
'/server/files/gcodes/', sd, can_delete=True,
op_check_cb=self._handle_operation_check)
try:
self._update_file_list()
except Exception:
logging.exception("Unable to initialize gcode file list")
# Configuration files in the optional config path
cfg_path = config.get('printer_config_path', None)
if cfg_path is not None:
cfg_path = os.path.normpath(os.path.expanduser(cfg_path))
if cfg_path != self.file_paths.get('config', ""):
self.file_paths['config'] = cfg_path
self.server.register_static_file_handler(
"/server/files/config/", cfg_path,
can_delete=True)
try:
self._update_file_list(base='config')
except Exception:
logging.exception("Unable to initialize config file list")
# Register path for example configs
klipper_path = config.get('klipper_path', None)
if klipper_path is not None:
example_cfg_path = os.path.join(klipper_path, "config")
if example_cfg_path != self.file_paths.get("config_examples", ""):
self.file_paths['config_examples'] = example_cfg_path
self.server.register_static_file_handler(
"/server/files/config_examples/", example_cfg_path)
try:
self._update_file_list(base='config_examples')
except Exception:
logging.exception(
"Unable to initialize config_examples file list")
def get_sd_directory(self):
return self.file_paths.get('gcodes', "")
async def _handle_filelist_request(self, path, method, args):
root = args.get('root', "gcodes")
return self.get_file_list(format_list=True, base=root)
async def _handle_metadata_request(self, path, method, args):
requested_file = args.get('filename')
metadata = self.gcode_metadata.get(requested_file)
if metadata is None:
raise self.server.error(
"Metadata not available for <%s>" % (requested_file), 404)
metadata['filename'] = requested_file
return metadata
async def _handle_directory_request(self, path, method, args):
directory = args.get('path', "gcodes")
base, url_path, dir_path = self._convert_path(directory)
method = method.upper()
if method == 'GET':
# Get list of files and subdirectories for this target
return self._list_directory(dir_path)
elif method == 'POST' and base in FULL_ACCESS_ROOTS:
# Create a new directory
try:
os.mkdir(dir_path)
except Exception as e:
raise self.server.error(str(e))
self.notify_filelist_changed(url_path, "add_directory", base)
elif method == 'DELETE' and base in FULL_ACCESS_ROOTS:
# Remove a directory
if directory.strip("/") == base:
raise self.server.error(
"Cannot delete root directory")
if not os.path.isdir(dir_path):
raise self.server.error(
"Directory does not exist (%s)" % (directory))
force = args.get('force', False)
if isinstance(force, str):
force = force.lower() == "true"
if force:
# Make sure that the directory does not contain a file
# loaded by the virtual_sdcard
await self._handle_operation_check(dir_path)
shutil.rmtree(dir_path)
else:
try:
os.rmdir(dir_path)
except Exception as e:
raise self.server.error(str(e))
self.notify_filelist_changed(url_path, "delete_directory", base)
else:
raise self.server.error("Operation Not Supported", 405)
return "ok"
async def _handle_operation_check(self, requested_path):
# Get virtual_sdcard status
request = self.server.make_request(
"objects/status", 'GET', {'virtual_sdcard': []})
result = await request.wait()
if isinstance(result, self.server.error):
raise result
vsd = result.get('virtual_sdcard', {})
loaded_file = vsd.get('filename', "")
gc_path = self.file_paths.get('gcodes', "")
full_path = os.path.join(gc_path, loaded_file)
if os.path.isdir(requested_path):
# Check to see of the loaded file is in the reques
if full_path.startswith(requested_path):
raise self.server.error("File currently in use", 403)
elif full_path == requested_path:
raise self.server.error("File currently in use", 403)
ongoing = vsd.get('total_duration', 0.) > 0.
return ongoing
def _convert_path(self, url_path):
parts = url_path.strip("/").split("/")
if not parts:
raise self.server.error("Invalid path: " % (url_path))
base = parts[0]
if base not in self.file_paths:
raise self.server.error("Invalid base path (%s)" % (base))
root_path = local_path = self.file_paths[base]
url_path = ""
if len(parts) > 1:
url_path = "/".join(parts[1:])
local_path = os.path.join(root_path, url_path)
return base, url_path, local_path
async def _handle_file_move_copy(self, path, method, args):
source = args.get("source")
destination = args.get("dest")
if source is None:
raise self.server.error("File move/copy request issing source")
if destination is None:
raise self.server.error(
"File move/copy request missing destination")
source_base, src_url_path, source_path = self._convert_path(source)
dest_base, dst_url_path, dest_path = self._convert_path(destination)
if dest_base not in FULL_ACCESS_ROOTS:
raise self.server.error(
"Destination path is read-only: %s" % (dest_base))
if not os.path.exists(source_path):
raise self.server.error("File %s does not exist" % (source_path))
# make sure the destination is not in use
if os.path.exists(dest_path):
await self._handle_operation_check(dest_path)
action = ""
if path == "/server/files/move":
if source_base not in FULL_ACCESS_ROOTS:
raise self.server.error(
"Source path is read-only, cannot move: %s"
% (source_base))
# if moving the file, make sure the source is not in use
await self._handle_operation_check(source_path)
try:
shutil.move(source_path, dest_path)
except Exception as e:
raise self.server.error(str(e))
action = "file_move"
elif path == "/server/files/copy":
try:
if os.path.isdir(source_path):
shutil.copytree(source_path, dest_path)
else:
shutil.copy2(source_path, dest_path)
except Exception as e:
raise self.server.error(str(e))
action = "file_copy"
self.notify_filelist_changed(
dst_url_path, action, dest_base,
{'prev_file': src_url_path, 'prev_root': source_base})
return "ok"
def _list_directory(self, path):
if not os.path.isdir(path):
raise self.server.error(
"Directory does not exist (%s)" % (path))
flist = {'dirs': [], 'files': []}
for fname in os.listdir(path):
full_path = os.path.join(path, fname)
modified = time.ctime(os.path.getmtime(full_path))
if os.path.isdir(full_path):
flist['dirs'].append({
'dirname': fname,
'modified': modified
})
elif os.path.isfile(full_path):
size = os.path.getsize(full_path)
flist['files'].append(
{'filename': fname,
'modified': modified,
'size': size})
return flist
def _shell_proc_callback(self, result):
try:
proc_resp = json.loads(result.strip())
except Exception:
logging.exception("file_manager: unable to load metadata")
logging.debug(result)
return
proc_log = proc_resp.get('log', [])
for log_msg in proc_log:
logging.info(log_msg)
file_path = proc_resp.pop('file', None)
if file_path is not None:
self.gcode_metadata[file_path] = proc_resp.get('metadata')
async def _update_metadata(self):
async with self.metadata_lock:
exisiting_data = {}
update_list = []
gc_files = dict(self.file_lists.get('gcodes', {}))
gc_path = self.file_paths.get('gcodes', "")
for fname, fdata in gc_files.items():
mdata = self.gcode_metadata.get(fname, {})
if mdata.get('size', "") == fdata.get('size') \
and mdata.get('modified', "") == fdata.get('modified'):
# file metadata has already been extracted
exisiting_data[fname] = mdata
else:
update_list.append(fname)
self.gcode_metadata = exisiting_data
for fname in update_list:
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
gc_path, "-f", "'" + fname + "'"])
shell_command = self.server.lookup_plugin('shell_command')
scmd = shell_command.build_shell_command(
cmd, self._shell_proc_callback)
try:
await scmd.run(timeout=4.)
except Exception:
logging.exception("Error running extract_metadata.py")
def _update_file_list(self, base='gcodes'):
# Use os.walk find files in sd path and subdirs
path = self.file_paths.get(base, None)
if path is None:
msg = "No known path for root: %s" % (base)
logging.info(msg)
raise self.server.error(msg)
elif not os.path.isdir(path):
msg = "Cannot generate file list for root: %s" % (base)
logging.info(msg)
raise self.server.error(msg)
logging.info("Updating File List <%s>..." % (base))
new_list = {}
for root, dirs, files in os.walk(path, followlinks=True):
for name in files:
ext = name[name.rfind('.')+1:]
if base == 'gcodes' and ext not in VALID_GCODE_EXTS:
continue
full_path = os.path.join(root, name)
r_path = full_path[len(path) + 1:]
size = os.path.getsize(full_path)
modified = time.ctime(os.path.getmtime(full_path))
new_list[r_path] = {'size': size, 'modified': modified}
self.file_lists[base] = new_list
if base == 'gcodes':
ioloop = IOLoop.current()
ioloop.spawn_callback(self._update_metadata)
return dict(new_list)
async def process_file_upload(self, request):
# lookup root file path
root = self._get_argument(request, 'root', "gcodes")
if root == "gcodes":
result = await self._do_gcode_upload(request)
elif root in FULL_ACCESS_ROOTS:
result = self._do_standard_upload(request, root)
else:
raise self.server.error("Invalid root request: %s" % (root))
return result
async def _do_gcode_upload(self, request):
start_print = print_ongoing = False
base_path = self.file_paths.get("gcodes", "")
if not base_path:
raise self.server.error("Gcodes root not available")
start_print = self._get_argument(request, 'print', "false") == "true"
upload = self._get_upload_info(request, base_path)
# Verify that the operation can be done if attempting to upload a gcode
try:
print_ongoing = await self._handle_operation_check(
upload['full_path'])
except self.server.error as e:
if e.status_code == 403:
raise self.server.error(
"File is loaded, upload not permitted", 403)
else:
# Couldn't reach Klippy, so it should be safe
# to permit the upload but not start
start_print = False
# Don't start if another print is currently in progress
start_print = start_print and not print_ongoing
self._write_file(upload)
if start_print:
# Make a Klippy Request to "Start Print"
gcode_apis = self.server.lookup_plugin('gcode_apis')
try:
await gcode_apis.gcode_start_print(
request.path, 'POST', {'filename': upload['filename']})
except self.server.error:
# Attempt to start print failed
start_print = False
self.notify_filelist_changed(upload['filename'], 'added', "gcodes")
return {'result': upload['filename'], 'print_started': start_print}
def _do_standard_upload(self, request, root):
path = self.file_paths.get(root, None)
if path is None:
raise self.server.error("Unknown root path: %s" % (root))
upload = self._get_upload_info(request, path)
self._write_file(upload)
self.notify_filelist_changed(upload['filename'], 'added', root)
return {'result': upload['filename']}
def _get_argument(self, request, name, default=None):
args = request.arguments.get(name, None)
if args is not None:
return args[0].decode().strip()
return default
def _get_upload_info(self, request, base_path):
# check relative path
dir_path = self._get_argument(request, 'path', "")
# fetch the upload from the request
if len(request.files) != 1:
raise self.server.error(
"Bad Request, can only process a single file upload")
f_list = list(request.files.values())[0]
if len(f_list) != 1:
raise self.server.error(
"Bad Request, can only process a single file upload")
upload = f_list[0]
if os.path.isfile(base_path):
filename = os.path.basename(base_path)
full_path = base_path
dir_path = ""
else:
filename = "_".join(upload['filename'].strip().split()).lstrip("/")
if dir_path:
filename = os.path.join(dir_path, filename)
full_path = os.path.normpath(os.path.join(base_path, filename))
# Validate the path. Don't allow uploads to a parent of the root
if not full_path.startswith(base_path):
raise self.server.error(
"Cannot write to path: %s" % (full_path))
return {
'filename': filename,
'body': upload['body'],
'dir_path': dir_path,
'full_path': full_path}
def _write_file(self, upload):
try:
if upload['dir_path']:
os.makedirs(os.path.dirname(upload['full_path']), exist_ok=True)
with open(upload['full_path'], 'wb') as fh:
fh.write(upload['body'])
except Exception:
raise self.server.error("Unable to save file", 500)
def get_file_list(self, format_list=False, base='gcodes'):
try:
filelist = self._update_file_list(base)
except Exception:
msg = "Unable to update file list"
logging.exception(msg)
raise self.server.error(msg)
if format_list:
flist = []
for fname in sorted(filelist, key=str.lower):
fdict = {'filename': fname}
fdict.update(filelist[fname])
flist.append(fdict)
return flist
return filelist
def get_file_metadata(self, filename):
if filename[0] == '/':
filename = filename[1:]
# Remove "gcodes" of its added. It is valid for a request to
# include to the root or assume the root is gcodes
if filename.startswith('gcodes/'):
filename = filename[7:]
flist = self.get_file_list()
return self.gcode_metadata.get(filename, flist.get(filename, {}))
def list_dir(self, directory, simple_format=False):
# List a directory relative to its root. Currently the only
# Supported root is "gcodes"
if directory[0] == "/":
directory = directory[1:]
parts = directory.split("/", 1)
root = parts[0]
if root not in self.file_paths:
raise self.server.error(
"Invalid Directory Request: %s" % (directory))
path = self.file_paths[root]
if len(parts) == 1:
dir_path = path
else:
dir_path = os.path.join(path, parts[1])
if not os.path.isdir(dir_path):
raise self.server.error(
"Directory does not exist (%s)" % (dir_path))
flist = self._list_directory(dir_path)
if simple_format:
simple_list = []
for dirobj in flist['dirs']:
simple_list.append("*" + dirobj['dirname'])
for fileobj in flist['files']:
fname = fileobj['filename']
ext = fname[fname.rfind('.')+1:]
if root == "gcodes" and ext in VALID_GCODE_EXTS:
simple_list.append(fname)
return simple_list
return flist
def delete_file(self, path):
parts = path.split("/", 1)
root = parts[0]
if root not in self.file_paths or len(parts) != 2:
raise self.server.error("Invalid file path: %s" % (path))
root_path = self.file_paths[root]
full_path = os.path.join(root_path, parts[1])
if not os.path.isfile(full_path):
raise self.server.error("Invalid file path: %s" % (path))
os.remove(full_path)
def notify_filelist_changed(self, fname, action, base, params={}):
self._update_file_list(base)
result = {'filename': fname, 'action': action, 'root': base}
if params:
result.update(params)
self.server.send_event("file_manager:filelist_changed", result)
def load_plugin(server):
return FileManager(server)
-67
View File
@@ -1,67 +0,0 @@
# Map HTTP/Websocket APIs for specific gcode tasks
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
GCODE_ENDPOINT = "gcode/script"
class GCodeAPIs:
def __init__(self, server):
self.server = server
# Register GCode Endpoints
self.server.register_endpoint(
"/printer/print/pause", "printer_print_pause", ['POST'],
self.gcode_pause)
self.server.register_endpoint(
"/printer/print/resume", "printer_print_resume", ['POST'],
self.gcode_resume)
self.server.register_endpoint(
"/printer/print/cancel", "printer_print_cancel", ['POST'],
self.gcode_cancel)
self.server.register_endpoint(
"/printer/print/start", "printer_print_start", ['POST'],
self.gcode_start_print)
self.server.register_endpoint(
"/printer/restart", "printer_restart", ['POST'],
self.gcode_restart)
self.server.register_endpoint(
"/printer/firmware_restart", "printer_firmware_restart", ['POST'],
self.gcode_firmware_restart)
async def _send_gcode(self, script):
args = {'script': script}
request = self.server.make_request(
GCODE_ENDPOINT, 'POST', args)
result = await request.wait()
if isinstance(result, self.server.error):
raise result
return result
async def gcode_pause(self, path, method, args):
return await self._send_gcode("PAUSE")
async def gcode_resume(self, path, method, args):
return await self._send_gcode("RESUME")
async def gcode_cancel(self, path, method, args):
return await self._send_gcode("CANCEL_PRINT")
async def gcode_start_print(self, path, method, args):
filename = args.get('filename')
# XXX - validate that file is on disk
if filename[0] != '/':
filename = '/' + filename
script = "M23 " + filename + "\nM24"
return await self._send_gcode(script)
async def gcode_restart(self, path, method, args):
return await self._send_gcode("RESTART")
async def gcode_firmware_restart(self, path, method, args):
return await self._send_gcode("FIRMWARE_RESTART")
def load_plugin(server):
return GCodeAPIs(server)
-34
View File
@@ -1,34 +0,0 @@
# Machine manipulation request handlers
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
class Machine:
def __init__(self, server):
self.server = server
self.server.register_endpoint(
"/machine/reboot", "machine_reboot", ['POST'],
self._handle_machine_request)
self.server.register_endpoint(
"/machine/shutdown", "machine_shutdown", ['POST'],
self._handle_machine_request)
async def _handle_machine_request(self, path, method, args):
if path == "/machine/shutdown":
cmd = "sudo shutdown now"
elif path == "/machine/reboot":
cmd = "sudo reboot now"
else:
raise self.server.error("Unsupported machine request")
shell_command = self.server.lookup_plugin('shell_command')
scmd = shell_command.build_shell_command(cmd, None)
try:
await scmd.run(timeout=2., verbose=False)
except Exception:
logging.exception("Error running cmd '%s'" % (cmd))
return "ok"
def load_plugin(server):
return Machine(server)
-685
View File
@@ -1,685 +0,0 @@
# PanelDue LCD display support
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import serial
import os
import time
import json
import errno
import logging
import tempfile
from utils import ServerError
from tornado import gen, netutil
from tornado.ioloop import IOLoop
from tornado.locks import Lock
MIN_EST_TIME = 10.
class PanelDueError(ServerError):
pass
class SerialConnection:
def __init__(self, paneldue):
self.ioloop = IOLoop.current()
self.paneldue = paneldue
self.port = ""
self.baud = 57200
self.sendlock = Lock()
self.partial_input = b""
self.ser = self.fd = None
self.connected = False
def load_config(self, config):
port = config.get('serial', None)
baud = int(config.get('baud', 57200))
if port is None:
logging.info("No serial port specified, cannot connect")
return
if port != self.port or baud != self.baud or \
not self.connected:
self.disconnect()
self.port = port
self.baud = baud
self.ioloop.spawn_callback(self._connect)
def disconnect(self):
if self.connected:
if self.fd is not None:
self.ioloop.remove_handler(self.fd)
self.fd = None
self.connected = False
self.ser.close()
self.ser = None
logging.info("PanelDue Disconnected")
async def _connect(self):
start_time = connect_time = time.time()
while not self.connected:
if connect_time > start_time + 30.:
logging.info("Unable to connect, aborting")
break
logging.info("Attempting to connect to: %s" % (self.port))
try:
# XXX - sometimes the port cannot be exclusively locked, this
# would likely be due to a restart where the serial port was
# not correctly closed. Maybe don't use exclusive mode?
self.ser = serial.Serial(
self.port, self.baud, timeout=0, exclusive=True)
except (OSError, IOError, serial.SerialException):
logging.exception("Unable to open port: %s" % (self.port))
await gen.sleep(2.)
connect_time += time.time()
continue
self.fd = self.ser.fileno()
os.set_blocking(self.fd, False)
self.ioloop.add_handler(
self.fd, self._handle_incoming, IOLoop.READ | IOLoop.ERROR)
self.connected = True
logging.info("PanelDue Connected")
def _handle_incoming(self, fd, events):
if events & IOLoop.ERROR:
logging.info("PanelDue Connection Error")
self.disconnect()
return
# Process incoming data using same method as gcode.py
try:
data = os.read(fd, 4096)
except os.error:
return
if not data:
# possibly an error, disconnect
self.disconnect()
logging.info("serial_display: No data received, disconnecting")
return
self.ioloop.spawn_callback(self._process_data, data)
async def _process_data(self, data):
# Remove null bytes, separate into lines
data = data.strip(b'\x00')
lines = data.split(b'\n')
lines[0] = self.partial_input + lines[0]
self.partial_input = lines.pop()
for line in lines:
line = line.strip().decode()
try:
await self.paneldue.process_line(line)
except ServerError:
logging.exception(
"GCode Processing Error: " + line)
self.paneldue.handle_gcode_response(
"!! GCode Processing Error: " + line)
except Exception:
logging.exception("Error during gcode processing")
async def send(self, data):
if self.connected:
async with self.sendlock:
while data:
try:
sent = os.write(self.fd, data)
except os.error as e:
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
sent = 0
else:
await gen.sleep(.001)
continue
if sent:
data = data[sent:]
else:
logging.exception(
"Error writing data, closing serial connection")
self.disconnect()
return
class PanelDue:
def __init__(self, server):
self.server = server
self.ioloop = IOLoop.current()
self.ser_conn = SerialConnection(self)
self.file_manager = self.server.load_plugin('file_manager')
self.kinematics = "none"
self.machine_name = "Klipper"
self.firmware_name = "Repetier | Klipper"
self.last_message = None
self.last_gcode_response = None
self.current_file = ""
self.file_metadata = {}
# Initialize tracked state.
self.printer_state = {
'gcode': {}, 'toolhead': {}, 'virtual_sdcard': {},
'pause_resume': {}, 'fan': {}, 'display_status': {}}
self.available_macros = {}
self.non_trivial_keys = []
self.extruder_count = 0
self.heaters = []
self.is_ready = False
self.is_shutdown = False
# Register server events
self.server.register_event_handler(
"server:klippy_state_changed", self.handle_klippy_state)
self.server.register_event_handler(
"server:status_update", self.handle_status_update)
self.server.register_event_handler(
"server:gcode_response", self.handle_gcode_response)
self.server.register_remote_method(
"paneldue_beep", self.handle_paneldue_beep)
# These commands are directly executued on the server and do not to
# make a request to Klippy
self.direct_gcodes = {
'M20': self._run_paneldue_M20,
'M30': self._run_paneldue_M30,
'M36': self._run_paneldue_M36,
'M408': self._run_paneldue_M408
}
# These gcodes require special parsing or handling prior to being
# sent via Klippy's "gcode/script" api command.
self.special_gcodes = {
'M0': lambda args: "CANCEL_PRINT",
'M23': self._prepare_M23,
'M24': lambda args: "RESUME",
'M25': lambda args: "PAUSE",
'M32': self._prepare_M32,
'M98': self._prepare_M98,
'M120': lambda args: "SAVE_GCODE_STATE STATE=PANELDUE",
'M121': lambda args: "RESTORE_GCODE_STATE STATE=PANELDUE",
'M290': self._prepare_M290,
'M999': lambda args: "FIRMWARE_RESTART"
}
def load_config(self, config):
self.ser_conn.load_config(config)
self.machine_name = config.get('machine_name', self.machine_name)
macros = config.get('macros', None)
if macros is not None:
# The macro's configuration name is the key, whereas the full
# command is the value
macros = [m for m in macros.split('\n') if m.strip()]
self.available_macros = {m.split()[0]: m for m in macros}
else:
self.available_macros = {}
ntkeys = config.get('non_trivial_keys', "Klipper state")
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
self.ioloop.spawn_callback(self.write_response, {'status': 'C'})
logging.info("PanelDue Configured")
async def _klippy_request(self, command, method='GET', args={}):
request = self.server.make_request(command, method, args)
result = await request.wait()
if isinstance(result, self.server.error):
raise PanelDueError(str(result))
return result
async def handle_klippy_state(self, state):
if state == "ready":
await self._process_klippy_ready()
elif state == "shutdown":
await self._process_klippy_shutdown()
elif state == "disconnect":
await self._process_klippy_disconnect()
async def _process_klippy_ready(self):
# Request "info" and "configfile" status
retries = 10
while retries:
try:
printer_info = await self._klippy_request("info")
cfg_status = await self._klippy_request(
"objects/status", args={'configfile': []})
except PanelDueError:
logging.exception("PanelDue initialization request failed")
retries -= 1
if not retries:
raise
await gen.sleep(1.)
continue
break
self.firmware_name = "Repetier | Klipper " + printer_info['version']
config = cfg_status.get('configfile', {}).get('config', {})
printer_cfg = config.get('printer', {})
self.kinematics = printer_cfg.get('kinematics', "none")
logging.info(
"PanelDue Config Received:\n"
"Firmware Name: %s\n"
"Kinematics: %s\n"
"Printer Config: %s\n"
% (self.firmware_name, self.kinematics, str(config)))
# Initalize printer state and make subscription request
self.printer_state = {
'gcode': {}, 'toolhead': {}, 'virtual_sdcard': {},
'pause_resume': {}, 'fan': {}, 'display_status': {}}
sub_args = {'gcode': [], 'toolhead': []}
self.extruder_count = 0
self.heaters = []
for cfg in config:
if cfg.startswith("extruder"):
self.extruder_count += 1
self.printer_state[cfg] = {}
self.heaters.append(cfg)
sub_args[cfg] = []
elif cfg == "heater_bed":
self.printer_state[cfg] = {}
self.heaters.append(cfg)
sub_args[cfg] = []
elif cfg in self.printer_state:
sub_args[cfg] = []
try:
await self._klippy_request(
"objects/subscription", method='POST', args=sub_args)
except PanelDueError:
logging.exception("Unable to complete subscription request")
self.is_shutdown = False
self.is_ready = True
async def _process_klippy_shutdown(self):
self.is_shutdown = True
async def _process_klippy_disconnect(self):
# Tell the PD that we are shutting down
await self.write_response({'status': 'S'})
self.is_ready = False
async def handle_status_update(self, status):
self.printer_state.update(status)
def handle_paneldue_beep(self, frequency, duration):
duration = int(duration * 1000.)
self.ioloop.spawn_callback(
self.write_response,
{'beep_freq': frequency, 'beep_length': duration})
async def process_line(self, line):
# If we find M112 in the line then skip verification
if "M112" in line.upper():
await self._klippy_request("emergency_stop", method='POST')
return
# Get line number
line_index = line.find(' ')
try:
line_no = int(line[1:line_index])
except Exception:
line_index = -1
line_no = None
# Verify checksum
cs_index = line.rfind('*')
try:
checksum = int(line[cs_index+1:])
except Exception:
# Invalid checksum, do not process
msg = "!! Invalid Checksum"
if line_no is not None:
msg = " Line Number: %d" % line_no
logging.exception("PanelDue: " + msg)
raise PanelDueError(msg)
# Checksum is calculated by XORing every byte in the line other
# than the checksum itself
calculated_cs = 0
for c in line[:cs_index]:
calculated_cs ^= ord(c)
if calculated_cs & 0xFF != checksum:
msg = "!! Invalid Checksum"
if line_no is not None:
msg = " Line Number: %d" % line_no
logging.info("PanelDue: " + msg)
raise PanelDueError(msg)
await self._run_gcode(line[line_index+1:cs_index])
async def _run_gcode(self, script):
# Execute the gcode. Check for special RRF gcodes that
# require special handling
parts = script.split()
cmd = parts[0].strip()
# Check for commands that query state and require immediate response
if cmd in self.direct_gcodes:
params = {}
for p in parts[1:]:
arg = p[0].lower() if p[0].lower() in "psr" else "p"
try:
val = int(p[1:].strip()) if arg in "sr" else p[1:].strip()
except Exception:
msg = "paneldue: Error parsing direct gcode %s" % (script)
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
return
params["arg_" + arg] = val
func = self.direct_gcodes[cmd]
await func(**params)
return
# Prepare GCodes that require special handling
if cmd in self.special_gcodes:
func = self.special_gcodes[cmd]
script = func(parts[1:])
try:
args = {'script': script}
await self._klippy_request(
"gcode/script", method='POST', args=args)
except PanelDueError:
msg = "Error executing script %s" % script
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
def _clean_filename(self, filename):
# Remove drive number
if filename.startswith("0:/"):
filename = filename[3:]
# Remove initial "gcodes" folder. This is necessary
# due to the HACK in the paneldue_M20 gcode.
if filename.startswith("gcodes/"):
filename = filename[6:]
elif filename.startswith("/gcodes/"):
filename = filename[7:]
# Start with a "/" so the gcode parser can correctly
# handle files that begin with digits or special chars
if filename[0] != "/":
filename = "/" + filename
return filename
def _prepare_M23(self, args):
filename = self._clean_filename(args[0].strip())
return "M23 " + filename
def _prepare_M32(self, args):
filename = self._clean_filename(args[0].strip())
return "M23 " + filename + "\n" + "M24"
def _prepare_M98(self, args):
macro = args[0][1:].strip()
name_start = macro.rfind('/') + 1
macro = macro[name_start:]
cmd = self.available_macros.get(macro)
if cmd is None:
raise PanelDueError("Macro %s invalid" % (macro))
return cmd
def _prepare_M290(self, args):
# args should in in the format Z0.02
offset = args[0][1:].strip()
return "SET_GCODE_OFFSET Z_ADJUST=%s MOVE=1" % (offset)
def handle_gcode_response(self, response):
# Only queue up "non-trivial" gcode responses. At the
# moment we'll handle state changes and errors
if "Klipper state" in response \
or response.startswith('!!'):
self.last_gcode_response = response
else:
for key in self.non_trivial_keys:
if key in response:
self.last_gcode_response = response
return
async def write_response(self, response):
byte_resp = json.dumps(response) + "\r\n"
await self.ser_conn.send(byte_resp.encode())
def _get_printer_status(self):
# PanelDue States applicable to Klipper:
# I = idle, P = printing from SD, S = stopped (shutdown),
# C = starting up (not ready), A = paused, D = pausing,
# B = busy
if self.is_shutdown:
return 'S'
printer_state = self.printer_state
is_active = printer_state['virtual_sdcard'].get('is_active', False)
paused = printer_state['pause_resume'].get('is_paused', False)
if paused:
if is_active:
return 'D'
else:
return 'A'
if is_active:
return 'P'
if printer_state['gcode'].get('busy', False):
return 'B'
return 'I'
async def _run_paneldue_M408(self, arg_r=None, arg_s=1):
response = {}
sequence = arg_r
response_type = arg_s
if not self.is_ready:
# Klipper is still starting up, do not query status
response['status'] = 'S' if self.is_shutdown else 'C'
await self.write_response(response)
return
# Send gcode responses
if sequence is not None and self.last_gcode_response:
response['seq'] = sequence + 1
response['resp'] = self.last_gcode_response
self.last_gcode_response = None
if response_type == 1:
# Extended response Request
response['myName'] = self.machine_name
response['firmwareName'] = self.firmware_name
response['numTools'] = self.extruder_count
response['geometry'] = self.kinematics
response['axes'] = 3
p_state = self.printer_state
status = self._get_printer_status()
response['status'] = status
response['babystep'] = round(p_state['gcode'].get(
'homing_zpos', 0.), 3)
# Current position
pos = p_state['toolhead'].get('position', [0., 0., 0., 0.])
response['pos'] = [round(p, 2) for p in pos[:3]]
homed_pos = p_state['toolhead'].get('homed_axes', "")
response['homed'] = [int(a in homed_pos) for a in "xyz"]
sfactor = round(p_state['gcode'].get('speed_factor', 1.) * 100, 2)
response['sfactor'] = sfactor
# Print Progress Tracking
sd_status = p_state['virtual_sdcard']
fname = sd_status.get('filename', "")
if fname:
# We know a file has been loaded, initialize metadata
if self.current_file != fname:
self.current_file = fname
self.file_metadata = self.file_manager.get_file_metadata(fname)
progress = p_state['virtual_sdcard'].get('progress', 0)
# progress and print tracking
if progress:
response['fraction_printed'] = round(progress, 3)
est_time = self.file_metadata.get('estimated_time', 0)
if est_time > MIN_EST_TIME:
# file read estimate
times_left = [int(est_time - est_time * progress)]
# filament estimate
est_total_fil = self.file_metadata.get('filament_total')
if est_total_fil:
cur_filament = sd_status.get('filament_used', 0.)
fpct = min(1., cur_filament / est_total_fil)
times_left.append(int(est_time - est_time * fpct))
# object height estimate
obj_height = self.file_metadata.get('object_height')
if obj_height:
cur_height = p_state['gcode'].get('move_zpos', 0.)
hpct = min(1., cur_height / obj_height)
times_left.append(int(est_time - est_time * hpct))
else:
# The estimated time is not in the metadata, however we
# can still provide an estimate based on file progress
duration = sd_status.get('print_duration', 0.)
times_left = [int(duration / progress - duration)]
response['timesLeft'] = times_left
else:
# clear filename and metadata
self.current_file = ""
self.file_metadata = {}
fan_speed = p_state['fan'].get('speed')
if fan_speed is not None:
response['fanPercent'] = [round(fan_speed * 100, 1)]
if self.extruder_count > 0:
extruder_name = p_state['toolhead'].get('extruder')
if extruder_name is not None:
tool = 0
if extruder_name != "extruder":
tool = int(extruder_name[-1])
response['tool'] = tool
# Report Heater Status
efactor = round(p_state['gcode'].get('extrude_factor', 1.) * 100., 2)
for name in self.heaters:
temp = round(p_state[name].get('temperature', 0.0), 1)
target = round(p_state[name].get('target', 0.0), 1)
response.setdefault('heaters', []).append(temp)
response.setdefault('active', []).append(target)
response.setdefault('standby', []).append(target)
response.setdefault('hstat', []).append(2 if target else 0)
if name.startswith('extruder'):
response.setdefault('efactor', []).append(efactor)
response.setdefault('extr', []).append(round(pos[3], 2))
# Display message (via M117)
msg = p_state['display_status'].get('message')
if msg and msg != self.last_message:
response['message'] = msg
# reset the message so it only shows once. The paneldue
# is strange about this, and displays it as a full screen
# notification
self.last_message = msg
await self.write_response(response)
async def _run_paneldue_M20(self, arg_p, arg_s=0):
response_type = arg_s
if response_type != 2:
logging.info(
"PanelDue: Cannot process response type %d in M20"
% (response_type))
return
path = arg_p
# Strip quotes if they exist
path = path.strip('\"')
# Path should come in as "0:/macros, or 0:/<gcode_folder>". With
# repetier compatibility enabled, the default folder is root,
# ie. "0:/"
if path.startswith("0:/"):
path = path[2:]
response = {'dir': path}
response['files'] = []
if path == "/macros":
response['files'] = list(self.available_macros.keys())
else:
# HACK: The PanelDue has a bug where it does not correctly detect
# subdirectories if we return the root as "/". Moonraker can
# support a "gcodes" directory, however we must choose between this
# support or disabling RRF specific gcodes (this is done by
# identifying as Repetier).
# The workaround below converts both "/" and "/gcodes" paths to
# "gcodes".
if path == "/":
response['dir'] = "/gcodes"
path = "gcodes"
elif path.startswith("/gcodes"):
path = path[1:]
flist = self.file_manager.list_dir(path, simple_format=True)
if flist:
response['files'] = flist
await self.write_response(response)
async def _run_paneldue_M30(self, arg_p=None):
# Delete a file. Clean up the file name and make sure
# it is relative to the "gcodes" root.
path = arg_p
path = path.strip('\"')
if path.startswith("0:/"):
path = path[3:]
elif path[0] == "/":
path = path[1:]
if not path.startswith("gcodes/"):
path = "gcodes/" + path
self.file_manager.delete_file(path)
async def _run_paneldue_M36(self, arg_p=None):
response = {}
filename = arg_p
sd_status = self.printer_state.get('virtual_sdcard', {})
if filename is None:
# PanelDue is requesting file information on a
# currently printed file
active = False
if sd_status:
filename = sd_status['filename']
active = sd_status['is_active']
if not filename or not active:
# Either no file printing or no virtual_sdcard
response['err'] = 1
await self.write_response(response)
return
else:
response['fileName'] = filename.split("/")[-1]
# For consistency make sure that the filename begins with the
# "gcodes/" root. The M20 HACK should add this in some cases.
# Ideally we would add support to the PanelDue firmware that
# indicates Moonraker supports a "gcodes" directory.
if not filename.startswith("gcodes/"):
filename = "gcodes/" + filename
metadata = self.file_manager.get_file_metadata(filename)
if metadata:
response['err'] = 0
response['size'] = metadata['size']
# workaround for PanelDue replacing the first "T" found
response['lastModified'] = "T" + metadata['modified']
slicer = metadata.get('slicer')
if slicer is not None:
response['generatedBy'] = slicer
height = metadata.get('object_height')
if height is not None:
response['height'] = round(height, 2)
layer_height = metadata.get('layer_height')
if layer_height is not None:
response['layerHeight'] = round(layer_height, 2)
filament = metadata.get('filament_total')
if filament is not None:
response['filament'] = [round(filament, 1)]
est_time = metadata.get('estimated_time')
if est_time is not None:
response['printTime'] = int(est_time + .5)
else:
response['err'] = 1
await self.write_response(response)
async def close(self):
self.ser_conn.disconnect()
def load_plugin(server):
return PanelDue(server)
-188
View File
@@ -1,188 +0,0 @@
# Raspberry Pi Power Control
#
# Copyright (C) 2020 Jordan Ruthe <jordanruthe@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
import os
from tornado.ioloop import IOLoop
from tornado import gen
class PrinterPower:
def __init__(self, server):
self.server = server
self.server.register_endpoint(
"/printer/power/devices", "power_devices", ['GET'],
self._handle_list_devices)
self.server.register_endpoint(
"/printer/power/status", "power_status", ['GET'],
self._handle_power_request)
self.server.register_endpoint(
"/printer/power/on", "power_on", ['POST'],
self._handle_power_request)
self.server.register_endpoint(
"/printer/power/off", "power_off", ['POST'],
self._handle_power_request)
self.current_dev = None
self.devices = {}
async def _handle_list_devices(self, path, method, args):
output = {"devices": []}
for dev in self.devices:
output['devices'].append({
"name": self.devices[dev]["name"],
"id": dev
})
return output
async def _handle_power_request(self, path, method, args):
if len(args) == 0:
if path == "/printer/power/status":
args = self.devices
else:
return "no_devices"
result = {}
for dev in args:
if dev not in self.devices:
result[dev] = "device_not_found"
continue
await GPIO.verify_pin(self.devices[dev]["pin"],
self.devices[dev]["active_low"])
if path == "/printer/power/on":
GPIO.set_pin_value(self.devices[dev]["pin"], 1)
elif path == "/printer/power/off":
GPIO.set_pin_value(self.devices[dev]["pin"], 0)
elif path != "/printer/power/status":
raise self.server.error("Unsupported power request")
self.devices[dev]["status"] = GPIO.is_pin_on(
self.devices[dev]["pin"])
result[dev] = self.devices[dev]["status"]
return result
def load_config(self, config):
if "devices" not in config:
return
devices = config["devices"].split(',')
logging.info("Power plugin loading devices: " + str(devices))
parsed_devices = {}
for dev in devices:
dev = dev.strip()
pin = config.get(dev + "_pin", "")
if not pin.isdigit():
logging.info(
"Power plugin: ERR %s does not have a pin defined" % (dev))
continue
name = config.get(dev + "_name", dev)
active_low = int(config.get(
dev + "_active_low", "false").lower() == "true")
parsed_devices[dev] = {
"name": name,
"pin": int(pin),
"active_low": active_low,
"status": None
}
ioloop = IOLoop.current()
ioloop.spawn_callback(self.initialize_devices, parsed_devices)
async def initialize_devices(self, devices):
for name, device in devices.items():
try:
logging.debug(
"Attempting to configure pin GPIO%d"
% (device["pin"]))
await GPIO.setup_pin(device["pin"], device["active_low"])
device["status"] = GPIO.is_pin_on(device["pin"])
except Exception:
logging.exception(
"Power plugin: ERR Problem configuring the output pin for"
" device %s. Removing device" % (name))
self.devices.pop(name, None)
continue
self.devices[name] = device
class GPIO:
gpio_root = "/sys/class/gpio"
@staticmethod
def _set_gpio_option(gpio, option, value):
GPIO._write(
os.path.join(GPIO.gpio_root, "gpio%d" % (gpio), option),
value
)
@staticmethod
def _get_gpio_option(pin, option):
return GPIO._read(
os.path.join(GPIO.gpio_root, "gpio%d" % (pin), option)
)
@staticmethod
def _write(file, data):
with open(file, 'w') as f:
f.write(str(data))
f.flush()
@staticmethod
def _read(file):
with open(file, 'r') as f:
f.seek(0)
return f.read().strip()
@staticmethod
async def verify_pin(pin, active_low=1):
gpiopath = os.path.join(GPIO.gpio_root, "gpio%d" % (pin))
if not os.path.exists(gpiopath):
logging.info("Re-intializing GPIO%d" % (pin))
await GPIO.setup_pin(pin, active_low)
return
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
GPIO._set_gpio_option(pin, "active_low", active_low)
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
GPIO._set_gpio_option(pin, "direction", "out")
@staticmethod
async def setup_pin(pin, active_low=1):
pin = int(pin)
active_low = 1 if active_low == 1 else 0
gpiopath = os.path.join(GPIO.gpio_root, "gpio%d" % (pin))
if not os.path.exists(gpiopath):
GPIO._write(
os.path.join(GPIO.gpio_root, "export"),
pin)
logging.info("Waiting for GPIO%d to initialize" % (pin))
while os.stat(os.path.join(
GPIO.gpio_root, "gpio%d" % (pin),
"active_low")).st_gid == 0:
await gen.sleep(.1)
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
GPIO._set_gpio_option(pin, "active_low", active_low)
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
GPIO._set_gpio_option(pin, "direction", "out")
@staticmethod
def is_pin_on(pin):
return "on" if int(GPIO._get_gpio_option(pin, "value")) else "off"
@staticmethod
def set_pin_value(pin, active):
value = 1 if (active == 1) else 0
GPIO._set_gpio_option(pin, "value", value)
def load_plugin(server):
return PrinterPower(server)
-88
View File
@@ -1,88 +0,0 @@
# linux shell command execution utility
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import os
import shlex
import subprocess
import logging
import tornado
from tornado import gen
from tornado.ioloop import IOLoop
class ShellCommand:
def __init__(self, cmd, callback=None):
self.io_loop = IOLoop.current()
self.name = cmd
self.output_cb = callback
cmd = os.path.expanduser(cmd)
self.command = shlex.split(cmd)
self.partial_output = b""
def _process_output(self, fd, events):
if events & IOLoop.ERROR:
return
try:
data = os.read(fd, 4096)
except Exception:
return
data = self.partial_output + data
if b'\n' not in data:
self.partial_output = data
return
elif data[-1] != b'\n':
split = data.rfind(b'\n') + 1
self.partial_output = data[split:]
data = data[:split]
try:
self.output_cb(data)
except Exception:
logging.exception("Error writing command output")
async def run(self, timeout=2., verbose=True):
if not timeout or self.output_cb is None:
# Fire and forget commands cannot be verbose as we can't
# clean up after the process terminates
verbose = False
try:
proc = subprocess.Popen(
self.command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
except Exception:
logging.exception(
"shell_command: Command {%s} failed" % (self.name))
return
if verbose:
fd = proc.stdout.fileno()
self.io_loop.add_handler(
fd, self._process_output, IOLoop.READ | IOLoop.ERROR)
elif not timeout:
# fire and forget, return from execution
return
sleeptime = 0
complete = False
while sleeptime < timeout:
await gen.sleep(.05)
sleeptime += .05
if proc.poll() is not None:
complete = True
break
if not complete:
proc.terminate()
if verbose:
if self.partial_output:
self.output_cb(self.partial_output)
self.partial_output = b""
if complete:
msg = "Command {%s} finished" % (self.name)
else:
msg = "Command {%s} timed out" % (self.name)
logging.info(msg)
self.io_loop.remove_handler(fd)
class ShellCommandFactory:
def build_shell_command(self, cmd, callback):
return ShellCommand(cmd, callback)
def load_plugin(server):
return ShellCommandFactory()
-102
View File
@@ -1,102 +0,0 @@
# Heater sensor temperature storage
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
from collections import deque
from tornado.ioloop import IOLoop, PeriodicCallback
TEMPERATURE_UPDATE_MS = 1000
TEMPERATURE_STORE_SIZE = 20 * 60
class TemperatureStore:
def __init__(self, server):
self.server = server
# Temperature Store Tracking
self.last_temps = {}
self.temperature_store = {}
self.temp_update_cb = PeriodicCallback(
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
# Register status update event
self.server.register_event_handler(
"server:status_update", self._set_current_temps)
self.server.register_event_handler(
"server:klippy_state_changed", self._init_sensors)
# Register endpoint
self.server.register_endpoint(
"/server/temperature_store", "server_temperature_store", ['GET'],
self._handle_temp_store_request)
async def _init_sensors(self, state):
if state != "ready":
return
# Fetch sensors
request = self.server.make_request(
"objects/status", 'GET', {'heaters': []})
result = await request.wait()
if isinstance(result, self.server.error):
logging.info("Error Configuring Sensors: %s" % (str(result)))
return
sensors = result.get("heaters", {}).get("available_sensors", [])
if sensors:
# Add Subscription
sub = {s: [] for s in sensors}
request = self.server.make_request(
"objects/subscription", 'POST', sub)
result = await request.wait()
if isinstance(result, self.server.error):
logging.info("Error subscribing to sensors: %s" %(str(result)))
return
logging.info("Configuring available sensors: %s" % (str(sensors)))
new_store = {}
for sensor in sensors:
if sensor in self.temperature_store:
new_store[sensor] = self.temperature_store[sensor]
else:
new_store[sensor] = {
'temperatures': deque(maxlen=TEMPERATURE_STORE_SIZE),
'targets': deque(maxlen=TEMPERATURE_STORE_SIZE)}
self.temperature_store = new_store
# Prune unconfigured sensors in self.last_temps
for sensor in list(self.last_temps.keys()):
if sensor not in self.temperature_store:
del self.last_temps[sensor]
self.temp_update_cb.start()
else:
logging.info("No sensors found")
self.last_temps = {}
self.temperature_store = {}
self.temp_update_cb.stop()
def _set_current_temps(self, data):
for sensor in self.temperature_store:
if sensor in data:
self.last_temps[sensor] = (
round(data[sensor].get('temperature', 0.), 2),
data[sensor].get('target', 0.))
def _update_temperature_store(self):
# XXX - If klippy is not connected, set values to zero
# as they are unknown?
for sensor, (temp, target) in self.last_temps.items():
self.temperature_store[sensor]['temperatures'].append(temp)
self.temperature_store[sensor]['targets'].append(target)
async def _handle_temp_store_request(self, path, method, args):
store = {}
for name, sensor in self.temperature_store.items():
store[name] = {k: list(v) for k, v in sensor.items()}
return store
async def close(self):
self.temp_update_cb.stop()
def load_plugin(server):
return TemperatureStore(server)
+151 -45
View File
@@ -3,68 +3,174 @@
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import logging
import logging.handlers
import os
import pathlib
import sys
import subprocess
import asyncio
import hashlib
import json
from queue import SimpleQueue as Queue
# Annotation imports
from typing import (
List,
Optional,
ClassVar,
Tuple,
Dict,
Any,
)
MOONRAKER_PATH = os.path.join(os.path.dirname(__file__), '..')
class ServerError(Exception):
def __init__(self, message, status_code=400):
def __init__(self, message: str, status_code: int = 400) -> None:
Exception.__init__(self, message)
self.status_code = status_code
# XXX - Currently logging over the socket is not implemented.
# I don't think it would be wise to log everything over the
# socket, however it may be useful to log some specific items.
# Decide what to do, then either finish the implementation or
# remove this code
class SocketLoggingHandler(logging.Handler):
def __init__(self, server_manager):
super(SocketLoggingHandler, self).__init__()
self.server_manager = server_manager
def emit(self, record):
record.msg = "[MOONRAKER]: " + record.msg
# XXX - Convert log record to dict before sending,
# the klippy_send function will handle serialization
class SentinelClass:
_instance: ClassVar[Optional[SentinelClass]] = None
self.server_manager.klippy_send(record)
@staticmethod
def get_instance() -> SentinelClass:
if SentinelClass._instance is None:
SentinelClass._instance = SentinelClass()
return SentinelClass._instance
# Coroutine friendly QueueHandler courtesy of Martjin Pieters:
# https://www.zopatista.com/python/2019/05/11/asyncio-logging/
class LocalQueueHandler(logging.handlers.QueueHandler):
def emit(self, record: logging.LogRecord) -> None:
# Removed the call to self.prepare(), handle task cancellation
try:
self.enqueue(record)
except asyncio.CancelledError:
raise
except Exception:
self.handleError(record)
# Timed Rotating File Handler, based on Klipper's implementation
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, filename, **kwargs):
super(MoonrakerLoggingHandler, self).__init__(filename, **kwargs)
self.header = "Moonraker Log Start...\n"
self.header += "Git Version: " + get_software_version() + "\n"
self.header += "="*80 + "\n"
def __init__(self, app_args: Dict[str, Any], **kwargs) -> None:
super().__init__(app_args['log_file'], **kwargs)
self.rollover_info: Dict[str, str] = {
'header': f"{'-'*20}Moonraker Log Start{'-'*20}"
}
self.rollover_info['application_args'] = "\n".join(
[f"{k}: {v}" for k, v in app_args.items()])
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write(self.header)
self.stream.write("\n".join(lines) + "\n")
def doRollover(self):
super(MoonrakerLoggingHandler, self).doRollover()
def set_rollover_info(self, name: str, item: str) -> None:
self.rollover_info[name] = item
def doRollover(self) -> None:
super().doRollover()
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write(self.header)
self.stream.write("\n".join(lines) + "\n")
# Parse the git version from the command line. This code
# is borrowed from Klipper.
def get_software_version():
moonraker_path = os.path.join(
os.path.dirname(__file__), '..')
def retreive_git_version(source_path: str) -> str:
# Obtain version info from "git" program
prog = ('git', '-C', moonraker_path, 'describe', '--always',
'--tags', '--long', '--dirty', "--all")
try:
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
ver, err = process.communicate()
retcode = process.wait()
if retcode == 0:
version = ver.strip()
if isinstance(version, bytes):
version = version.decode()
return version
else:
logging.debug("Error getting git version: %s", err)
except OSError:
logging.exception("Error runing git describe")
prog = ('git', '-C', source_path, 'describe', '--always',
'--tags', '--long', '--dirty')
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
ver, err = process.communicate()
retcode = process.wait()
if retcode == 0:
return ver.strip().decode()
raise Exception(f"Failed to retreive git version: {err.decode()}")
return "?"
def get_software_version() -> str:
version = "?"
try:
version = retreive_git_version(MOONRAKER_PATH)
except Exception:
vfile = pathlib.Path(os.path.join(
MOONRAKER_PATH, "moonraker/.version"))
if vfile.exists():
try:
version = vfile.read_text().strip()
except Exception:
logging.exception("Unable to extract version from file")
version = "?"
return version
def setup_logging(app_args: Dict[str, Any]
) -> Tuple[logging.handlers.QueueListener,
Optional[MoonrakerLoggingHandler]]:
root_logger = logging.getLogger()
queue: Queue = Queue()
queue_handler = LocalQueueHandler(queue)
root_logger.addHandler(queue_handler)
root_logger.setLevel(logging.INFO)
stdout_hdlr = logging.StreamHandler(sys.stdout)
stdout_fmt = logging.Formatter(
'[%(filename)s:%(funcName)s()] - %(message)s')
stdout_hdlr.setFormatter(stdout_fmt)
for name, val in app_args.items():
logging.info(f"{name}: {val}")
file_hdlr = None
if app_args.get('log_file', ""):
file_hdlr = MoonrakerLoggingHandler(
app_args, when='midnight', backupCount=2)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
file_hdlr.setFormatter(formatter)
listener = logging.handlers.QueueListener(
queue, file_hdlr, stdout_hdlr)
else:
listener = logging.handlers.QueueListener(
queue, stdout_hdlr)
listener.start()
return listener, file_hdlr
def hash_directory(dir_path: str,
ignore_exts: List[str],
ignore_dirs: List[str]
) -> str:
checksum = hashlib.blake2s()
if not os.path.exists(dir_path):
return ""
for dpath, dnames, fnames in os.walk(dir_path):
valid_dirs: List[str] = []
for dname in sorted(dnames):
if dname[0] == '.' or dname in ignore_dirs:
continue
valid_dirs.append(dname)
dnames[:] = valid_dirs
for fname in sorted(fnames):
ext = os.path.splitext(fname)[-1].lower()
if fname[0] == '.' or ext in ignore_exts:
continue
fpath = pathlib.Path(os.path.join(dpath, fname))
try:
checksum.update(fpath.read_bytes())
except Exception:
pass
return checksum.hexdigest()
def verify_source(path: str = MOONRAKER_PATH) -> Optional[Tuple[str, bool]]:
rfile = pathlib.Path(os.path.join(path, ".release_info"))
if not rfile.exists():
return None
try:
rinfo = json.loads(rfile.read_text())
except Exception:
return None
orig_chksum = rinfo['source_checksum']
ign_dirs = rinfo['ignored_dirs']
ign_exts = rinfo['ignored_exts']
checksum = hash_directory(path, ign_exts, ign_dirs)
return checksum, checksum == orig_chksum
+358 -129
View File
@@ -4,51 +4,195 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import logging
import tornado
import ipaddress
import json
import tornado.util
from tornado.ioloop import IOLoop
from tornado.websocket import WebSocketHandler, WebSocketClosedError
from utils import ServerError
from tornado.locks import Event
from utils import ServerError, SentinelClass
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Callable,
Coroutine,
Type,
TypeVar,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from moonraker import Server
from app import APIDefinition, MoonrakerApp
import components.authorization
_T = TypeVar("_T")
_C = TypeVar("_C", str, bool, float, int)
IPUnion = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
ConvType = Union[str, bool, float, int]
ArgVal = Union[None, int, float, bool, str]
RPCCallback = Callable[..., Coroutine]
AuthComp = Optional[components.authorization.Authorization]
SENTINEL = SentinelClass.get_instance()
class Subscribable:
def send_status(self,
status: Dict[str, Any],
eventtime: float
) -> None:
raise NotImplementedError
class WebRequest:
def __init__(self,
endpoint: str,
args: Dict[str, Any],
action: Optional[str] = "",
conn: Optional[Subscribable] = None,
ip_addr: str = "",
user: Optional[Dict[str, Any]] = None
) -> None:
self.endpoint = endpoint
self.action = action or ""
self.args = args
self.conn = conn
self.ip_addr: Optional[IPUnion] = None
try:
self.ip_addr = ipaddress.ip_address(ip_addr)
except Exception:
self.ip_addr = None
self.current_user = user
def get_endpoint(self) -> str:
return self.endpoint
def get_action(self) -> str:
return self.action
def get_args(self) -> Dict[str, Any]:
return self.args
def get_connection(self) -> Optional[Subscribable]:
return self.conn
def get_ip_address(self) -> Optional[IPUnion]:
return self.ip_addr
def get_current_user(self) -> Optional[Dict[str, Any]]:
return self.current_user
def _get_converted_arg(self,
key: str,
default: Union[SentinelClass, _T],
dtype: Type[_C]
) -> Union[_C, _T]:
if key not in self.args:
if isinstance(default, SentinelClass):
raise ServerError(f"No data for argument: {key}")
return default
val = self.args[key]
try:
if dtype is not bool:
return dtype(val)
else:
if isinstance(val, str):
val = val.lower()
if val in ["true", "false"]:
return True if val == "true" else False # type: ignore
elif isinstance(val, bool):
return val # type: ignore
raise TypeError
except Exception:
raise ServerError(
f"Unable to convert argument [{key}] to {dtype}: "
f"value recieved: {val}")
def get(self,
key: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[_T, Any]:
val = self.args.get(key, default)
if isinstance(val, SentinelClass):
raise ServerError(f"No data for argument: {key}")
return val
def get_str(self,
key: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[str, _T]:
return self._get_converted_arg(key, default, str)
def get_int(self,
key: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[int, _T]:
return self._get_converted_arg(key, default, int)
def get_float(self,
key: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[float, _T]:
return self._get_converted_arg(key, default, float)
def get_boolean(self,
key: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[bool, _T]:
return self._get_converted_arg(key, default, bool)
class JsonRPC:
def __init__(self):
self.methods = {}
def __init__(self, transport: str = "Websocket") -> None:
self.methods: Dict[str, RPCCallback] = {}
self.transport = transport
def register_method(self, name, method):
def register_method(self,
name: str,
method: RPCCallback
) -> None:
self.methods[name] = method
def remove_method(self, name):
def remove_method(self, name: str) -> None:
self.methods.pop(name, None)
async def dispatch(self, data):
response = None
async def dispatch(self,
data: str,
conn: Optional[WebSocket] = None
) -> Optional[str]:
response: Any = None
try:
request = json.loads(data)
request: Union[Dict[str, Any], List[dict]] = json.loads(data)
except Exception:
msg = "Websocket data not json: %s" % (str(data))
msg = f"{self.transport} data not json: {data}"
logging.exception(msg)
response = self.build_error(-32700, "Parse error")
return json.dumps(response)
logging.debug("Websocket Request::" + data)
logging.debug(f"{self.transport} Request::{data}")
if isinstance(request, list):
response = []
for req in request:
resp = await self.process_request(req)
resp = await self.process_request(req, conn)
if resp is not None:
response.append(resp)
if not response:
response = None
else:
response = await self.process_request(request)
response = await self.process_request(request, conn)
if response is not None:
response = json.dumps(response)
logging.debug("Websocket Response::" + response)
logging.debug(f"{self.transport} Response::{response}")
return response
async def process_request(self, request):
req_id = request.get('id', None)
rpc_version = request.get('jsonrpc', "")
async def process_request(self,
request: Dict[str, Any],
conn: Optional[WebSocket]
) -> Optional[Dict[str, Any]]:
req_id: Optional[int] = request.get('id', None)
rpc_version: str = request.get('jsonrpc', "")
method_name = request.get('method', None)
if rpc_version != "2.0" or not isinstance(method_name, str):
return self.build_error(-32600, "Invalid Request", req_id)
@@ -58,176 +202,261 @@ class JsonRPC:
if 'params' in request:
params = request['params']
if isinstance(params, list):
response = await self.execute_method(method, req_id, *params)
response = await self.execute_method(
method, req_id, conn, *params)
elif isinstance(params, dict):
response = await self.execute_method(method, req_id, **params)
response = await self.execute_method(
method, req_id, conn, **params)
else:
return self.build_error(-32600, "Invalid Request", req_id)
else:
response = await self.execute_method(method, req_id)
response = await self.execute_method(method, req_id, conn)
return response
async def execute_method(self, method, req_id, *args, **kwargs):
async def execute_method(self,
method: RPCCallback,
req_id: Optional[int],
conn: Optional[WebSocket],
*args,
**kwargs
) -> Optional[Dict[str, Any]]:
try:
result = await method(*args, **kwargs)
if conn is not None:
result = await method(conn, *args, **kwargs)
else:
result = await method(*args, **kwargs)
except TypeError as e:
return self.build_error(-32603, "Invalid params", req_id)
return self.build_error(
-32603, f"Invalid params:\n{e}", req_id, True)
except ServerError as e:
return self.build_error(e.status_code, str(e), req_id, True)
except Exception as e:
return self.build_error(-31000, str(e), req_id)
if isinstance(result, ServerError):
return self.build_error(result.status_code, str(result), req_id)
elif req_id is None:
return self.build_error(-31000, str(e), req_id, True)
if req_id is None:
return None
else:
return self.build_result(result, req_id)
def build_result(self, result, req_id):
def build_result(self, result: Any, req_id: int) -> Dict[str, Any]:
return {
'jsonrpc': "2.0",
'result': result,
'id': req_id
}
def build_error(self, code, msg, req_id=None):
def build_error(self,
code: int,
msg: str,
req_id: Optional[int] = None,
is_exc: bool = False
) -> Dict[str, Any]:
log_msg = f"JSON-RPC Request Error: {code}\n{msg}"
if is_exc:
logging.exception(log_msg)
else:
logging.info(log_msg)
return {
'jsonrpc': "2.0",
'error': {'code': code, 'message': msg},
'id': req_id
}
class WebsocketManager:
def __init__(self, server):
class APITransport:
def register_api_handler(self, api_def: APIDefinition) -> None:
raise NotImplementedError
def remove_api_handler(self, api_def: APIDefinition) -> None:
raise NotImplementedError
class WebsocketManager(APITransport):
def __init__(self, server: Server) -> None:
self.server = server
self.websockets = {}
self.ws_lock = tornado.locks.Lock()
self.websockets: Dict[int, WebSocket] = {}
self.rpc = JsonRPC()
self.closed_event: Optional[Event] = None
# Register events
self.rpc.register_method("server.websocket.id", self._handle_id_request)
def register_notification(self,
event_name: str,
notify_name: Optional[str] = None
) -> None:
if notify_name is None:
notify_name = event_name.split(':')[-1]
def notify_handler(*args):
self.notify_websockets(notify_name, *args)
self.server.register_event_handler(
"server:klippy_state_changed", self._handle_klippy_state_changed)
self.server.register_event_handler(
"server:gcode_response", self._handle_gcode_response)
self.server.register_event_handler(
"server:status_update", self._handle_status_update)
self.server.register_event_handler(
"file_manager:filelist_changed", self._handle_filelist_changed)
event_name, notify_handler)
async def _handle_klippy_state_changed(self, state):
await self.notify_websockets("klippy_state_changed", state)
async def _handle_gcode_response(self, response):
await self.notify_websockets("gcode_response", response)
async def _handle_status_update(self, status):
await self.notify_websockets("status_update", status)
async def _handle_filelist_changed(self, flist):
await self.notify_websockets("filelist_changed", flist)
def register_handler(self, api_def, callback=None):
for r_method in api_def.request_methods:
cmd = r_method.lower() + '_' + api_def.ws_method
if callback is not None:
# Callback is a local method
def register_api_handler(self, api_def: APIDefinition) -> None:
if api_def.callback is None:
# Remote API, uses RPC to reach out to Klippy
ws_method = api_def.jrpc_methods[0]
rpc_cb = self._generate_callback(api_def.endpoint)
self.rpc.register_method(ws_method, rpc_cb)
else:
# Local API, uses local callback
for ws_method, req_method in \
zip(api_def.jrpc_methods, api_def.request_methods):
rpc_cb = self._generate_local_callback(
api_def.endpoint, r_method, callback)
else:
# Callback is a remote method
rpc_cb = self._generate_callback(api_def.endpoint, r_method)
self.rpc.register_method(cmd, rpc_cb)
api_def.endpoint, req_method, api_def.callback)
self.rpc.register_method(ws_method, rpc_cb)
logging.info(
"Registering Websocket JSON-RPC methods: "
f"{', '.join(api_def.jrpc_methods)}")
def remove_handler(self, ws_method):
for prefix in ["get", "post", "delete"]:
self.rpc.remove_method(prefix + "_" + ws_method)
def remove_api_handler(self, api_def: APIDefinition) -> None:
for jrpc_method in api_def.jrpc_methods:
self.rpc.remove_method(jrpc_method)
def _generate_callback(self, endpoint, request_method):
async def func(**kwargs):
request = self.server.make_request(
endpoint, request_method, kwargs)
result = await request.wait()
def _generate_callback(self, endpoint: str) -> RPCCallback:
async def func(ws: WebSocket, **kwargs) -> Any:
result = await self.server.make_request(
WebRequest(endpoint, kwargs, conn=ws, ip_addr=ws.ip_addr,
user=ws.current_user))
return result
return func
def _generate_local_callback(self, endpoint, request_method, callback):
async def func(**kwargs):
try:
result = await callback(
endpoint, request_method, kwargs)
except ServerError as e:
result = e
def _generate_local_callback(self,
endpoint: str,
request_method: str,
callback: Callable[[WebRequest], Coroutine]
) -> RPCCallback:
async def func(ws: WebSocket, **kwargs) -> Any:
result = await callback(
WebRequest(endpoint, kwargs, request_method, ws,
ip_addr=ws.ip_addr, user=ws.current_user))
return result
return func
def has_websocket(self, ws_id):
async def _handle_id_request(self,
ws: WebSocket,
**kwargs
) -> Dict[str, int]:
return {'websocket_id': ws.uid}
def has_websocket(self, ws_id: int) -> bool:
return ws_id in self.websockets
async def add_websocket(self, ws):
async with self.ws_lock:
self.websockets[ws.uid] = ws
logging.info("New Websocket Added: %d" % ws.uid)
def get_websocket(self, ws_id: int) -> Optional[WebSocket]:
return self.websockets.get(ws_id, None)
async def remove_websocket(self, ws):
async with self.ws_lock:
old_ws = self.websockets.pop(ws.uid, None)
if old_ws is not None:
logging.info("Websocket Removed: %d" % ws.uid)
def add_websocket(self, ws: WebSocket) -> None:
self.websockets[ws.uid] = ws
logging.info(f"New Websocket Added: {ws.uid}")
async def notify_websockets(self, name, data):
notification = json.dumps({
'jsonrpc': "2.0",
'method': "notify_" + name,
'params': [data]})
async with self.ws_lock:
for ws in list(self.websockets.values()):
try:
ws.write_message(notification)
except WebSocketClosedError:
self.websockets.pop(ws.uid, None)
logging.info("Websocket Removed: %d" % ws.uid)
except Exception:
logging.exception(
"Error sending data over websocket: %d" % (ws.uid))
def remove_websocket(self, ws: WebSocket) -> None:
old_ws = self.websockets.pop(ws.uid, None)
if old_ws is not None:
self.server.remove_subscription(old_ws)
logging.info(f"Websocket Removed: {ws.uid}")
if self.closed_event is not None and not self.websockets:
self.closed_event.set()
async def close(self):
async with self.ws_lock:
for ws in self.websockets.values():
ws.close()
self.websockets = {}
def notify_websockets(self,
name: str,
data: Any = SENTINEL
) -> None:
msg: Dict[str, Any] = {'jsonrpc': "2.0", 'method': "notify_" + name}
if data != SENTINEL:
msg['params'] = [data]
for ws in list(self.websockets.values()):
ws.queue_message(msg)
class WebSocket(WebSocketHandler):
def initialize(self, wsm, auth):
self.wsm = wsm
self.auth = auth
async def close(self) -> None:
if not self.websockets:
return
self.closed_event = Event()
for ws in list(self.websockets.values()):
ws.close()
try:
await self.closed_event.wait(IOLoop.current().time() + 2.)
except tornado.util.TimeoutError:
pass
self.closed_event = None
class WebSocket(WebSocketHandler, Subscribable):
def initialize(self) -> None:
app: MoonrakerApp = self.settings['parent']
self.server = app.get_server()
self.wsm = app.get_websocket_manager()
self.rpc = self.wsm.rpc
self.uid = id(self)
self.is_closed: bool = False
self.ip_addr: str = self.request.remote_ip
self.queue_busy: bool = False
self.message_buf: List[Union[str, Dict[str, Any]]] = []
async def open(self):
await self.wsm.add_websocket(self)
def open(self, *args, **kwargs) -> None:
self.set_nodelay(True)
self.wsm.add_websocket(self)
def on_message(self, message):
def on_message(self, message: Union[bytes, str]) -> None:
io_loop = IOLoop.current()
io_loop.spawn_callback(self._process_message, message)
async def _process_message(self, message):
async def _process_message(self, message: str) -> None:
try:
response = await self.rpc.dispatch(message)
response = await self.rpc.dispatch(message, self)
if response is not None:
self.write_message(response)
self.queue_message(response)
except Exception:
logging.exception("Websocket Command Error")
def on_close(self):
io_loop = IOLoop.current()
io_loop.spawn_callback(self.wsm.remove_websocket, self)
def queue_message(self, message: Union[str, Dict[str, Any]]):
self.message_buf.append(message)
if self.queue_busy:
return
self.queue_busy = True
IOLoop.current().spawn_callback(self._process_messages)
def check_origin(self, origin):
if self.settings['enable_cors']:
# allow CORS
return True
else:
return super(WebSocket, self).check_origin(origin)
async def _process_messages(self):
if self.is_closed:
self.message_buf = []
self.queue_busy = False
return
while self.message_buf:
msg = self.message_buf.pop(0)
try:
await self.write_message(msg)
except WebSocketClosedError:
self.is_closed = True
logging.info(
f"Websocket closed while writing: {self.uid}")
break
except Exception:
logging.exception(
f"Error sending data over websocket: {self.uid}")
self.queue_busy = False
def send_status(self,
status: Dict[str, Any],
eventtime: float
) -> None:
if not status:
return
self.queue_message({
'jsonrpc': "2.0",
'method': "notify_status_update",
'params': [status, eventtime]})
def on_close(self) -> None:
self.is_closed = True
self.message_buf = []
self.wsm.remove_websocket(self)
def check_origin(self, origin: str) -> bool:
if not super(WebSocket, self).check_origin(origin):
auth: AuthComp = self.server.lookup_component('authorization', None)
if auth is not None:
return auth.check_cors(origin)
return False
return True
# Check Authorized User
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
auth: AuthComp = self.server.lookup_component('authorization', None)
if auth is not None:
self.current_user = auth.check_authorized(self.request)
+64
View File
@@ -0,0 +1,64 @@
#!/bin/bash
# This script builds a zipped source release for Moonraker and Klipper.
install_packages()
{
PKGLIST="python3-dev curl"
# Update system package info
report_status "Running apt-get update..."
sudo apt-get update
# Install desired packages
report_status "Installing packages..."
sudo apt-get install --yes $PKGLIST
}
report_status()
{
echo -e "\n\n###### $1"
}
verify_ready()
{
if [ "$EUID" -eq 0 ]; then
echo "This script must not run as root"
exit -1
fi
if [ ! -d "$SRCDIR/.git" ]; then
echo "This script must be run from a git repo"
exit -1
fi
if [ ! -d "$KLIPPER_DIR/.git" ]; then
echo "This script must be run from a git repo"
exit -1
fi
}
# Force script to exit if an error occurs
set -e
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
OUTPUT_DIR="$SRCDIR/.dist"
KLIPPER_DIR="$HOME/klipper"
BETA=""
# Parse command line arguments
while getopts "o:k:b" arg; do
case $arg in
o) OUTPUT_DIR=$OPTARG;;
k) KLIPPER_DIR=$OPTARG;;
b) BETA="-b";;
esac
done
[ ! -d $OUTPUT_DIR ] && mkdir $OUTPUT_DIR
verify_ready
if [ "$BETA" = "" ]; then
releaseTag=$( git -C $KLIPPER_DIR describe --tags `git -C $KLIPPER_DIR rev-list --tags --max-count=1` )
echo "Checking out Klipper release $releaseTag"
git -C $KLIPPER_DIR checkout $releaseTag
fi
python3 "$SRCDIR/scripts/build_release.py" -k $KLIPPER_DIR -o $OUTPUT_DIR $BETA
+338
View File
@@ -0,0 +1,338 @@
#!/usr/bin/python3
# Builds zip release files for Moonraker and Klipper
import os
import sys
import argparse
import shutil
import tempfile
import json
import pathlib
import time
import traceback
import subprocess
import re
from typing import Dict, Any, List, Set, Optional
MOONRAKER_PATH = os.path.abspath(
os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(os.path.join(MOONRAKER_PATH, "moonraker"))
from utils import hash_directory, retreive_git_version # noqa:E402
# Dirs and exts to ignore when calculating the repo hash
IGNORE_DIRS = ["out", "lib", "test", "docs", "__pycache__"]
IGNORE_EXTS = [".o", ".so", ".pyc", ".pyo", ".pyd", ".yml", ".yaml"]
# Files not to include in the source package
SKIP_FILES = [".gitignore", ".gitattributes", ".readthedocs.yaml",
"mkdocs.yml", "__pycache__"]
RELEASE_URL = "https://api.github.com/repos/Arksine/moonraker/releases"
GIT_MAX_LOG_CNT = 100
GIT_LOG_FMT = \
"sha:%H%x1Dauthor:%an%x1Ddate:%ct%x1Dsubject:%s%x1Dmessage:%b%x1E"
OWNER_REPOS = {
'moonraker': "arksine/moonraker",
'klippy': "kevinoconnor/klipper"
}
INSTALL_SCRIPTS = {
'klippy': {
'debian': "install-octopi.sh",
'arch': "install-arch.sh",
'centos': "install-centos.sh"
},
'moonraker': {
'debian': "install-moonraker.sh"
}
}
class CopyIgnore:
def __init__(self, root_dir: str) -> None:
self.root_dir = root_dir
def __call__(self, dir_path: str, dir_items: List[str]) -> List[str]:
ignored: List[str] = []
for item in dir_items:
if item in SKIP_FILES:
ignored.append(item)
elif dir_path == self.root_dir:
full_path = os.path.join(dir_path, item)
# Ignore all hidden directories in the root
if os.path.isdir(full_path) and item[0] == ".":
ignored.append(item)
return ignored
def search_install_script(data: str,
regex: str,
exclude: str
) -> List[str]:
items: Set[str] = set()
lines: List[str] = re.findall(regex, data)
for line in lines:
items.update(line.strip().split())
try:
items.remove(exclude)
except KeyError:
pass
return list(items)
def generate_dependency_info(repo_path: str, app_name: str) -> None:
inst_scripts = INSTALL_SCRIPTS[app_name]
package_info: Dict[str, Any] = {}
for distro, script_name in inst_scripts.items():
script_path = os.path.join(repo_path, "scripts", script_name)
script = pathlib.Path(script_path)
if not script.exists():
continue
data = script.read_text()
packages: List[str] = search_install_script(
data, r'PKGLIST="(.*)"', "${PKGLIST}")
package_info[distro] = {'packages': sorted(packages)}
if distro == "arch":
aur_packages: List[str] = search_install_script(
data, r'AURLIST="(.*)"', "${AURLIST}")
package_info[distro]['aur_packages'] = sorted(aur_packages)
req_file_name = os.path.join(repo_path, "scripts",
f"{app_name}-requirements.txt")
req_file = pathlib.Path(req_file_name)
python_reqs: List[str] = []
if req_file.exists():
req_data = req_file.read_text()
lines = [line.strip() for line in req_data.split('\n')
if line.strip()]
for line in lines:
comment_idx = line.find('#')
if comment_idx == 0:
continue
if comment_idx > 0:
line = line[:comment_idx].strip()
python_reqs.append(line)
package_info['python'] = sorted(python_reqs)
dep_file = pathlib.Path(os.path.join(repo_path, ".dependencies"))
dep_file.write_text(json.dumps(package_info))
def clean_repo(path: str) -> None:
# Obtain version info from "git" program
prog = ('git', '-C', path, 'clean', '-x', '-f', '-d')
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=path)
retcode = process.wait()
if retcode != 0:
print(f"Error running git clean: {path}")
def get_releases() -> List[Dict[str, Any]]:
print("Fetching Release List...")
prog = ('curl', '-H', "Accept: application/vnd.github.v3+json",
RELEASE_URL)
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
response, err = process.communicate()
retcode = process.wait()
if retcode != 0:
print(f"Release list request returned with code {retcode},"
f" response:\n{err.decode()}")
return []
releases = json.loads(response.decode().strip())
print(f"Found {len(releases)} releases")
return releases
def get_last_release_info(moonraker_version: str,
is_beta: bool,
releases: List[Dict[str, Any]]
) -> Dict[str, Any]:
print("Searching for previous release assets...")
cur_tag, commit_count = moonraker_version.split('-', 2)[:2]
release_assets = []
matched_tag: Optional[str] = None
for release in releases:
if int(commit_count) != 0:
# This is build is not being done against a fresh release,
# return release info from a matching tag
if release['tag_name'] == cur_tag:
release_assets = release['assets']
matched_tag = cur_tag
break
else:
# Get the most recent non-matching tag
if release['tag_name'] == cur_tag:
continue
if is_beta or not release['prerelease']:
# Get the last tagged release. If we are building a beta,
# that is the most recent release. Otherwise we should
# omit pre-releases
release_assets = release['assets']
matched_tag = release['tag_name']
break
if matched_tag is None:
print("No matching release found")
matched_tag = "No Tag"
else:
print(f"Found release: {matched_tag}")
asset_url: Optional[str] = None
content_type: str = ""
for asset in release_assets:
if asset['name'] == "RELEASE_INFO":
asset_url = asset['browser_download_url']
content_type = asset['content_type']
break
if asset_url is None:
print(f"RELEASE_INFO asset not found in release: {matched_tag}")
return {}
# This build is prior to a tagged release, so fetch the current tag
print(f"Release Info Download URL: {asset_url}")
prog = ('curl', '-L', '-H', f"Accept: {content_type}", asset_url)
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
response, err = process.communicate()
retcode = process.wait()
if retcode != 0:
print("Request for release info failed")
return {}
resp = response.decode().strip()
print(f"Found Info for release {matched_tag}")
return json.loads(resp)
def get_commit_log(path: str,
release_info: Dict[str, Any]
) -> List[Dict[str, Any]]:
print(f"Preparing commit log for {path.split('/')[-1]}")
start_sha = release_info.get('commit_hash', None)
prog = ['git', '-C', path, 'log', f'--format={GIT_LOG_FMT}',
f'--max-count={GIT_MAX_LOG_CNT}']
if start_sha is not None:
prog = ['git', '-C', path, 'log', f'{start_sha}..HEAD',
f'--format={GIT_LOG_FMT}', f'--max-count={GIT_MAX_LOG_CNT}']
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=path)
response, err = process.communicate()
retcode = process.wait()
if retcode != 0:
return []
resp = response.decode().strip()
commit_log: List[Dict[str, Any]] = []
for log_entry in resp.split('\x1E'):
log_entry = log_entry.strip()
if not log_entry:
continue
log_items = [li.strip() for li in log_entry.split('\x1D')
if li.strip()]
cbh = [li.split(':', 1) for li in log_items]
commit_log.append(dict(cbh)) # type: ignore
print(f"Found {len(commit_log)} commits")
return commit_log
def get_commit_hash(path: str) -> str:
prog = ('git', '-C', path, 'rev-parse', 'HEAD')
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=path)
commit_hash, err = process.communicate()
retcode = process.wait()
if retcode == 0:
return commit_hash.strip().decode()
raise Exception(f"Failed to get commit hash: {commit_hash.decode()}")
def generate_version_info(path: str,
source_dir: str,
channel: str,
release_tag: Optional[str] = None
) -> Dict[str, Any]:
print(f"Generating version info: {source_dir}")
clean_repo(path)
owner_repo = OWNER_REPOS[source_dir]
curtime = int(time.time())
date_str = time.strftime("%Y%m%d", time.gmtime(curtime))
version = retreive_git_version(path)
if release_tag is None:
release_tag = version.split('-')[0]
source_hash = hash_directory(path, IGNORE_EXTS, IGNORE_DIRS)
long_version = f"{version}-moonraker-{date_str}"
release_info = {
'git_version': version,
'long_version': long_version,
'commit_hash': get_commit_hash(path),
'source_checksum': source_hash,
'ignored_exts': IGNORE_EXTS,
'ignored_dirs': IGNORE_DIRS,
'build_date': curtime,
'channel': channel,
'owner_repo': owner_repo,
'host_repo': OWNER_REPOS['moonraker'],
'release_tag': release_tag
}
vfile = pathlib.Path(os.path.join(path, source_dir, ".version"))
vfile.write_text(long_version)
rfile = pathlib.Path(os.path.join(path, ".release_info"))
rfile.write_text(json.dumps(release_info))
generate_dependency_info(path, source_dir)
return release_info
def create_zip(repo_path: str,
repo_name: str,
output_path: str
) -> None:
print(f"Creating Zip Release: {repo_name}")
zip_path = os.path.join(output_path, repo_name)
with tempfile.TemporaryDirectory() as tmp_dir:
dest_path = os.path.join(tmp_dir, repo_name)
ingore_cb = CopyIgnore(repo_path)
shutil.copytree(repo_path, dest_path, ignore=ingore_cb)
shutil.make_archive(zip_path, "zip", root_dir=dest_path)
def main() -> None:
# Parse start arguments
parser = argparse.ArgumentParser(
description="Generates zip releases for Moonraker and Klipper")
parser.add_argument(
"-k", "--klipper", default="~/klipper",
metavar='<klipper_path>',
help="Path to Klipper git repo")
parser.add_argument(
"-o", "--output", default=os.path.join(MOONRAKER_PATH, ".dist"),
metavar='<output_path>', help="Path to output directory")
parser.add_argument(
"-b", "--beta", action='store_true',
help="Tag release as beta")
args = parser.parse_args()
kpath: str = os.path.abspath(os.path.expanduser(args.klipper))
opath: str = os.path.abspath(os.path.expanduser(args.output))
is_beta: bool = args.beta
channel = "beta" if is_beta else "stable"
if not os.path.exists(kpath):
print(f"Invalid path to Klipper: {kpath}")
sys.exit(-1)
if not os.path.exists(opath):
print(f"Invalid output path: {opath}")
sys.exit(-1)
releases = get_releases()
all_info: Dict[str, Dict[str, Any]] = {}
try:
print("Generating Moonraker Zip Distribution...")
all_info['moonraker'] = generate_version_info(
MOONRAKER_PATH, "moonraker", channel)
create_zip(MOONRAKER_PATH, 'moonraker', opath)
rtag: str = all_info['moonraker']['release_tag']
print("Generating Klipper Zip Distribution...")
all_info['klipper'] = generate_version_info(
kpath, "klippy", channel, rtag)
create_zip(kpath, 'klipper', opath)
info_file = pathlib.Path(os.path.join(opath, "RELEASE_INFO"))
info_file.write_text(json.dumps(all_info))
last_rinfo = get_last_release_info(
all_info['moonraker']['git_version'], is_beta, releases)
commit_log = {}
commit_log['moonraker'] = get_commit_log(
MOONRAKER_PATH, last_rinfo.get('moonraker', {}))
commit_log['klipper'] = get_commit_log(
kpath, last_rinfo.get('klipper', {}))
clog_file = pathlib.Path(os.path.join(opath, "COMMIT_LOG"))
clog_file.write_text(json.dumps(commit_log))
except Exception:
print("Error Creating Zip Distribution")
traceback.print_exc(file=sys.stdout)
sys.exit(-1)
print(f"Build Complete. Files are located at '{opath}'")
if __name__ == "__main__":
main()
-355
View File
@@ -1,355 +0,0 @@
# GCode metadata extraction utility
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import json
import argparse
import re
import os
import sys
import time
# regex helpers
def _regex_find_floats(pattern, data, strict=False):
# If strict is enabled, pattern requires a floating point
# value, otherwise it can be an integer value
fptrn = r'\d+\.\d*' if strict else r'\d+\.?\d*'
matches = re.findall(pattern, data)
if matches:
# return the maximum height value found
try:
return [float(h) for h in re.findall(
fptrn, " ".join(matches))]
except Exception:
pass
return []
def _regex_find_ints(pattern, data):
matches = re.findall(pattern, data)
if matches:
# return the maximum height value found
try:
return [int(h) for h in re.findall(
r'\d+', " ".join(matches))]
except Exception:
pass
return []
# Slicer parsing implementations
class BaseSlicer(object):
def __init__(self, name, id_pattern):
self.name = name
self.id_pattern = id_pattern
self.header_data = self.footer_data = self.log = None
def set_data(self, header_data, footer_data, log):
self.header_data = header_data
self.footer_data = footer_data
self.log = log
def get_name(self):
return self.name
def get_id_pattern(self):
return self.id_pattern
def _parse_min_float(self, pattern, data):
result = _regex_find_floats(pattern, data)
if result:
return min(result)
else:
return None
def _parse_max_float(self, pattern, data):
result = _regex_find_floats(pattern, data)
if result:
return max(result)
else:
return None
class PrusaSlicer(BaseSlicer):
def __init__(self, name="PrusaSlicer", id_pattern=r"PrusaSlicer\s.*\son"):
super(PrusaSlicer, self).__init__(name, id_pattern)
def parse_first_layer_height(self):
return self._parse_min_float(
r"; first_layer_height =.*", self.footer_data)
def parse_layer_height(self):
return self._parse_min_float(r"; layer_height =.*", self.footer_data)
def parse_object_height(self):
return self._parse_max_float(r"G1\sZ\d+\.\d*\sF", self.footer_data)
def parse_filament_total(self):
return self._parse_max_float(
r"filament\sused\s\[mm\]\s=\s\d+\.\d*", self.footer_data)
def parse_estimated_time(self):
time_matches = re.findall(
r';\sestimated\sprinting\stime.*', self.footer_data)
if not time_matches:
return None
total_time = 0
time_match = time_matches[0]
time_patterns = [(r"\d+h", 60*60), (r"\d+m", 60), (r"\d+s", 1)]
for pattern, multiplier in time_patterns:
t = _regex_find_ints(pattern, time_match)
if t:
total_time += max(t) * multiplier
return round(total_time, 2)
def parse_thumbnails(self):
thumb_matches = re.findall(
r"; thumbnail begin[;/\+=\w\s]+?; thumbnail end", self.header_data)
if not thumb_matches:
return None
parsed_matches = []
for match in thumb_matches:
lines = re.split(r"\r?\n", match.replace('; ', ''))
info = _regex_find_ints(r".*", lines[0])
data = "".join(lines[1:-1])
if len(info) != 3:
self.log.append(
{'MetadataError': "Error parsing thumbnail header: %s"
% (lines[0])})
continue
if len(data) != info[2]:
self.log.append(
{'MetadataError': "Thumbnail Size Mismatch: detected %d, "
"actual %d" % (info[2], len(data))})
continue
parsed_matches.append({
'width': info[0], 'height': info[1],
'size': info[2], 'data': data})
return parsed_matches
class Slic3rPE(PrusaSlicer):
def __init__(self, name="Slic3r PE",
id_pattern=r"Slic3r\sPrusa\sEdition\s.*\son"):
super(Slic3rPE, self).__init__(name, id_pattern)
def parse_filament_total(self):
return self._parse_max_float(
r"filament\sused\s=\s\d+\.\d+mm", self.footer_data)
def parse_thumbnails(self):
return None
class Slic3r(Slic3rPE):
def __init__(self, name="Slic3r", id_pattern=r"Slic3r\s\d.*\son"):
super(Slic3r, self).__init__(name, id_pattern)
def parse_estimated_time(self):
return None
class SuperSlicer(PrusaSlicer):
def __init__(self, name="SuperSlicer", id_pattern=r"SuperSlicer\s.*\son"):
super(SuperSlicer, self).__init__(name, id_pattern)
class Cura(BaseSlicer):
def __init__(self, name="Cura", id_pattern=r"Cura_SteamEngine.*"):
super(Cura, self).__init__(name, id_pattern)
def parse_first_layer_height(self):
return self._parse_min_float(r";MINZ:.*", self.header_data)
def parse_layer_height(self):
return self._parse_min_float(r";Layer\sheight:.*", self.header_data)
def parse_object_height(self):
return self._parse_max_float(r";MAXZ:.*", self.header_data)
def parse_filament_total(self):
filament = self._parse_max_float(
r";Filament\sused:.*", self.header_data)
if filament is not None:
filament *= 1000
return filament
def parse_estimated_time(self):
return self._parse_max_float(r";TIME:.*", self.header_data)
def parse_thumbnails(self):
return None
class Simplify3D(BaseSlicer):
def __init__(self, name="Simplify3D", id_pattern=r"Simplify3D\(R\)"):
super(Simplify3D, self).__init__(name, id_pattern)
def parse_first_layer_height(self):
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_layer_height(self):
return self._parse_min_float(r";\s+layerHeight,.*", self.header_data)
def parse_object_height(self):
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
def parse_filament_total(self):
return self._parse_max_float(
r";\s+Filament\slength:.*mm", self.footer_data)
def parse_estimated_time(self):
time_matches = re.findall(
r';\s+Build time:.*', self.footer_data)
if not time_matches:
return None
total_time = 0
time_match = time_matches[0]
time_patterns = [(r"\d+\shours", 60*60), (r"\d+\smin", 60),
(r"\d+\ssec", 1)]
for pattern, multiplier in time_patterns:
t = _regex_find_ints(pattern, time_match)
if t:
total_time += max(t) * multiplier
return round(total_time, 2)
def parse_thumbnails(self):
return None
class KISSlicer(BaseSlicer):
def __init__(self, name="KISSlicer", id_pattern=r";\sKISSlicer"):
super(KISSlicer, self).__init__(name, id_pattern)
def parse_first_layer_height(self):
return self._parse_min_float(
r";\s+first_layer_thickness_mm\s=\s\d.*", self.header_data)
def parse_layer_height(self):
return self._parse_min_float(
r";\s+max_layer_thickness_mm\s=\s\d.*", self.header_data)
def parse_object_height(self):
return self._parse_max_float(
r";\sEND_LAYER_OBJECT\sz.*", self.footer_data)
def parse_filament_total(self):
filament = _regex_find_floats(
r";\s+Ext\s.*mm", self.footer_data, strict=True)
if filament:
return sum(filament)
return None
def parse_estimated_time(self):
time = self._parse_max_float(
r";\sCalculated.*Build\sTime:.*", self.footer_data)
if time is not None:
time *= 60
return round(time, 2)
def parse_thumbnails(self):
return None
class IdeaMaker(BaseSlicer):
def __init__(self, name="IdeaMaker", id_pattern=r"\sideaMaker\s.*,",):
super(IdeaMaker, self).__init__(name, id_pattern)
def parse_first_layer_height(self):
layer_info = _regex_find_floats(
r";LAYER:0\s*.*\s*;HEIGHT.*", self.header_data)
if len(layer_info) >= 3:
return layer_info[2]
return None
def parse_layer_height(self):
layer_info = _regex_find_floats(
r";LAYER:1\s*.*\s*;HEIGHT.*", self.header_data)
if len(layer_info) >= 3:
return layer_info[2]
return None
def parse_object_height(self):
bounds = _regex_find_floats(
r";Bounding Box:.*", self.footer_data)
if len(bounds) >= 6:
return bounds[5]
return None
def parse_filament_total(self):
filament = _regex_find_floats(
r";Material.\d\sUsed:.*", self.header_data, strict=True)
if filament:
return sum(filament)
return None
def parse_estimated_time(self):
return self._parse_max_float(r";Print\sTime:.*", self.footer_data)
def parse_thumbnails(self):
return None
READ_SIZE = 512 * 1024
SUPPORTED_SLICERS = [
PrusaSlicer, Slic3rPE, Slic3r, SuperSlicer,
Cura, Simplify3D, KISSlicer, IdeaMaker]
SUPPORTED_DATA = [
'first_layer_height', 'layer_height', 'object_height',
'filament_total', 'estimated_time', 'thumbnails']
def main(path, filename):
file_path = os.path.join(path, filename)
slicers = [s() for s in SUPPORTED_SLICERS]
log = []
metadata = {}
if not os.path.isfile(file_path):
log.append("File Not Found: %s" % (file_path))
else:
header_data = footer_data = slicer = None
size = os.path.getsize(file_path)
metadata['size'] = size
metadata['modified'] = time.ctime(os.path.getmtime(file_path))
with open(file_path, 'r') as f:
# read the default size, which should be enough to
# identify the slicer
header_data = f.read(READ_SIZE)
for s in slicers:
if re.search(s.get_id_pattern(), header_data) is not None:
slicer = s
break
if slicer is not None:
metadata['slicer'] = slicer.get_name()
if size > READ_SIZE * 2:
f.seek(size - READ_SIZE)
footer_data = f.read()
elif size > READ_SIZE:
remaining = size - READ_SIZE
footer_data = header_data[remaining - READ_SIZE:] + f.read()
else:
footer_data = header_data
slicer.set_data(header_data, footer_data, log)
for key in SUPPORTED_DATA:
func = getattr(slicer, "parse_" + key)
result = func()
if result is not None:
metadata[key] = result
fd = sys.stdout.fileno()
data = json.dumps(
{'file': filename, 'log': log, 'metadata': metadata}).encode()
while data:
try:
ret = os.write(fd, data)
except OSError:
continue
data = data[ret:]
if __name__ == "__main__":
# Parse start arguments
parser = argparse.ArgumentParser(
description="GCode Metadata Extraction Utility")
parser.add_argument(
"-f", "--filename", metavar='<filename>',
help="name gcode file to parse")
parser.add_argument(
"-p", "--path", default=os.path.abspath(os.path.dirname(__file__)),
metavar='<path>',
help="optional absolute path for file"
)
args = parser.parse_args()
main(args.path, args.filename)
+42
View File
@@ -0,0 +1,42 @@
#!/bin/bash
# Helper Script for fetching the API Key from a moonraker database
DATABASE_PATH="${HOME}/.moonraker_database"
MOONRAKER_ENV="${HOME}/moonraker-env"
DB_ARGS="--read=READ --db=authorized_users get _API_KEY_USER_"
API_REGEX='(?<="api_key": ")([^"]+)'
print_help()
{
echo "Moonraker API Key Extraction Utility"
echo
echo "usage: fetch-apikey.sh [-h] [-e <python env path>] [-d <database path>]"
echo
echo "optional arguments:"
echo " -h show this message"
echo " -e <env path> path to Moonraker env folder"
echo " -d <database path> path to Moonraker LMDB database folder"
exit 0
}
# Parse command line arguments
while getopts "he:d:" arg; do
case $arg in
h) print_help;;
e) MOONRAKER_ENV=$OPTARG;;
d) DATABASE_PATH=$OPTARG;;
esac
done
PYTHON_BIN="${MOONRAKER_ENV}/bin/python"
if [ ! -f $PYTHON_BIN ]; then
echo "No Python binary found at '${PYTHON_BIN}'"
exit -1
fi
if [ ! -d $DATABASE_PATH ]; then
echo "No Moonraker database found at '${DATABASE_PATH}'"
exit -1
fi
${PYTHON_BIN} -mlmdb --env=${DATABASE_PATH} ${DB_ARGS} | grep -Po "${API_REGEX}"
+71 -31
View File
@@ -3,11 +3,16 @@
# Raspbian/Raspberry Pi OS based distributions.
PYTHONDIR="${HOME}/moonraker-env"
SYSTEMDDIR="/etc/systemd/system"
REBUILD_ENV="n"
FORCE_DEFAULTS="n"
CONFIG_PATH="${HOME}/moonraker.conf"
LOG_PATH="/tmp/moonraker.log"
# Step 1: Verify Klipper has been installed
check_klipper()
{
if [ "$(systemctl list-units --full -all -t service --no-legend | grep -F "klipper.service")" ]; then
if [ "$(sudo systemctl list-units --full -all -t service --no-legend | grep -F "klipper.service")" ]; then
echo "Klipper service found!"
else
echo "Klipper service not found, please install Klipper first"
@@ -16,10 +21,23 @@ check_klipper()
}
# Step 2: Install packages
# Step 2: Clean up legacy installation
cleanup_legacy() {
if [ -f "/etc/init.d/moonraker" ]; then
# Stop Moonraker Service
echo "#### Cleanup legacy install script"
sudo systemctl stop moonraker
sudo update-rc.d -f moonraker remove
sudo rm -f /etc/init.d/moonraker
sudo rm -f /etc/default/moonraker
fi
}
# Step 3: Install packages
install_packages()
{
PKGLIST="python3-virtualenv python3-dev nginx"
PKGLIST="python3-virtualenv python3-dev nginx libopenjp2-7 python3-libgpiod"
PKGLIST="${PKGLIST} liblmdb0 libsodium-dev zlib1g-dev"
# Update system package info
report_status "Running apt-get update..."
@@ -30,52 +48,63 @@ install_packages()
sudo apt-get install --yes ${PKGLIST}
}
# Step 3: Create python virtual environment
# Step 4: Create python virtual environment
create_virtualenv()
{
report_status "Updating python virtual environment..."
report_status "Installing python virtual environment..."
# Create virtualenv if it doesn't already exist
[ ! -d ${PYTHONDIR} ] && virtualenv -p /usr/bin/python3 ${PYTHONDIR}
# If venv exists and user prompts a rebuild, then do so
if [ -d ${PYTHONDIR} ] && [ $REBUILD_ENV = "y" ]; then
report_status "Removing old virtualenv"
rm -rf ${PYTHONDIR}
fi
if [ ! -d ${PYTHONDIR} ]; then
virtualenv -p /usr/bin/python3 ${PYTHONDIR}
fi
# Install/update dependencies
${PYTHONDIR}/bin/pip install -r ${SRCDIR}/scripts/moonraker-requirements.txt
}
# Step 4: Install startup script
# Step 5: Install startup script
install_script()
{
# Create systemd service file
SERVICE_FILE="${SYSTEMDDIR}/moonraker.service"
[ -f $SERVICE_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
report_status "Installing system start script..."
sudo cp "${SRCDIR}/scripts/moonraker-start.sh" /etc/init.d/moonraker
sudo update-rc.d moonraker defaults
}
sudo /bin/sh -c "cat > ${SERVICE_FILE}" << EOF
#Systemd service file for moonraker
[Unit]
Description=API Server for Klipper
After=network.target
# Step 5: Install startup script config
install_config()
{
DEFAULTS_FILE=/etc/default/moonraker
[ -f $DEFAULTS_FILE ] && return
report_status "Installing system start configuration..."
sudo /bin/sh -c "cat > $DEFAULTS_FILE" <<EOF
# Configuration for /etc/init.d/moonraker
MOONRAKER_USER=$USER
MOONRAKER_EXEC=${PYTHONDIR}/bin/python
MOONRAKER_ARGS="${SRCDIR}/moonraker/moonraker.py"
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
User=$USER
RemainAfterExit=yes
WorkingDirectory=${SRCDIR}
ExecStart=${LAUNCH_CMD} -c ${CONFIG_PATH} -l ${LOG_PATH}
Restart=always
RestartSec=10
EOF
# Use systemctl to enable the klipper systemd service script
sudo systemctl enable moonraker.service
sudo systemctl daemon-reload
}
# Step 4: Start server
# Step 6: Start server
start_software()
{
report_status "Launching Moonraker API Server..."
sudo /etc/init.d/klipper stop
sudo /etc/init.d/moonraker restart
sudo /etc/init.d/klipper start
sudo systemctl stop klipper
sudo systemctl restart moonraker
sudo systemctl start klipper
}
# Helper functions
@@ -97,12 +126,23 @@ set -e
# Find SRCDIR from the pathname of this script
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
LAUNCH_CMD="${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py"
# Parse command line arguments
while getopts "rfc:l:" arg; do
case $arg in
r) REBUILD_ENV="y";;
f) FORCE_DEFAULTS="y";;
c) CONFIG_PATH=$OPTARG;;
l) LOG_PATH=$OPTARG;;
esac
done
# Run installation steps defined above
verify_ready
check_klipper
cleanup_legacy
install_packages
create_virtualenv
install_script
install_config
start_software
+8 -1
View File
@@ -1,3 +1,10 @@
# Python dependencies for Moonraker
tornado==6.0.4
tornado==6.1.0
pyserial==3.4
pillow==8.2.0
lmdb==1.2.1
streaming-form-data==1.8.1
distro==1.5.0
inotify-simple==1.3.5
libnacl==1.7.2
paho-mqtt==1.5.1
-55
View File
@@ -1,55 +0,0 @@
#!/bin/sh
# System startup script for Moonraker, Klipper's API Server
### BEGIN INIT INFO
# Provides: moonraker
# Required-Start: $local_fs
# Required-Stop:
# X-Start-Before: $klipper
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: moonraker daemon
# Description: Starts the Moonraker daemon
### END INIT INFO
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
DESC="moonraker daemon"
NAME="moonraker"
DEFAULTS_FILE=/etc/default/moonraker
PIDFILE=/var/run/moonraker.pid
. /lib/lsb/init-functions
# Read defaults file
[ -r $DEFAULTS_FILE ] && . $DEFAULTS_FILE
case "$1" in
start) log_daemon_msg "Starting moonraker" $NAME
start-stop-daemon --start --quiet --exec $MOONRAKER_EXEC \
--background --pidfile $PIDFILE --make-pidfile \
--chuid $MOONRAKER_USER --user $MOONRAKER_USER \
-- $MOONRAKER_ARGS
log_end_msg $?
;;
stop) log_daemon_msg "Stopping moonraker" $NAME
killproc -p $PIDFILE $MOONRAKER_EXEC
RETVAL=$?
[ $RETVAL -eq 0 ] && [ -e "$PIDFILE" ] && rm -f $PIDFILE
log_end_msg $RETVAL
;;
restart) log_daemon_msg "Restarting moonraker" $NAME
$0 stop
$0 start
;;
reload|force-reload)
log_daemon_msg "Reloading configuration not supported" $NAME
log_end_msg 1
;;
status)
status_of_proc -p $PIDFILE $MOONRAKER_EXEC $NAME && exit 0 || exit $?
;;
*) log_action_msg "Usage: /etc/init.d/moonraker {start|stop|status|restart|reload|force-reload}"
exit 2
;;
esac
exit 0
+184
View File
@@ -0,0 +1,184 @@
#!/bin/bash
# moonraker-sudo (mnrkrsudo)
# Provides a specified Group that is intended to elevate user privileges
# to help moonraker with sudo actions, if in CustomPIOS Images with
# Module "password-for-sudo".
#
# Partially used functions from Arcsine
#
# Copyright (C) 2020 Stephan Wendel <me@stephanwe.de>
#
# This file may be distributed under the terms of the GNU GPLv3 license
### Exit on Errors
set -e
### Configuration
SUDOERS_DIR='/etc/sudoers.d'
SUDOERS_FILE='020-sudo-for-moonraker'
NEW_GROUP='mnrkrsudo'
### Functions
verify_ready()
{
if [ "$EUID" -eq 0 ]; then
echo "This script must not run as root"
exit -1
fi
}
create_sudoers_file()
{
SCRIPT_TEMP_PATH=/tmp
report_status "Creating ${SUDOERS_FILE} ..."
sudo rm -f $SCRIPT_TEMP_PATH/$SUDOERS_FILE
sudo sed "s/GROUPNAME/$NEW_GROUP/g" > $SCRIPT_TEMP_PATH/$SUDOERS_FILE << '#EOF'
### Elevate moonraker API rights
### Do NOT allow Command Parts only Full Commands
### for example
###
### /sbin/systemctl "reboot", /sbin/apt "update", .....
Defaults!/usr/bin/apt-get env_keep +="DEBIAN_FRONTEND"
Cmnd_Alias REBOOT = /sbin/shutdown -r now, /bin/systemctl "reboot"
Cmnd_Alias SHUTDOWN = /sbin/shutdown now, /sbin/shutdown -h now, /bin/systemctl "poweroff"
Cmnd_Alias APT = /usr/bin/apt-get
Cmnd_Alias SYSTEMCTL = /bin/systemctl
%GROUPNAME ALL=(ALL) NOPASSWD: REBOOT, SHUTDOWN, APT, SYSTEMCTL
#EOF
report_status "\e[1;32m...done\e[0m"
}
update_env()
{
report_status "Export System Variable: DEBIAN_FRONTEND=noninteractive"
sudo /bin/sh -c 'echo "DEBIAN_FRONTEND=noninteractive" >> /etc/environment'
}
verify_syntax()
{
report_status "\e[1;33mVerifying Syntax of ${SUDOERS_FILE}\e[0m\n"
if [ $(LANG=C visudo -cf $SCRIPT_TEMP_PATH/$SUDOERS_FILE | grep -c "OK" ) -eq 1 ];
then
VERIFY_STATUS=0
report_status "\e[1;32m$(LANG=C visudo -cf $SCRIPT_TEMP_PATH/$SUDOERS_FILE)\e[0m"
else
report_status "\e[1;31mSyntax Error:\e[0m Check File: $SCRIPT_TEMP_PATH/$SUDOERS_FILE"
exit 1
fi
}
install_sudoers_file()
{
verify_syntax
if [ $VERIFY_STATUS -eq 0 ];
then
report_status "Copying $SCRIPT_TEMP_PATH/$SUDOERS_FILE to $SUDOERS_DIR/$SUDOERS_FILE"
sudo chmod 0440 $SCRIPT_TEMP_PATH/$SUDOERS_FILE
sudo cp --preserve=mode $SCRIPT_TEMP_PATH/$SUDOERS_FILE $SUDOERS_DIR/$SUDOERS_FILE
else
exit 1
fi
}
check_update_sudoers_file()
{
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ];
then
create_sudoers_file
if [ -z $(sudo diff $SCRIPT_TEMP_PATH/$SUDOERS_FILE $SUDOERS_DIR/$SUDOERS_FILE) ]
then
report_status "No need to update $SUDOERS_DIR/$SUDOERS_FILE"
else
report_status "$SUDOERS_DIR/$SUDOERS_FILE needs to be updated."
install_sudoers_file
fi
fi
}
add_new_group()
{
sudo addgroup --system $NEW_GROUP &> /dev/null
report_status "\e[1;32m...done\e[0m"
}
add_user_to_group()
{
sudo usermod -aG $NEW_GROUP $USER &> /dev/null
report_status "\e[1;32m...done\e[0m"
}
adduser_hint()
{
report_status "\e[1;31mYou have to REBOOT to take changes effect!\e[0m"
}
# Helper functions
report_status()
{
echo -e "\n\n###### $1"
}
clean_temp()
{
sudo rm -f $SCRIPT_TEMP_PATH/$SUDOERS_FILE
}
### Main
verify_ready
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ] && [ $(sudo cat /etc/gshadow | grep -c "${NEW_GROUP}") -eq 1 ] && [ $(groups | grep -c "$NEW_GROUP") -eq 1 ];
then
check_update_sudoers_file
report_status "\e[1;32mEverything is setup, nothing to do...\e[0m\n"
exit 0
else
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ];
then
report_status "\e[1;32mFile exists:\e[0m ${SUDOERS_FILE}"
check_update_sudoers_file
else
report_status "\e[1;31mFile not found:\e[0m ${SUDOERS_FILE}\n"
create_sudoers_file
install_sudoers_file
fi
if [ $(sudo cat /etc/gshadow | grep -c "${NEW_GROUP}") -eq 1 ];
then
report_status "Group ${NEW_GROUP} already exists..."
else
report_status "Group ${NEW_GROUP} will be added..."
add_new_group
fi
if [ $(groups | grep -c "$NEW_GROUP") -eq 1 ];
then
report_status "User ${USER} is already in $NEW_GROUP..."
else
report_status "Adding User ${USER} to Group $NEW_GROUP..."
add_user_to_group
adduser_hint
fi
fi
update_env
clean_temp
exit 0
+17 -9
View File
@@ -4,20 +4,25 @@
stop_service() {
# Stop Moonraker Service
echo "#### Stopping Moonraker Service.."
sudo service moonraker stop
sudo systemctl stop moonraker
}
remove_service() {
# Remove Moonraker from Startup
echo
echo "#### Removing Moonraker from Startup.."
sudo update-rc.d -f moonraker remove
# Remove Moonraker from Services
# Remove Moonraker LSB/systemd service
echo
echo "#### Removing Moonraker Service.."
sudo rm -f /etc/init.d/moonraker /etc/default/moonraker
if [ -f "/etc/init.d/moonraker" ]; then
# legacy installation, remove the LSB service
sudo update-rc.d -f moonraker remove
sudo rm -f /etc/init.d/moonraker
sudo rm -f /etc/default/moonraker
else
# Remove systemd installation
sudo systemctl disable moonraker
sudo rm -f /etc/systemd/system/moonraker.service
sudo systemctl daemon-reload
sudo systemctl reset-failed
fi
}
remove_files() {
@@ -47,6 +52,9 @@ remove_files() {
echo
echo "The following command is typically used to remove source files:"
echo " rm -rf ~/moonraker"
echo
echo "You may also wish to uninstall nginx:"
echo " sudo apt-get remove nginx"
}
verify_ready()
+128
View File
@@ -0,0 +1,128 @@
#lean_overlay {
position: fixed;
z-index:100;
top: 0px;
left: 0px;
height:100%;
width:100%;
background: #000;
display: none;
}
.user {
width: 404px;
padding-bottom: 2px;
display:none;
background: #FFF;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
box-shadow: 0px 0px 4px rgba(0,0,0,0.7);
-webkit-box-shadow: 0 0 4px rgba(0,0,0,0.7);
-moz-box-shadow: 0 0px 4px rgba(0,0,0,0.7);
}
.user-header {
/*background: url(../img/hd-bg.png);*/
background: #cecece;
padding: 8px 8px 8px 8px;
border-bottom: 1px solid #CCC;
border-top-left-radius: 5px;
-moz-border-radius-topleft: 5px;
-webkit-border-top-left-radius: 5px;
border-top-right-radius: 5px;
-moz-border-radius-topright: 5px;
-webkit-border-top-right-radius: 5px;
}
.user-header h2 {
color: #444;
font-size: 1.2em;
font-weight: 700;
margin-bottom: 3px;
text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.5);
}
.user-header p {
color: #444;
font-size: 1em;
margin: 0;
text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.5);
text-shadow: none;
}
.user .text-field {
position: relative;
width: 364px;
padding: 14px 20px;
border-bottom: 1px solid #EEE;
text-align: right;
}
.user .button-field {
width: 254px;
overflow: hidden;
padding: 12px 20px 12px 130px;
}
.user .text-field label {
display: block;
float: left;
width: 90px;
padding-top: 8px;
color: #222;
font-size: 1em;
text-align: left;
}
.user .text-field input {
width: 244px;
padding: 8px;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
font-size: 1em; color: #222;
background: #F7F7F7;
font-family: "Helvetica Neue";
outline: none;
border-top: 1px solid #CCC;
border-left: 1px solid #CCC;
border-right: 1px solid #E7E6E6;
border-bottom: 1px solid #E7E6E6;
}
/*.user .text-field input.good_input {
background: #DEF5E1 url(../img/good.png) 236px center no-repeat;
}*/
.user .text-field input.error_input {
background: #FDE0E0;
}
.user-button {
float: right;
font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
background: #cecece;
border: none;
width: auto;
overflow: visible;
font-size: 1.1em;
color: rgb(0, 0, 0);
padding: 7px 10px;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
text-shadow: 0 1px 0 rgba(0,0,0,0.4);
}
.modal_close {
position: absolute;
top: 12px;
right: 12px;
display: inline-block;
border: none;
width: 20px;
height: 20px;
background: url(../img/close-button.png);
z-index: 2;
}
+5
View File
@@ -0,0 +1,5 @@
// leanModal v1.1 by Ray Stone - http://finelysliced.com.au
// Dual licensed under the MIT and GPL
(function($){$.fn.extend({leanModal:function(options){var defaults={top:100,overlay:0.5,closeButton:null};var overlay=$("<div id='lean_overlay'></div>");$("body").append(overlay);options=$.extend(defaults,options);return this.each(function(){var o=options;$(this).click(function(e){var modal_id=$(this).attr("href");$("#lean_overlay").click(function(){close_modal(modal_id)});$(o.closeButton).click(function(){close_modal(modal_id)});var modal_height=$(modal_id).outerHeight();var modal_width=$(modal_id).outerWidth();
$("#lean_overlay").css({"display":"block",opacity:0});$("#lean_overlay").fadeTo(200,o.overlay);$(modal_id).css({"display":"block","position":"fixed","opacity":0,"z-index":11000,"left":50+"%","margin-left":-(modal_width/2)+"px","top":o.top+"px"});$(modal_id).fadeTo(200,1);e.preventDefault()})});function close_modal(modal_id){$("#lean_overlay").fadeOut(200);$(modal_id).css({"display":"none"})}}})})(jQuery);
+8647
View File
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
/*! jsTree - v3.3.10 - 2020-06-16 - (MIT) */
!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery"],a):"undefined"!=typeof module&&module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a,b){"use strict";if(!a.jstree){var c=0,d=!1,e=!1,f=!1,g=[],h=a("script:last").attr("src"),i=window.document,j=window.setImmediate,k=window.Promise;!j&&k&&(j=function(a,b){k.resolve(b).then(a)}),a.jstree={version:"3.3.10",defaults:{plugins:[]},plugins:{},path:h&&-1!==h.indexOf("/")?h.replace(/\/[^\/]+$/,""):"",idregex:/[\\:&!^|()\[\]<>@*'+~#";.,=\- \/${}%?`]/g,root:"#"},a.jstree.create=function(b,d){var e=new a.jstree.core(++c),f=d;return d=a.extend(!0,{},a.jstree.defaults,d),f&&f.plugins&&(d.plugins=f.plugins),a.each(d.plugins,function(a,b){"core"!==a&&(e=e.plugin(b,d[b]))}),a(b).data("jstree",e),e.init(b,d),e},a.jstree.destroy=function(){a(".jstree:jstree").jstree("destroy"),a(i).off(".jstree")},a.jstree.core=function(a){this._id=a,this._cnt=0,this._wrk=null,this._data={core:{themes:{name:!1,dots:!1,icons:!1,ellipsis:!1},selected:[],last_error:{},working:!1,worker_queue:[],focused:null}}},a.jstree.reference=function(b){var c=null,d=null;if(!b||!b.id||b.tagName&&b.nodeType||(b=b.id),!d||!d.length)try{d=a(b)}catch(e){}if(!d||!d.length)try{d=a("#"+b.replace(a.jstree.idregex,"\\$&"))}catch(e){}return d&&d.length&&(d=d.closest(".jstree")).length&&(d=d.data("jstree"))?c=d:a(".jstree").each(function(){var d=a(this).data("jstree");return d&&d._model.data[b]?(c=d,!1):void 0}),c},a.fn.jstree=function(c){var d="string"==typeof c,e=Array.prototype.slice.call(arguments,1),f=null;return c!==!0||this.length?(this.each(function(){var g=a.jstree.reference(this),h=d&&g?g[c]:null;return f=d&&h?h.apply(g,e):null,g||d||c!==b&&!a.isPlainObject(c)||a.jstree.create(this,c),(g&&!d||c===!0)&&(f=g||!1),null!==f&&f!==b?!1:void 0}),null!==f&&f!==b?f:this):!1},a.expr.pseudos.jstree=a.expr.createPseudo(function(c){return function(c){return a(c).hasClass("jstree")&&a(c).data("jstree")!==b}}),a.jstree.defaults.core={data:!1,strings:!1,check_callback:!1,error:a.noop,animation:200,multiple:!0,themes:{name:!1,url:!1,dir:!1,dots:!0,icons:!0,ellipsis:!1,stripes:!1,variant:!1,responsive:!1},expand_selected_onload:!0,worker:!0,force_text:!1,dblclick_toggle:!0,loaded_state:!1,restore_focus:!0,keyboard:{"ctrl-space":function(b){b.type="click",a(b.currentTarget).trigger(b)},enter:function(b){b.type="click",a(b.currentTarget).trigger(b)},left:function(b){if(b.preventDefault(),this.is_open(b.currentTarget))this.close_node(b.currentTarget);else{var c=this.get_parent(b.currentTarget);c&&c.id!==a.jstree.root&&this.get_node(c,!0).children(".jstree-anchor").focus()}},up:function(a){a.preventDefault();var b=this.get_prev_dom(a.currentTarget);b&&b.length&&b.children(".jstree-anchor").focus()},right:function(b){if(b.preventDefault(),this.is_closed(b.currentTarget))this.open_node(b.currentTarget,function(a){this.get_node(a,!0).children(".jstree-anchor").focus()});else if(this.is_open(b.currentTarget)){var c=this.get_node(b.currentTarget,!0).children(".jstree-children")[0];c&&a(this._firstChild(c)).children(".jstree-anchor").focus()}},down:function(a){a.preventDefault();var b=this.get_next_dom(a.currentTarget);b&&b.length&&b.children(".jstree-anchor").focus()},"*":function(a){this.open_all()},home:function(b){b.preventDefault();var c=this._firstChild(this.get_container_ul()[0]);c&&a(c).children(".jstree-anchor").filter(":visible").focus()},end:function(a){a.preventDefault(),this.element.find(".jstree-anchor").filter(":visible").last().focus()},f2:function(a){a.preventDefault(),this.edit(a.currentTarget)}}},a.jstree.core.prototype={plugin:function(b,c){var d=a.jstree.plugins[b];return d?(this._data[b]={},d.prototype=this,new d(c,this)):this},init:function(b,c){this._model={data:{},changed:[],force_full_redraw:!1,redraw_timeout:!1,default_state:{loaded:!0,opened:!1,selected:!1,disabled:!1}},this._model.data[a.jstree.root]={id:a.jstree.root,parent:null,parents:[],children:[],children_d:[],state:{loaded:!1}},this.element=a(b).addClass("jstree jstree-"+this._id),this.settings=c,this._data.core.ready=!1,this._data.core.loaded=!1,this._data.core.rtl="rtl"===this.element.css("direction"),this.element[this._data.core.rtl?"addClass":"removeClass"]("jstree-rtl"),this.element.attr("role","tree"),this.settings.core.multiple&&this.element.attr("aria-multiselectable",!0),this.element.attr("tabindex")||this.element.attr("tabindex","0"),this.bind(),this.trigger("init"),this._data.core.original_container_html=this.element.find(" > ul > li").clone(!0),this._data.core.original_container_html.find("li").addBack().contents().filter(function(){return 3===this.nodeType&&(!this.nodeValue||/^\s+$/.test(this.nodeValue))}).remove(),this.element.html("<ul class='jstree-container-ul jstree-children' role='group'><li id='j"+this._id+"_loading' class='jstree-initial-node jstree-loading jstree-leaf jstree-last' role='presentation'><i class='jstree-icon jstree-ocl'></i><a class='jstree-anchor' role='treeitem' hLine truncated
if(a&&"object"==typeof a.state)for(f in a.state)a.state.hasOwnProperty(f)&&(l.state[f]=a.state[f]);if(a&&"object"==typeof a.li_attr)for(f in a.li_attr)a.li_attr.hasOwnProperty(f)&&(l.li_attr[f]=a.li_attr[f]);if(l.li_attr.id&&!l.id&&(l.id=l.li_attr.id.toString()),l.id||(l.id=e),l.li_attr.id||(l.li_attr.id=l.id),a&&"object"==typeof a.a_attr)for(f in a.a_attr)a.a_attr.hasOwnProperty(f)&&(l.a_attr[f]=a.a_attr[f]);if(a&&a.children&&a.children.length){for(f=0,g=a.children.length;g>f;f++)h=this._parse_model_from_json(a.children[f],l.id,d),i=j[h],l.children.push(h),i.children_d.length&&(l.children_d=l.children_d.concat(i.children_d));l.children_d=l.children.concat(l.children_d)}return a&&a.children&&a.children===!0&&(l.state.loaded=!1,l.children=[],l.children_d=[]),delete a.data,delete a.children,l.original=a,j[l.id]=l,l.state.selected&&this._data.core.selected.push(l.id),l.id},_redraw:function(){var b=this._model.force_full_redraw?this._model.data[a.jstree.root].children.concat([]):this._model.changed.concat([]),c=i.createElement("UL"),d,e,f,g=this._data.core.focused;for(e=0,f=b.length;f>e;e++)d=this.redraw_node(b[e],!0,this._model.force_full_redraw),d&&this._model.force_full_redraw&&c.appendChild(d);this._model.force_full_redraw&&(c.className=this.get_container_ul()[0].className,c.setAttribute("role","group"),this.element.empty().append(c)),null!==g&&this.settings.core.restore_focus&&(d=this.get_node(g,!0),d&&d.length&&d.children(".jstree-anchor")[0]!==i.activeElement?d.children(".jstree-anchor").focus():this._data.core.focused=null),this._model.force_full_redraw=!1,this._model.changed=[],this.trigger("redraw",{nodes:b})},redraw:function(a){a&&(this._model.force_full_redraw=!0),this._redraw()},draw_children:function(b){var c=this.get_node(b),d=!1,e=!1,f=!1,g=i;if(!c)return!1;if(c.id===a.jstree.root)return this.redraw(!0);if(b=this.get_node(b,!0),!b||!b.length)return!1;if(b.children(".jstree-children").remove(),b=b[0],c.children.length&&c.state.loaded){for(f=g.createElement("UL"),f.setAttribute("role","group"),f.className="jstree-children",d=0,e=c.children.length;e>d;d++)f.appendChild(this.redraw_node(c.children[d],!0,!0));b.appendChild(f)}},redraw_node:function(b,c,d,e){var f=this.get_node(b),g=!1,h=!1,j=!1,k=!1,l=!1,m=!1,n="",o=i,p=this._model.data,q=!1,r=!1,s=null,t=0,u=0,v=!1,w=!1;if(!f)return!1;if(f.id===a.jstree.root)return this.redraw(!0);if(c=c||0===f.children.length,b=i.querySelector?this.element[0].querySelector("#"+(-1!=="0123456789".indexOf(f.id[0])?"\\3"+f.id[0]+" "+f.id.substr(1).replace(a.jstree.idregex,"\\$&"):f.id.replace(a.jstree.idregex,"\\$&"))):i.getElementById(f.id))b=a(b),d||(g=b.parent().parent()[0],g===this.element[0]&&(g=null),h=b.index()),c||!f.children.length||b.children(".jstree-children").length||(c=!0),c||(j=b.children(".jstree-children")[0]),q=b.children(".jstree-anchor")[0]===i.activeElement,b.remove();else if(c=!0,!d){if(g=f.parent!==a.jstree.root?a("#"+f.parent.replace(a.jstree.idregex,"\\$&"),this.element)[0]:null,!(null===g||g&&p[f.parent].state.opened))return!1;h=a.inArray(f.id,null===g?p[a.jstree.root].children:p[f.parent].children)}b=this._data.core.node.cloneNode(!0),n="jstree-node ";for(k in f.li_attr)if(f.li_attr.hasOwnProperty(k)){if("id"===k)continue;"class"!==k?b.setAttribute(k,f.li_attr[k]):n+=f.li_attr[k]}for(f.a_attr.id||(f.a_attr.id=f.id+"_anchor"),b.setAttribute("aria-selected",!!f.state.selected),b.childNodes[1].setAttribute("aria-selected",!!f.state.selected),b.setAttribute("aria-level",f.parents.length),b.childNodes[1].setAttribute("aria-level",f.parents.length),b.setAttribute("aria-labelledby",f.a_attr.id),f.state.disabled&&(b.setAttribute("aria-disabled",!0),b.childNodes[1].setAttribute("aria-disabled",!0)),k=0,l=f.children.length;l>k;k++)if(!p[f.children[k]].state.hidden){v=!0;break}if(null!==f.parent&&p[f.parent]&&!f.state.hidden&&(k=a.inArray(f.id,p[f.parent].children),w=f.id,-1!==k))for(k++,l=p[f.parent].children.length;l>k;k++)if(p[p[f.parent].children[k]].state.hidden||(w=p[f.parent].children[k]),w!==f.id)break;f.state.hidden&&(n+=" jstree-hidden"),f.state.loading&&(n+=" jstree-loading"),f.state.loaded&&!v?n+=" jstree-leaf":(n+=f.state.opened&&f.state.loaded?" jstree-open":" jstree-closed",b.setAttribute("aria-expanded",f.state.opened&&f.state.loaded),b.childNodes[1].setAttribute("aria-expanded",f.state.opened&&f.state.loaded)),w===f.id&&(n+=" jstree-last"),b.id=f.id,b.className=n,n=(f.state.selected?" jstree-clicked":"")+(f.state.disabled?" jstree-disabled":"");for(l in f.a_attr)if(f.a_attr.hasOwnProperty(l)){if("href"===l&&"#"===f.a_attr[l])continue;"class"!==l?b.childNodes[1].setAttribute(l,f.a_attr[l]):n+=" "+f.a_attr[l]}if(n.length&&(b.childNodes[1].className="jstree-anchor "+n),(f.icon&&f.icon!==!0||f.icon===!1)&&(f.icon===!1?b.childNodes[1].childNodes[0].className+=" jstree-themeicon-hidden":-1===f.icon.indexOf("/")&&-1===f.icon.indexOf(".")?b.childNodes[1].childNodes[0].className+=" "+f.icon+" jstree-themeicon-custom":(b.childNodes[1].childNodeLine truncated
!p)return!1;for(m=this.get_node(p),c&&c.state&&c.state.loaded===!1&&(m.state.loaded=!1),l=[],l.push(p),l=l.concat(m.children_d),this.trigger("model",{nodes:l,parent:r.id}),n=0,o=r.parents.length;o>n;n++)this._model.data[r.parents[n]].children_d=this._model.data[r.parents[n]].children_d.concat(l);for(l=[],n=0,o=r.children.length;o>n;n++)l[n>=e?n+1:n]=r.children[n];return l[e]=m.id,r.children=l,r.children_d.push(m.id),r.children_d=r.children_d.concat(m.children_d),r.id===a.jstree.root&&(this._model.force_full_redraw=!0),this._model.force_full_redraw||this._node_changed(r.id),h||this.redraw(r.id===a.jstree.root),f&&f.call(this,m,r,e),this.trigger("copy_node",{node:m,original:c,parent:r.id,position:e,old_parent:q,old_position:s&&s._id&&q&&s._model.data[q]&&s._model.data[q].children?a.inArray(c.id,s._model.data[q].children):-1,is_multi:s&&s._id&&s._id!==this._id,is_foreign:!s||!s._id,old_instance:s,new_instance:this}),m.id},cut:function(b){if(b||(b=this._data.core.selected.concat()),a.isArray(b)||(b=[b]),!b.length)return!1;var c=[],g,h,i;for(h=0,i=b.length;i>h;h++)g=this.get_node(b[h]),g&&g.id&&g.id!==a.jstree.root&&c.push(g);return c.length?(d=c,f=this,e="move_node",void this.trigger("cut",{node:b})):!1},copy:function(b){if(b||(b=this._data.core.selected.concat()),a.isArray(b)||(b=[b]),!b.length)return!1;var c=[],g,h,i;for(h=0,i=b.length;i>h;h++)g=this.get_node(b[h]),g&&g.id&&g.id!==a.jstree.root&&c.push(g);return c.length?(d=c,f=this,e="copy_node",void this.trigger("copy",{node:b})):!1},get_buffer:function(){return{mode:e,node:d,inst:f}},can_paste:function(){return e!==!1&&d!==!1},paste:function(a,b){return a=this.get_node(a),a&&e&&e.match(/^(copy_node|move_node)$/)&&d?(this[e](d,a,b,!1,!1,!1,f)&&this.trigger("paste",{parent:a.id,node:d,mode:e}),d=!1,e=!1,void(f=!1)):!1},clear_buffer:function(){d=!1,e=!1,f=!1,this.trigger("clear_buffer")},edit:function(b,c,d){var e,f,g,h,j,k,l,m,n,o=!1;return(b=this.get_node(b))?this.check("edit",b,this.get_parent(b))?(n=b,c="string"==typeof c?c:b.text,this.set_text(b,""),b=this._open_to(b),n.text=c,e=this._data.core.rtl,f=this.element.width(),this._data.core.focused=n.id,g=b.children(".jstree-anchor").focus(),h=a("<span></span>"),j=c,k=a("<div></div>",{css:{position:"absolute",top:"-200px",left:e?"0px":"-1000px",visibility:"hidden"}}).appendTo(i.body),l=a("<input />",{value:j,"class":"jstree-rename-input",css:{padding:"0",border:"1px solid silver","box-sizing":"border-box",display:"inline-block",height:this._data.core.li_height+"px",lineHeight:this._data.core.li_height+"px",width:"150px"},blur:a.proxy(function(c){c.stopImmediatePropagation(),c.preventDefault();var e=h.children(".jstree-rename-input"),f=e.val(),i=this.settings.core.force_text,m;""===f&&(f=j),k.remove(),h.replaceWith(g),h.remove(),j=i?j:a("<div></div>").append(a.parseHTML(j)).html(),b=this.get_node(b),this.set_text(b,j),m=!!this.rename_node(b,i?a("<div></div>").text(f).text():a("<div></div>").append(a.parseHTML(f)).html()),m||this.set_text(b,j),this._data.core.focused=n.id,setTimeout(a.proxy(function(){var a=this.get_node(n.id,!0);a.length&&(this._data.core.focused=n.id,a.children(".jstree-anchor").focus())},this),0),d&&d.call(this,n,m,o),l=null},this),keydown:function(a){var b=a.which;27===b&&(o=!0,this.value=j),(27===b||13===b||37===b||38===b||39===b||40===b||32===b)&&a.stopImmediatePropagation(),(27===b||13===b)&&(a.preventDefault(),this.blur())},click:function(a){a.stopImmediatePropagation()},mousedown:function(a){a.stopImmediatePropagation()},keyup:function(a){l.width(Math.min(k.text("pW"+this.value).width(),f))},keypress:function(a){return 13===a.which?!1:void 0}}),m={fontFamily:g.css("fontFamily")||"",fontSize:g.css("fontSize")||"",fontWeight:g.css("fontWeight")||"",fontStyle:g.css("fontStyle")||"",fontStretch:g.css("fontStretch")||"",fontVariant:g.css("fontVariant")||"",letterSpacing:g.css("letterSpacing")||"",wordSpacing:g.css("wordSpacing")||""},h.attr("class",g.attr("class")).append(g.contents().clone()).append(l),g.replaceWith(h),k.css(m),l.css(m).width(Math.min(k.text("pW"+l[0].value).width(),f))[0].select(),void a(i).one("mousedown.jstree touchstart.jstree dnd_start.vakata",function(b){l&&b.target!==l&&a(l).blur()})):(this.settings.core.error.call(this,this._data.core.last_error),!1):!1},set_theme:function(b,c){if(!b)return!1;if(c===!0){var d=this.settings.core.themes.dir;d||(d=a.jstree.path+"/themes"),c=d+"/"+b+"/style.css"}c&&-1===a.inArray(c,g)&&(a("head").append('<link rel="stylesheet" href="'+c+'" type="text/css" />'),g.push(c)),this._data.core.themes.name&&this.element.removeClass("jstree-"+this._data.core.themes.name),this._data.core.themes.name=b,this.element.addClass("jstree-"+b),this.element[this.settings.core.themes.responsive?"addClass":"removeClass"]("jstree-"+b+"-responsive"),this.trigger("set_theme",{theme:b})},get_theme:function(){return this._data.core.themes.name},set_theme_variant:function(a){this._data.core.themes.variant&&this.element.removeClass("jstree-"+this._data.core.theLine truncated
item:b,reference:c.reference,element:c.element}))&&b.action?b.action.call(null,{item:b,reference:c.reference,element:c.element,position:{x:c.position_x,y:c.position_y}}):!1},_parse:function(b,d){if(!b)return!1;d||(c.html="",c.items=[]);var e="",f=!1,g;return d&&(e+="<ul>"),a.each(b,function(b,d){return d?(c.items.push(d),!f&&d.separator_before&&(e+="<li class='vakata-context-separator'><a href='#' "+(a.vakata.context.settings.icons?"":'style="margin-left:0px;"')+">&#160;</a></li>"),f=!1,e+="<li class='"+(d._class||"")+(d._disabled===!0||a.isFunction(d._disabled)&&d._disabled({item:d,reference:c.reference,element:c.element})?" vakata-contextmenu-disabled ":"")+"' "+(d.shortcut?" data-shortcut='"+d.shortcut+"' ":"")+">",e+="<a href='#' rel='"+(c.items.length-1)+"' "+(d.title?"title='"+d.title+"'":"")+">",a.vakata.context.settings.icons&&(e+="<i ",d.icon&&(e+=-1!==d.icon.indexOf("/")||-1!==d.icon.indexOf(".")?" style='background:url(\""+d.icon+"\") center center no-repeat' ":" class='"+d.icon+"' "),e+="></i><span class='vakata-contextmenu-sep'>&#160;</span>"),e+=(a.isFunction(d.label)?d.label({item:b,reference:c.reference,element:c.element}):d.label)+(d.shortcut?' <span class="vakata-contextmenu-shortcut vakata-contextmenu-shortcut-'+d.shortcut+'">'+(d.shortcut_label||"")+"</span>":"")+"</a>",d.submenu&&(g=a.vakata.context._parse(d.submenu,!0),g&&(e+=g)),e+="</li>",void(d.separator_after&&(e+="<li class='vakata-context-separator'><a href='#' "+(a.vakata.context.settings.icons?"":'style="margin-left:0px;"')+">&#160;</a></li>",f=!0))):!0}),e=e.replace(/<li class\='vakata-context-separator'\><\/li\>$/,""),d&&(e+="</ul>"),d||(c.html=e,a.vakata.context._trigger("parse")),e.length>10?e:!1},_show_submenu:function(c){if(c=a(c),c.length&&c.children("ul").length){var d=c.children("ul"),e=c.offset().left,f=e+c.outerWidth(),g=c.offset().top,h=d.width(),i=d.height(),j=a(window).width()+a(window).scrollLeft(),k=a(window).height()+a(window).scrollTop();b?c[f-(h+10+c.outerWidth())<0?"addClass":"removeClass"]("vakata-context-left"):c[f+h>j&&e>j-f?"addClass":"removeClass"]("vakata-context-right"),g+i+10>k&&d.css("bottom","-1px"),c.hasClass("vakata-context-right")?h>e&&d.css("margin-right",e-h):h>j-f&&d.css("margin-left",j-f-h),d.show()}},show:function(d,e,f){var g,h,j,k,l,m,n,o,p=!0;switch(c.element&&c.element.length&&c.element.width(""),p){case!e&&!d:return!1;case!!e&&!!d:c.reference=d,c.position_x=e.x,c.position_y=e.y;break;case!e&&!!d:c.reference=d,g=d.offset(),c.position_x=g.left+d.outerHeight(),c.position_y=g.top;break;case!!e&&!d:c.position_x=e.x,c.position_y=e.y}d&&!f&&a(d).data("vakata_contextmenu")&&(f=a(d).data("vakata_contextmenu")),a.vakata.context._parse(f)&&c.element.html(c.html),c.items.length&&(c.element.appendTo(i.body),h=c.element,j=c.position_x,k=c.position_y,l=h.width(),m=h.height(),n=a(window).width()+a(window).scrollLeft(),o=a(window).height()+a(window).scrollTop(),b&&(j-=h.outerWidth()-a(d).outerWidth(),j<a(window).scrollLeft()+20&&(j=a(window).scrollLeft()+20)),j+l+20>n&&(j=n-(l+20)),k+m+20>o&&(k=o-(m+20)),c.element.css({left:j,top:k}).show().find("a").first().focus().parent().addClass("vakata-context-hover"),c.is_visible=!0,a.vakata.context._trigger("show"))},hide:function(){c.is_visible&&(c.element.hide().find("ul").hide().end().find(":focus").blur().end().detach(),c.is_visible=!1,a.vakata.context._trigger("hide"))}},a(function(){b="rtl"===a(i.body).css("direction");var d=!1;c.element=a("<ul class='vakata-context'></ul>"),c.element.on("mouseenter","li",function(b){b.stopImmediatePropagation(),a.contains(this,b.relatedTarget)||(d&&clearTimeout(d),c.element.find(".vakata-context-hover").removeClass("vakata-context-hover").end(),a(this).siblings().find("ul").hide().end().end().parentsUntil(".vakata-context","li").addBack().addClass("vakata-context-hover"),a.vakata.context._show_submenu(this))}).on("mouseleave","li",function(b){a.contains(this,b.relatedTarget)||a(this).find(".vakata-context-hover").addBack().removeClass("vakata-context-hover")}).on("mouseleave",function(b){a(this).find(".vakata-context-hover").removeClass("vakata-context-hover"),a.vakata.context.settings.hide_onmouseleave&&(d=setTimeout(function(b){return function(){a.vakata.context.hide()}}(this),a.vakata.context.settings.hide_onmouseleave))}).on("click","a",function(b){b.preventDefault(),a(this).blur().parent().hasClass("vakata-context-disabled")||a.vakata.context._execute(a(this).attr("rel"))===!1||a.vakata.context.hide()}).on("keydown","a",function(b){var d=null;switch(b.which){case 13:case 32:b.type="click",b.preventDefault(),a(b.currentTarget).trigger(b);break;case 37:c.is_visible&&(c.element.find(".vakata-context-hover").last().closest("li").first().find("ul").hide().find(".vakata-context-hover").removeClass("vakata-context-hover").end().end().children("a").focus(),b.stopImmediatePropagation(),b.preventDefault());break;case 38:c.is_visible&&(d=c.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClaLine truncated
e[f[h]].type=j,e[f[h]].icon===!0&&g[j].icon!==b&&(e[f[h]].icon=g[j].icon),g[j].li_attr!==b&&"object"==typeof g[j].li_attr)for(k in g[j].li_attr)if(g[j].li_attr.hasOwnProperty(k)){if("id"===k)continue;e[f[h]].li_attr[k]===b?e[f[h]].li_attr[k]=g[j].li_attr[k]:"class"===k&&(e[f[h]].li_attr["class"]=g[j].li_attr["class"]+" "+e[f[h]].li_attr["class"])}if(g[j].a_attr!==b&&"object"==typeof g[j].a_attr)for(k in g[j].a_attr)if(g[j].a_attr.hasOwnProperty(k)){if("id"===k)continue;e[f[h]].a_attr[k]===b?e[f[h]].a_attr[k]=g[j].a_attr[k]:"href"===k&&"#"===e[f[h]].a_attr[k]?e[f[h]].a_attr.href=g[j].a_attr.href:"class"===k&&(e[f[h]].a_attr["class"]=g[j].a_attr["class"]+" "+e[f[h]].a_attr["class"])}}e[a.jstree.root].type=a.jstree.root},this)),d.bind.call(this)},this.get_json=function(b,c,e){var f,g,h=this._model.data,i=c?a.extend(!0,{},c,{no_id:!1}):{},j=d.get_json.call(this,b,i,e);if(j===!1)return!1;if(a.isArray(j))for(f=0,g=j.length;g>f;f++)j[f].type=j[f].id&&h[j[f].id]&&h[j[f].id].type?h[j[f].id].type:"default",c&&c.no_id&&(delete j[f].id,j[f].li_attr&&j[f].li_attr.id&&delete j[f].li_attr.id,j[f].a_attr&&j[f].a_attr.id&&delete j[f].a_attr.id);else j.type=j.id&&h[j.id]&&h[j.id].type?h[j.id].type:"default",c&&c.no_id&&(j=this._delete_ids(j));return j},this._delete_ids=function(b){if(a.isArray(b)){for(var c=0,d=b.length;d>c;c++)b[c]=this._delete_ids(b[c]);return b}return delete b.id,b.li_attr&&b.li_attr.id&&delete b.li_attr.id,b.a_attr&&b.a_attr.id&&delete b.a_attr.id,b.children&&a.isArray(b.children)&&(b.children=this._delete_ids(b.children)),b},this.check=function(c,e,f,g,h){if(d.check.call(this,c,e,f,g,h)===!1)return!1;e=e&&e.id?e:this.get_node(e),f=f&&f.id?f:this.get_node(f);var i=e&&e.id?h&&h.origin?h.origin:a.jstree.reference(e.id):null,j,k,l,m;switch(i=i&&i._model&&i._model.data?i._model.data:null,c){case"create_node":case"move_node":case"copy_node":if("move_node"!==c||-1===a.inArray(e.id,f.children)){if(j=this.get_rules(f),j.max_children!==b&&-1!==j.max_children&&j.max_children===f.children.length)return this._data.core.last_error={error:"check",plugin:"types",id:"types_01",reason:"max_children prevents function: "+c,data:JSON.stringify({chk:c,pos:g,obj:e&&e.id?e.id:!1,par:f&&f.id?f.id:!1})},!1;if(j.valid_children!==b&&-1!==j.valid_children&&-1===a.inArray(e.type||"default",j.valid_children))return this._data.core.last_error={error:"check",plugin:"types",id:"types_02",reason:"valid_children prevents function: "+c,data:JSON.stringify({chk:c,pos:g,obj:e&&e.id?e.id:!1,par:f&&f.id?f.id:!1})},!1;if(i&&e.children_d&&e.parents){for(k=0,l=0,m=e.children_d.length;m>l;l++)k=Math.max(k,i[e.children_d[l]].parents.length);k=k-e.parents.length+1}(0>=k||k===b)&&(k=1);do{if(j.max_depth!==b&&-1!==j.max_depth&&j.max_depth<k)return this._data.core.last_error={error:"check",plugin:"types",id:"types_03",reason:"max_depth prevents function: "+c,data:JSON.stringify({chk:c,pos:g,obj:e&&e.id?e.id:!1,par:f&&f.id?f.id:!1})},!1;f=this.get_node(f.parent),j=this.get_rules(f),k++}while(f)}}return!0},this.get_rules=function(a){if(a=this.get_node(a),!a)return!1;var c=this.get_type(a,!0);return c.max_depth===b&&(c.max_depth=-1),c.max_children===b&&(c.max_children=-1),c.valid_children===b&&(c.valid_children=-1),c},this.get_type=function(b,c){return b=this.get_node(b),b?c?a.extend({type:b.type},this.settings.types[b.type]):b.type:!1},this.set_type=function(c,d){var e=this._model.data,f,g,h,i,j,k,l,m;if(a.isArray(c)){for(c=c.slice(),g=0,h=c.length;h>g;g++)this.set_type(c[g],d);return!0}if(f=this.settings.types,c=this.get_node(c),!f[d]||!c)return!1;if(l=this.get_node(c,!0),l&&l.length&&(m=l.children(".jstree-anchor")),i=c.type,j=this.get_icon(c),c.type=d,(j===!0||!f[i]||f[i].icon!==b&&j===f[i].icon)&&this.set_icon(c,f[d].icon!==b?f[d].icon:!0),f[i]&&f[i].li_attr!==b&&"object"==typeof f[i].li_attr)for(k in f[i].li_attr)if(f[i].li_attr.hasOwnProperty(k)){if("id"===k)continue;"class"===k?(e[c.id].li_attr["class"]=(e[c.id].li_attr["class"]||"").replace(f[i].li_attr[k],""),l&&l.removeClass(f[i].li_attr[k])):e[c.id].li_attr[k]===f[i].li_attr[k]&&(e[c.id].li_attr[k]=null,l&&l.removeAttr(k))}if(f[i]&&f[i].a_attr!==b&&"object"==typeof f[i].a_attr)for(k in f[i].a_attr)if(f[i].a_attr.hasOwnProperty(k)){if("id"===k)continue;"class"===k?(e[c.id].a_attr["class"]=(e[c.id].a_attr["class"]||"").replace(f[i].a_attr[k],""),m&&m.removeClass(f[i].a_attr[k])):e[c.id].a_attr[k]===f[i].a_attr[k]&&("href"===k?(e[c.id].a_attr[k]="#",m&&m.attr("href","#")):(delete e[c.id].a_attr[k],m&&m.removeAttr(k)))}if(f[d].li_attr!==b&&"object"==typeof f[d].li_attr)for(k in f[d].li_attr)if(f[d].li_attr.hasOwnProperty(k)){if("id"===k)continue;e[c.id].li_attr[k]===b?(e[c.id].li_attr[k]=f[d].li_attr[k],l&&("class"===k?l.addClass(f[d].li_attr[k]):l.attr(k,f[d].li_attr[k]))):"class"===k&&(e[c.id].li_attr["class"]=f[d].li_attr[k]+" "+e[c.id].li_attr["class"],l&&l.addClass(f[d].li_attr[k]))}if(f[d].a_attr!==b&&"object"==typeof f[d].a_attr)for(k in f[d].a_attr)if(f[d].a_attr.hasOwnProperty(k)){if("idLine truncated
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
.jstree-node,.jstree-children,.jstree-container-ul{display:block;margin:0;padding:0;list-style-type:none;list-style-image:none}.jstree-node{white-space:nowrap}.jstree-anchor{display:inline-block;color:black;white-space:nowrap;padding:0 4px 0 1px;margin:0;vertical-align:top}.jstree-anchor:focus{outline:0}.jstree-anchor,.jstree-anchor:link,.jstree-anchor:visited,.jstree-anchor:hover,.jstree-anchor:active{text-decoration:none;color:inherit}.jstree-icon{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-icon:empty{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-ocl{cursor:pointer}.jstree-leaf>.jstree-ocl{cursor:default}.jstree .jstree-open>.jstree-children{display:block}.jstree .jstree-closed>.jstree-children,.jstree .jstree-leaf>.jstree-children{display:none}.jstree-anchor>.jstree-themeicon{margin-right:2px}.jstree-no-icons .jstree-themeicon,.jstree-anchor>.jstree-themeicon-hidden{display:none}.jstree-hidden,.jstree-node.jstree-hidden{display:none}.jstree-rtl .jstree-anchor{padding:0 1px 0 4px}.jstree-rtl .jstree-anchor>.jstree-themeicon{margin-left:2px;margin-right:0}.jstree-rtl .jstree-node{margin-left:0}.jstree-rtl .jstree-container-ul>.jstree-node{margin-right:0}.jstree-wholerow-ul{position:relative;display:inline-block;min-width:100%}.jstree-wholerow-ul .jstree-leaf>.jstree-ocl{cursor:pointer}.jstree-wholerow-ul .jstree-anchor,.jstree-wholerow-ul .jstree-icon{position:relative}.jstree-wholerow-ul .jstree-wholerow{width:100%;cursor:pointer;position:absolute;left:0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.jstree-contextmenu .jstree-anchor{-webkit-user-select:none;-webkit-touch-callout:none}.vakata-context{display:none}.vakata-context,.vakata-context ul{margin:0;padding:2px;position:absolute;background:#f5f5f5;border:1px solid #979797;box-shadow:2px 2px 2px #999999}.vakata-context ul{list-style:none;left:100%;margin-top:-2.7em;margin-left:-4px}.vakata-context .vakata-context-right ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context li{list-style:none}.vakata-context li>a{display:block;padding:0 2em 0 2em;text-decoration:none;width:auto;color:black;white-space:nowrap;line-height:2.4em;text-shadow:1px 1px 0 white;border-radius:1px}.vakata-context li>a:hover{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAIORI4JlrqN1oMSnmmZDQUAOw==");background-position:right center;background-repeat:no-repeat}.vakata-context li>a:focus{outline:0}.vakata-context .vakata-context-hover>a{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context .vakata-context-separator>a,.vakata-context .vakata-context-separator>a:hover{background:white;border:0;border-top:1px solid #e2e3e3;height:1px;min-height:1px;max-height:1px;padding:0;margin:0 0 0 2.4em;border-left:1px solid #e0e0e0;text-shadow:0 0 0 transparent;box-shadow:0 0 0 transparent;border-radius:0}.vakata-context .vakata-contextmenu-disabled a,.vakata-context .vakata-contextmenu-disabled a:hover{color:silver;background-color:transparent;border:0;box-shadow:0 0 0}.vakata-context .vakata-contextmenu-disabled>a>i{filter:grayscale(100%)}.vakata-context li>a>i{text-decoration:none;display:inline-block;width:2.4em;height:2.4em;background:transparent;margin:0 0 0 -2em;vertical-align:top;text-align:center;line-height:2.4em}.vakata-context li>a>i:empty{width:2.4em;line-height:2.4em}.vakata-context li>a .vakata-contextmenu-sep{display:inline-block;width:1px;height:2.4em;background:white;margin:0 .5em 0 0;border-left:1px solid #e2e3e3}.vakata-context .vakata-contextmenu-shortcut{font-size:.8em;color:silver;opacity:.5;display:none}.vakata-context-rtl ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context-rtl li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAINjI+AC7rWHIsPtmoxLAA7");background-position:left center;background-repeat:no-repeat}.vakata-context-rtl .vakata-context-separator>a{margin:0 2.4em 0 0;border-left:0;border-right:1px solid #e2e3e3}.vakata-context-rtl .vakata-context-left ul{right:auto;left:100%;margin-left:-4px;margin-right:auto}.vakata-context-rtl li>a>i{margin:0 -2em 0 0}.vakata-context-rtl li>a .vakata-contextmenu-sep{margin:0 0 0 .5em;border-left-color:white;background:#e2e3e3}#jstree-marker{position:absolute;top:0;left:0;margin:-5px 0 0 0;padding:0;border-right:0;border-top:5px solid transparent;border-bottom:5px solid transparent;border-left:5px solid;width:0;height:0;font-size:0;line-height:0}#jstree-dnd{line-height:16px;margin:0;padding:4px}#jstree-dnd .jstree-icon,#jstree-dnd .jstree-copy{display:inline-block;text-decoration:none;margin:0 2px 0 0;padding:0;width:16px;height:16px}#jstree-dnd .jstree-ok{background:Line truncated
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
.jstree-node,.jstree-children,.jstree-container-ul{display:block;margin:0;padding:0;list-style-type:none;list-style-image:none}.jstree-node{white-space:nowrap}.jstree-anchor{display:inline-block;color:black;white-space:nowrap;padding:0 4px 0 1px;margin:0;vertical-align:top}.jstree-anchor:focus{outline:0}.jstree-anchor,.jstree-anchor:link,.jstree-anchor:visited,.jstree-anchor:hover,.jstree-anchor:active{text-decoration:none;color:inherit}.jstree-icon{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-icon:empty{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-ocl{cursor:pointer}.jstree-leaf>.jstree-ocl{cursor:default}.jstree .jstree-open>.jstree-children{display:block}.jstree .jstree-closed>.jstree-children,.jstree .jstree-leaf>.jstree-children{display:none}.jstree-anchor>.jstree-themeicon{margin-right:2px}.jstree-no-icons .jstree-themeicon,.jstree-anchor>.jstree-themeicon-hidden{display:none}.jstree-hidden,.jstree-node.jstree-hidden{display:none}.jstree-rtl .jstree-anchor{padding:0 1px 0 4px}.jstree-rtl .jstree-anchor>.jstree-themeicon{margin-left:2px;margin-right:0}.jstree-rtl .jstree-node{margin-left:0}.jstree-rtl .jstree-container-ul>.jstree-node{margin-right:0}.jstree-wholerow-ul{position:relative;display:inline-block;min-width:100%}.jstree-wholerow-ul .jstree-leaf>.jstree-ocl{cursor:pointer}.jstree-wholerow-ul .jstree-anchor,.jstree-wholerow-ul .jstree-icon{position:relative}.jstree-wholerow-ul .jstree-wholerow{width:100%;cursor:pointer;position:absolute;left:0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.jstree-contextmenu .jstree-anchor{-webkit-user-select:none;-webkit-touch-callout:none}.vakata-context{display:none}.vakata-context,.vakata-context ul{margin:0;padding:2px;position:absolute;background:#f5f5f5;border:1px solid #979797;box-shadow:2px 2px 2px #999999}.vakata-context ul{list-style:none;left:100%;margin-top:-2.7em;margin-left:-4px}.vakata-context .vakata-context-right ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context li{list-style:none}.vakata-context li>a{display:block;padding:0 2em 0 2em;text-decoration:none;width:auto;color:black;white-space:nowrap;line-height:2.4em;text-shadow:1px 1px 0 white;border-radius:1px}.vakata-context li>a:hover{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAIORI4JlrqN1oMSnmmZDQUAOw==");background-position:right center;background-repeat:no-repeat}.vakata-context li>a:focus{outline:0}.vakata-context .vakata-context-hover>a{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context .vakata-context-separator>a,.vakata-context .vakata-context-separator>a:hover{background:white;border:0;border-top:1px solid #e2e3e3;height:1px;min-height:1px;max-height:1px;padding:0;margin:0 0 0 2.4em;border-left:1px solid #e0e0e0;text-shadow:0 0 0 transparent;box-shadow:0 0 0 transparent;border-radius:0}.vakata-context .vakata-contextmenu-disabled a,.vakata-context .vakata-contextmenu-disabled a:hover{color:silver;background-color:transparent;border:0;box-shadow:0 0 0}.vakata-context .vakata-contextmenu-disabled>a>i{filter:grayscale(100%)}.vakata-context li>a>i{text-decoration:none;display:inline-block;width:2.4em;height:2.4em;background:transparent;margin:0 0 0 -2em;vertical-align:top;text-align:center;line-height:2.4em}.vakata-context li>a>i:empty{width:2.4em;line-height:2.4em}.vakata-context li>a .vakata-contextmenu-sep{display:inline-block;width:1px;height:2.4em;background:white;margin:0 .5em 0 0;border-left:1px solid #e2e3e3}.vakata-context .vakata-contextmenu-shortcut{font-size:.8em;color:silver;opacity:.5;display:none}.vakata-context-rtl ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context-rtl li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAINjI+AC7rWHIsPtmoxLAA7");background-position:left center;background-repeat:no-repeat}.vakata-context-rtl .vakata-context-separator>a{margin:0 2.4em 0 0;border-left:0;border-right:1px solid #e2e3e3}.vakata-context-rtl .vakata-context-left ul{right:auto;left:100%;margin-left:-4px;margin-right:auto}.vakata-context-rtl li>a>i{margin:0 -2em 0 0}.vakata-context-rtl li>a .vakata-contextmenu-sep{margin:0 0 0 .5em;border-left-color:white;background:#e2e3e3}#jstree-marker{position:absolute;top:0;left:0;margin:-5px 0 0 0;padding:0;border-right:0;border-top:5px solid transparent;border-bottom:5px solid transparent;border-left:5px solid;width:0;height:0;font-size:0;line-height:0}#jstree-dnd{line-height:16px;margin:0;padding:4px}#jstree-dnd .jstree-icon,#jstree-dnd .jstree-copy{display:inline-block;text-decoration:none;margin:0 2px 0 0;padding:0;width:16px;height:16px}#jstree-dnd .jstree-ok{background:Line truncated
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 643 B

+119 -20
View File
@@ -1,8 +1,13 @@
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/main.js?v=0.1.18" type="module"></script>
<link rel="stylesheet" href="dist/themes/default/style.min.css"/>
<link rel="stylesheet" href="css/login_dialog.css"/>
<script src="//cdn.jsdelivr.net/npm/sha256-uint8array/dist/sha256-uint8array.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="dist/jstree.min.js"></script>
<script src="dist/jquery.leanModal.min.js"></script>
<script src="/js/main.js?v=0.1.3" type="module"></script>
</head>
<body>
<h3>Klippy Web API Test</h3>
@@ -37,27 +42,13 @@
</form>
<br/>
<div style="display: flex">
<input type="file" style="display:none" id="upload-file" />
<div style="width: 10em">
<button id="btnupload" class="toggleable" style="width: 9em">Upload File</button><br/><br/>
<button id="btndownload" class="toggleable" style="width: 9em">Download File</button><br/><br/>
<button id="btndelete" class="toggleable" style="width: 9em">Delete File</button><br/><br/>
<button id="btngetfiles" style="width: 9em">Refresh List</button>
<a id="hidden_link" href="#" hidden>hidden</a>
</div>
<div style="width: 10em">
<button id="btnstartprint" style="width: 9em">Start Print</button><br/><br/>
<button id="btnpauseresume" style="width: 9em">Pause Print</button><br/><br/>
<button id="btncancelprint" style="width: 9em">Cancel Print</button><br/><br/>
<button id="btngetmetadata" style="width: 9em">Get Metadata</button>
</div>
<div>
<select id="filelist" size="8"></select>
</div>
<div id=filetype>
<input type="radio" name="file_type" value="gcodes" checked="true">GCodes<br/>
<input type="radio" name="file_type" value="config">Config Files<br/>
<input type="radio" name="file_type" value="config_examples">Config Examples
<a id="hidden_link" href="#" hidden>hidden</a>
<input type="file" style="display:none" id="upload-file" />
<div id="filelist">
</div>
</div>
<br/>
@@ -65,9 +56,10 @@ Progress: <progress id="progressbar" value="0" max="100"></progress>
<span id="upload_progress">0%</span><br/><br/>
<button id="btnqueryendstops" style="width: 9em">Query Endstops</button>
<button id="btnsubscribe" style="width: 9em">Post Subscription</button>
<button id="btngetsub" style="width: 9em">Get Subscription</button>
<button id="btngetfiles" style="width: 9em">Get File List</button>
<button id="btngethelp" style="width: 9em">Get Gcode Help</button>
<button id="btngetobjs" style="width: 9em">Get Object List</button>
<button id="btntestmesh" style="width: 9em">Get Bed Mesh</button>
<button id="btnsendbatch" class="reqws" style="width: 9em">Test GC Batch</button>
<button id="btnsendmacro" class="reqws" style="width: 9em">Test GC Macro</button>
<br/><br/>
@@ -78,10 +70,117 @@ Progress: <progress id="progressbar" value="0" max="100"></progress>
<button id="btnshutdown" style="width: 9em">Shutdown OS</button>
<button id="btngetlog" style="width: 9em">Klippy Log</button>
<button id="btnmoonlog" style="width: 9em">Moonraker Log</button>
<br/><br/>
<button id="btnloginuser" style="width: 9em">Login User</button>
<button id="btncreateuser" style="width: 9em">Create User</button>
<button id="btnsetapikey" style="width: 9em">Set API Key</button>
<button id="btnlogout" style="width: 9em" class="req-login">Log Out</button>
<button id="btndeluser" style="width: 9em" class="req-login">Delete User</button>
<button id="btnchangepass" style="width: 9em" class="req-login">Change Pass</button>
<br/><br/>
<span id="filename" hidden></span></br>
<div id="streamdiv">
</div>
<a id="nav_home" href="#" hidden>Hidden Home</a>
<a id="do_login" rel="leanModal" name="login" href="#login" hidden>Hidden Login</a>
<div id="login" class="user">
<div id="login-ct">
<div id="login-header" class="user-header">
<h2>Moonraker Login</h2>
<button id="login_close" class="modal_close"></a>
</div>
<form id="login_form" class="user-form">
<div class="text-field">
<label for="login_username">Username</label>
<input id="login_username" class="good_input" name="login_username" type="text" />
</div>
<div class="text-field">
<label for="login_password">Password</label>
<input id="login_password" name="login_password" type="password" />
</div>
<div class="button-field">
<button type="submit" class="user-button">Login</button>
</div>
</form>
</div>
</div>
<a id="do_deleteuser" rel="leanModal" name="deleteuser" href="#deleteuser" hidden>Hidden Delete</a>
<div id="deleteuser" class="user">
<div id="login-ct">
<div id="deleteuser-header" class="user-header">
<h2>Delete User</h2>
<button id="deleteuser_close" class="modal_close"></a>
</div>
<form id="deleteuser_form" class="user-form">
<div class="text-field">
<label for="deleteuser_username">Username</label>
<input id="deleteuser_username" class="good_input" name="deleteuser_username" type="text" />
</div>
<div class="button-field">
<button type="submit" class="user-button">Submit</button>
</div>
</form>
</div>
</div>
<a id="do_signup" rel="leanModal" name="signup" href="#signup" hidden>Hidden Signup</a>
<div id="signup" class="user">
<div id="signup-ct">
<div id="signup-header" class="user-header">
<h2>Create User</h2>
<button id="signup_close" class="modal_close"></a>
</div>
<form id="signup_form" class="user-form">
<div class="text-field">
<label for="signup_username">Username</label>
<input id="signup_username" class="good_input" name="signup_username" type="text" />
</div>
<div class="text-field">
<label for="signup_password">Password</label>
<input id="signup_password" name="signup_password" type="password" />
</div>
<div class="text-field">
<label for="signup_verify_pass">Re-Enter Password</label>
<input id="signup_verify_pass" name="signup_verify_pass" type="password" />
</div>
<div class="button-field">
<button type="submit" class="user-button">Signup</button>
</div>
</form>
</div>
</div>
<a id="do_changepass" rel="leanModal" name="changepass" href="#changepass" hidden></a>
<div id="changepass" class="user">
<div id="changepass-ct">
<div id="changepass-header" class="user-header">
<h2>Change Password</h2>
<button id="changepass_close" class="modal_close"></a>
</div>
<form id="changepass_form" class="user-form">
<div class="text-field">
<label for="changepass_oldpass">Current Password</label>
<input id="changepass_oldpass" name="changepass_oldpass" type="password" />
</div>
<div class="text-field">
<label for="changepass_newpass">New Password</label>
<input id="changepass_newpass" name="changepass_newpass" type="password" />
</div>
<div class="text-field">
<label for="changepass_verify_pass">Re-Enter New Password</label>
<input id="changepass_verify_pass" name="changepass_verify_pass" type="password" />
</div>
<div class="button-field">
<button type="submit" class="user-button">Submit</button>
</div>
</form>
</div>
</div>
</body>
</html>
+1171 -433
View File
File diff suppressed because it is too large. Load diff