494 Commits
Author SHA1 Message Date
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
66 changed files with 23225 additions and 3389 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
+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/) - March 10th 2021
Developers:\
[api_changes.md](https://moonraker.readthedocs.io/en/latest/api_changes/) - March 15th 2021
+326
View File
@@ -0,0 +1,326 @@
##
This document keeps a record of all changes to Moonraker's web APIs.
### 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"}
```
+304
View File
@@ -0,0 +1,304 @@
## 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, protocol=["http", "websocket"], 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 `protocol` is a list containing any combination of `http` and `websocket`.
If `websocket` is selected associated JSON-RPC methods 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
`SeverError` 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 `SeverError` 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 `SeverError` 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 `SeverError` 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 `SeverError` will be raised.
+414
View File
@@ -0,0 +1,414 @@
#
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
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.
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. This section is required.
```ini
# moonraker.conf
[authorization]
enabled: True
# Enables authorization. When set to true, requests must either contain
# a valid API key or originate from a trusted client. Default is True.
api_key_file: ~/.moonraker_api_key
# Path of the file that stores Moonraker's API key. The default is
# ~/.moonraker_api_key
trusted_clients:
192.168.1.30
192.168.1.0/24
# A list of newline 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.
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.
```
## `[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 are supported.
```ini
# moonraker.conf
[power device_name]
type: gpio
# The type of device. Can be either gpio, tplink_smartplug, tasmota
# or homeseer.
# 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. The
# address must be provided. The port defaults to 9999.
address:
password:
output_id:
# 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:
# 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).
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
```
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
```
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:
TURN_OFF_MOTORS
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.
distro: debian
# The disto in which moonraker has been installed. Currently the
# update manager only supports "debian", which encompasses all of
# its derivatives. The default is debain.
```
### 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 client_name]
type: web
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 git repositories that have a service that need
updating.
```ini
# moonraker.conf
# service_name must be the name of the systemd service
[update_manager client service_name]
type: git_repo
path:
# The absolute path to the client's files on disk. This parameter must be provided.
# Example:
# path: ~/service_name
origin:
# The full GitHub 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.
```
+54 -14
View File
@@ -8,24 +8,64 @@ 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
```
# 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 or documentation should exceed 80 characters.
Be sure there is no trailing whitespace.
- 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.1.2
+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.
+144 -197
View File
@@ -6,241 +6,188 @@ 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.
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.
```
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.
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.
### Additional Notes
## Plugin Configuration
The core plugins are configured via the primary configuration above. Optional
plugins each need their own configuration as outlined below.
- 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.
### PanelDue Plugin
```
[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
```
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
+380
View File
@@ -0,0 +1,380 @@
#
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 "standby", "printing", "paused",
"complete", or "error". 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.
+73
View File
@@ -0,0 +1,73 @@
##
This file will track changes that require user intervention,
such as a configuration change or a reinstallation.
### 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.
+2664 -586
View File
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
site_name: Moonraker
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
+285 -206
View File
@@ -7,45 +7,30 @@
import os
import mimetypes
import logging
import json
import tornado
from inspect import isclass
from tornado.escape import url_unescape
from tornado.routing import Rule, PathMatches, AnyMatches
from tornado.log import access_log
from utils import ServerError
from websockets import WebsocketManager, WebSocket
from websockets import WebRequest, WebsocketManager, WebSocket
from authorization import AuthorizedRequestHandler, AuthorizedFileHandler
from authorization import Authorization
# Max Upload Size of 200MB
MAX_UPLOAD_SIZE = 200 * 1024 * 1024
from streaming_form_data import StreamingFormDataParser
from streaming_form_data.targets import FileTarget, ValueTarget
# These endpoints are reserved for klippy/server communication only and are
# not exposed via http or the websocket
RESERVED_ENDPOINTS = [
"list_endpoints", "moonraker/get_configuration"
"list_endpoints", "gcode/subscribe_output",
"register_remote_method"
]
# Status objects require special parsing
def _status_parser(request):
query_args = request.query_arguments
args = {}
for key, vals in query_args.items():
parsed = []
for v in vals:
if v:
parsed += v.decode().split(',')
args[key] = parsed
return args
# Built-in Query String Parser
def _default_parser(request):
query_args = request.query_arguments
args = {}
for key, vals in query_args.items():
if len(vals) != 1:
raise tornado.web.HTTPError(404, "Invalid Query String")
args[key] = vals[0].decode()
return args
# 50 MiB Max Standard Body Size
MAX_BODY_SIZE = 50 * 1024 * 1024
EXCLUDED_ARGS = ["_", "token", "connection_id"]
DEFAULT_KLIPPY_LOG_PATH = "/tmp/klippy.log"
class MutableRouter(tornado.web.ReversibleRuleRouter):
def __init__(self, application):
@@ -77,135 +62,164 @@ class MutableRouter(tornado.web.ReversibleRuleRouter):
try:
self.rules.remove(rule)
except Exception:
logging.exception("Unable to remove rule: %s" % (pattern))
logging.exception(f"Unable to remove rule: {pattern}")
class APIDefinition:
def __init__(self, endpoint, http_uri, ws_method,
request_methods, parser):
def __init__(self, endpoint, http_uri, ws_methods,
request_methods, need_object_parser):
self.endpoint = endpoint
self.uri = http_uri
self.ws_method = ws_method
self.ws_methods = ws_methods
if not isinstance(request_methods, list):
request_methods = [request_methods]
self.request_methods = request_methods
self.parser = parser
self.need_object_parser = need_object_parser
class MoonrakerApp:
def __init__(self, server, args):
self.server = server
def __init__(self, config):
self.server = config.get_server()
self.tornado_server = None
self.api_cache = {}
self.registered_base_handlers = []
self.max_upload_size = config.getint('max_upload_size', 1024)
self.max_upload_size *= 1024 * 1024
# Set Up Websocket and Authorization Managers
self.wsm = WebsocketManager(server)
self.auth = Authorization(args.apikey)
self.wsm = WebsocketManager(self.server)
self.auth = Authorization(config['authorization'])
mimetypes.add_type('text/plain', '.log')
mimetypes.add_type('text/plain', '.gcode')
mimetypes.add_type('text/plain', '.cfg')
debug = config.getboolean('enable_debug_logging', False)
log_level = logging.DEBUG if debug else logging.INFO
logging.getLogger().setLevel(log_level)
app_args = {
'serve_traceback': debug,
'websocket_ping_interval': 10,
'websocket_ping_timeout': 30,
'parent': self,
'default_handler_class': AuthorizedErrorHandler,
'default_handler_args': {}
}
if not debug:
app_args['log_function'] = self.log_release_mode
# Set up HTTP only requests
self.mutable_router = MutableRouter(self)
app_handlers = [
(AnyMatches(), self.mutable_router),
(r"/websocket", WebSocket,
{'wsm': self.wsm, 'auth': self.auth}),
(r"/api/version", EmulateOctoprintHandler,
{'server': server, 'auth': self.auth})]
self.app = tornado.web.Application(
app_handlers,
serve_traceback=args.debug,
websocket_ping_interval=10,
websocket_ping_timeout=30,
enable_cors=False)
(r"/websocket", WebSocket)]
self.app = tornado.web.Application(app_handlers, **app_args)
self.get_handler_delegate = self.app.get_handler_delegate
# Register handlers
self.register_static_file_handler("moonraker.log", args.logfile)
logfile = config['system_args'].get('logfile')
if logfile:
self.register_static_file_handler(
"moonraker.log", logfile, force=True)
self.register_static_file_handler(
"klippy.log", DEFAULT_KLIPPY_LOG_PATH, force=True)
self.auth.register_handlers(self)
def listen(self, host, port):
self.tornado_server = self.app.listen(
port, address=host, max_body_size=MAX_UPLOAD_SIZE,
port, address=host, max_body_size=MAX_BODY_SIZE,
xheaders=True)
def log_release_mode(self, handler):
status_code = handler.get_status()
if status_code in [200, 204]:
# don't log OK and No Content
return
if status_code < 400:
log_method = access_log.info
elif status_code < 500:
log_method = access_log.warning
else:
log_method = access_log.error
request_time = 1000.0 * handler.request.request_time()
log_method("%d %s %.2fms", status_code,
handler._request_summary(), request_time)
def get_server(self):
return self.server
def get_auth(self):
return self.auth
def get_websocket_manager(self):
return self.wsm
async def close(self):
if self.tornado_server is not None:
self.tornado_server.stop()
await self.tornado_server.close_all_connections()
await self.wsm.close()
self.auth.close()
def load_config(self, config):
if 'enable_cors' in config:
self.app.settings['enable_cors'] = config['enable_cors']
self.auth.load_config(config)
def register_remote_handler(self, endpoint):
if endpoint in RESERVED_ENDPOINTS:
return
api_def = self.api_cache.get(
endpoint, self._create_api_definition(endpoint))
api_def = self._create_api_definition(endpoint)
if api_def.uri in self.registered_base_handlers:
# reserved handler or already registered
return
logging.info("Registering remote endpoint: (%s) %s" % (
" ".join(api_def.request_methods), api_def.uri))
self.wsm.register_handler(api_def)
logging.info(
f"Registering remote endpoint - "
f"HTTP: ({' '.join(api_def.request_methods)}) {api_def.uri}; "
f"Websocket: {', '.join(api_def.ws_methods)}")
self.wsm.register_remote_handler(api_def)
params = {}
params['server'] = self.server
params['auth'] = self.auth
params['methods'] = api_def.request_methods
params['arg_parser'] = api_def.parser
params['remote_callback'] = api_def.endpoint
params['callback'] = api_def.endpoint
params['need_object_parser'] = api_def.need_object_parser
self.mutable_router.add_handler(
api_def.uri, RemoteRequestHandler, params)
api_def.uri, DynamicRequestHandler, params)
self.registered_base_handlers.append(api_def.uri)
def register_local_handler(self, uri, ws_method, request_methods,
callback, http_only=False):
def register_local_handler(self, uri, request_methods,
callback, protocol=["http", "websocket"],
wrap_result=True):
if uri in self.registered_base_handlers:
return
api_def = self._create_api_definition(
uri, ws_method, request_methods)
logging.info("Registering local endpoint: (%s) %s" % (
" ".join(request_methods), uri))
if not http_only:
self.wsm.register_handler(api_def, callback)
params = {}
params['server'] = self.server
params['auth'] = self.auth
params['methods'] = request_methods
params['arg_parser'] = api_def.parser
params['callback'] = callback
self.mutable_router.add_handler(uri, LocalRequestHandler, params)
self.registered_base_handlers.append(uri)
uri, request_methods, is_remote=False)
msg = "Registering local endpoint"
if "http" in protocol:
msg += f" - HTTP: ({' '.join(request_methods)}) {uri}"
params = {}
params['methods'] = request_methods
params['callback'] = callback
params['wrap_result'] = wrap_result
params['is_remote'] = False
self.mutable_router.add_handler(uri, DynamicRequestHandler, params)
self.registered_base_handlers.append(uri)
if "websocket" in protocol:
msg += f" - Websocket: {', '.join(api_def.ws_methods)}"
self.wsm.register_local_handler(api_def, callback)
logging.info(msg)
def register_static_file_handler(self, pattern, file_path,
can_delete=False, op_check_cb=None):
def register_static_file_handler(self, pattern, file_path, force=False):
if pattern[0] != "/":
pattern = "/server/files/" + pattern
if os.path.isfile(file_path):
if os.path.isfile(file_path) or force:
pattern += '()'
elif os.path.isdir(file_path):
if pattern[-1] != "/":
pattern += "/"
pattern += "(.*)"
else:
logging.info("Invalid file path: %s" % (file_path))
logging.info(f"Invalid file path: {file_path}")
return
methods = ['GET']
if can_delete:
methods.append('DELETE')
params = {
'server': self.server, 'auth': self.auth,
'path': file_path, 'methods': methods, 'op_check_cb': op_check_cb}
logging.debug(f"Registering static file: ({pattern}) {file_path}")
params = {'path': file_path}
self.mutable_router.add_handler(pattern, FileRequestHandler, params)
def register_upload_handler(self, pattern):
params = {'server': self.server, 'auth': self.auth}
self.mutable_router.add_handler(pattern, FileUploadHandler, params)
self.mutable_router.add_handler(
pattern, FileUploadHandler,
{'max_upload_size': self.max_upload_size})
def remove_handler(self, endpoint):
api_def = self.api_cache.get(endpoint)
@@ -213,155 +227,220 @@ class MoonrakerApp:
self.wsm.remove_handler(api_def.uri)
self.mutable_router.remove_handler(api_def.ws_method)
def _create_api_definition(self, endpoint, ws_method=None,
request_methods=['GET', 'POST']):
def _create_api_definition(self, endpoint, request_methods=[],
is_remote=True):
if endpoint in self.api_cache:
return self.api_cache[endpoint]
if endpoint[0] == '/':
uri = endpoint
else:
elif is_remote:
uri = "/printer/" + endpoint
if ws_method is None:
ws_method = uri[1:].replace('/', '_')
if endpoint.startswith("objects/"):
parser = _status_parser
else:
parser = _default_parser
api_def = APIDefinition(endpoint, uri, ws_method,
request_methods, parser)
uri = "/server/" + endpoint
ws_methods = []
if is_remote:
# Remote requests accept both GET and POST requests. These
# requests execute the same callback, thus they resolve to
# only a single websocket method.
ws_methods.append(uri[1:].replace('/', '.'))
request_methods = ['GET', 'POST']
else:
name_parts = uri[1:].split('/')
if len(request_methods) > 1:
for req_mthd in request_methods:
func_name = req_mthd.lower() + "_" + name_parts[-1]
ws_methods.append(".".join(name_parts[:-1] + [func_name]))
else:
ws_methods.append(".".join(name_parts))
if not is_remote and len(request_methods) != len(ws_methods):
raise self.server.error(
"Invalid API definition. Number of websocket methods must "
"match the number of request methods")
need_object_parser = endpoint.startswith("objects/")
api_def = APIDefinition(endpoint, uri, ws_methods,
request_methods, need_object_parser)
self.api_cache[endpoint] = api_def
return api_def
# ***** Dynamic Handlers*****
class RemoteRequestHandler(AuthorizedRequestHandler):
def initialize(self, remote_callback, server, auth,
methods, arg_parser):
super(RemoteRequestHandler, self).initialize(server, auth)
self.remote_callback = remote_callback
self.methods = methods
self.query_parser = arg_parser
async def get(self):
if 'GET' in self.methods:
await self._process_http_request('GET')
else:
raise tornado.web.HTTPError(405)
async def post(self):
if 'POST' in self.methods:
await self._process_http_request('POST')
else:
raise tornado.web.HTTPError(405)
async def _process_http_request(self, method):
args = {}
if self.request.query:
args = self.query_parser(self.request)
request = self.server.make_request(
self.remote_callback, method, args)
result = await request.wait()
if isinstance(result, ServerError):
raise tornado.web.HTTPError(
result.status_code, str(result))
self.finish({'result': result})
class LocalRequestHandler(AuthorizedRequestHandler):
def initialize(self, callback, server, auth,
methods, arg_parser):
super(LocalRequestHandler, self).initialize(server, auth)
class DynamicRequestHandler(AuthorizedRequestHandler):
def initialize(self, callback, methods, need_object_parser=False,
is_remote=True, wrap_result=True):
super(DynamicRequestHandler, self).initialize()
self.callback = callback
self.methods = methods
self.query_parser = arg_parser
self.wrap_result = wrap_result
self._do_request = self._do_remote_request if is_remote \
else self._do_local_request
self._parse_query = self._object_parser if need_object_parser \
else self._default_parser
async def get(self):
if 'GET' in self.methods:
await self._process_http_request('GET')
else:
raise tornado.web.HTTPError(405)
async def post(self):
if 'POST' in self.methods:
await self._process_http_request('POST')
else:
raise tornado.web.HTTPError(405)
async def delete(self):
if 'DELETE' in self.methods:
await self._process_http_request('DELETE')
else:
raise tornado.web.HTTPError(405)
async def _process_http_request(self, method):
args = {}
if self.request.query:
args = self.query_parser(self.request)
# Converts query string values with type hints
def _convert_type(self, value, hint):
type_funcs = {
"int": int, "float": float,
"bool": lambda x: x.lower() == "true",
"json": json.loads}
if hint not in type_funcs:
logging.info(f"No conversion method for type hint {hint}")
return value
func = type_funcs[hint]
try:
result = await self.callback(self.request.path, method, args)
converted = func(value)
except Exception:
logging.exception("Argument conversion error: Hint: "
f"{hint}, Arg: {value}")
return value
return converted
def _default_parser(self):
args = {}
for key in self.request.arguments.keys():
if key in EXCLUDED_ARGS:
continue
key_parts = key.rsplit(":", 1)
val = self.get_argument(key)
if len(key_parts) == 1:
args[key] = val
else:
args[key_parts[0]] = self._convert_type(val, key_parts[1])
return args
def _object_parser(self):
args = {}
for key in self.request.arguments.keys():
if key in EXCLUDED_ARGS:
continue
val = self.get_argument(key)
if not val:
args[key] = None
else:
args[key] = val.split(',')
logging.debug(f"Parsed Arguments: {args}")
return {'objects': args}
def parse_args(self):
try:
args = self._parse_query()
except Exception:
raise ServerError(
"Error Parsing Request Arguments. "
"Is the Content-Type correct?")
content_type = self.request.headers.get('Content-Type', "").strip()
if content_type.startswith("application/json"):
try:
args.update(json.loads(self.request.body))
except json.JSONDecodeError:
pass
for key, value in self.path_kwargs.items():
if value is not None:
args[key] = value
return args
async def get(self, *args, **kwargs):
await self._process_http_request()
async def post(self, *args, **kwargs):
await self._process_http_request()
async def delete(self, *args, **kwargs):
await self._process_http_request()
async def _do_local_request(self, args, conn):
return await self.callback(
WebRequest(self.request.path, args, self.request.method,
conn=conn))
async def _do_remote_request(self, args, conn):
return await self.server.make_request(
WebRequest(self.callback, args, conn=conn))
async def _process_http_request(self):
if self.request.method not in self.methods:
raise tornado.web.HTTPError(405)
conn = self.get_associated_websocket()
args = self.parse_args()
try:
result = await self._do_request(args, conn)
except ServerError as e:
raise tornado.web.HTTPError(
e.status_code, str(e))
self.finish({'result': result})
e.status_code, str(e)) from e
if self.wrap_result:
result = {'result': result}
self.finish(result)
class FileRequestHandler(AuthorizedFileHandler):
def initialize(self, server, auth, path, methods,
op_check_cb=None, default_filename=None):
super(FileRequestHandler, self).initialize(
server, auth, path, default_filename)
self.methods = methods
self.op_check_cb = op_check_cb
def set_extra_headers(self, path):
# The call below shold never return an empty string,
# as the path should have already been validated to be
# a file
basename = os.path.basename(self.absolute_path)
self.set_header(
"Content-Disposition", "attachment; filename=%s" % (basename))
"Content-Disposition", f"attachment; filename={basename}")
async def delete(self, path):
if 'DELETE' not in self.methods:
raise tornado.web.HTTPError(405)
# Use the same method Tornado uses to validate the path
self.path = self.parse_url_path(path)
del path # make sure we don't refer to path instead of self.path again
absolute_path = self.get_absolute_path(self.root, self.path)
self.absolute_path = self.validate_absolute_path(
self.root, absolute_path)
if self.op_check_cb is not None:
try:
await self.op_check_cb(self.absolute_path)
except ServerError as e:
if e.status_code == 403:
raise tornado.web.HTTPError(
403, "File is loaded, DELETE not permitted")
os.remove(self.absolute_path)
base = self.request.path.lstrip("/").split("/")[2]
filename = self.path.lstrip("/")
file_manager = self.server.lookup_plugin('file_manager')
file_manager.notify_filelist_changed(filename, 'removed', base)
path = self.request.path.lstrip("/").split("/", 2)[-1]
path = url_unescape(path, plus=False)
file_manager = self.server.lookup_component('file_manager')
try:
filename = await file_manager.delete_file(path)
except self.server.error as e:
if e.status_code == 403:
raise tornado.web.HTTPError(
403, "File is loaded, DELETE not permitted")
else:
raise tornado.web.HTTPError(e.status_code, str(e))
self.finish({'result': filename})
@tornado.web.stream_request_body
class FileUploadHandler(AuthorizedRequestHandler):
def initialize(self, server, auth):
super(FileUploadHandler, self).initialize(server, auth)
def initialize(self, max_upload_size):
super(FileUploadHandler, self).initialize()
self.file_manager = self.server.lookup_component('file_manager')
self.max_upload_size = max_upload_size
def prepare(self):
if self.request.method == "POST":
self.request.connection.set_max_body_size(self.max_upload_size)
tmpname = self.file_manager.gen_temp_upload_path()
self._targets = {
'root': ValueTarget(),
'print': ValueTarget(),
'path': ValueTarget(),
}
self._file = FileTarget(tmpname)
self._parser = StreamingFormDataParser(self.request.headers)
self._parser.register('file', self._file)
for name, target in self._targets.items():
self._parser.register(name, target)
def data_received(self, chunk):
if self.request.method == "POST":
self._parser.data_received(chunk)
async def post(self):
file_manager = self.server.lookup_plugin('file_manager')
form_args = {}
for name, target in self._targets.items():
if target.value:
form_args[name] = target.value.decode()
form_args['filename'] = self._file.multipart_filename
form_args['tmp_file_path'] = self._file.filename
debug_msg = "\nFile Upload Arguments:"
for name, value in form_args.items():
debug_msg += f"\n{name}: {value}"
logging.debug(debug_msg)
try:
result = await file_manager.process_file_upload(self.request)
result = await self.file_manager.finalize_upload(form_args)
except ServerError as e:
raise tornado.web.HTTPError(
e.status_code, str(e))
self.finish(result)
# Default Handler for unregistered endpoints
class AuthorizedErrorHandler(AuthorizedRequestHandler):
def prepare(self):
super(AuthorizedRequestHandler, self).prepare()
self.set_status(404)
raise tornado.web.HTTPError(404)
class EmulateOctoprintHandler(AuthorizedRequestHandler):
def get(self):
self.finish({
'server': "1.1.1",
'api': "0.1",
'text': "OctoPrint Upload Emulator"})
def check_xsrf_cookie(self):
pass
+151 -91
View File
@@ -8,104 +8,112 @@ import uuid
import os
import time
import ipaddress
import re
import logging
import tornado
from tornado.ioloop import IOLoop, PeriodicCallback
from utils import ServerError
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)
def __init__(self, config):
api_key_file = config.get('api_key_file', "~/.moonraker_api_key")
self.api_key_file = os.path.expanduser(api_key_file)
self.api_key = self._read_api_key()
self.auth_enabled = True
self.trusted_ips = []
self.trusted_ranges = []
self.auth_enabled = config.getboolean('enabled', True)
self.trusted_connections = {}
self.access_tokens = {}
# Get allowed cors domains
self.cors_domains = []
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 = []
self.trusted_ranges = []
trusted_clients = config.get('trusted_clients', "")
trusted_clients = [c.strip() for c in trusted_clients.split('\n')
if c.strip()]
for ip in trusted_clients:
# Check IP address
try:
tc = ipaddress.ip_address(ip)
except ValueError:
tc = None
if tc is None:
# Check ip network
try:
tc = ipaddress.ip_network(ip)
except ValueError:
raise ServerError(
f"Invalid option in trusted_clients: {ip}")
self.trusted_ranges.append(tc)
else:
self.trusted_ips.append(tc)
t_clients = "\n".join(
[str(ip) for ip in self.trusted_ips] +
[str(rng) for rng in self.trusted_ranges])
c_domains = "\n".join(self.cors_domains)
logging.info(
f"Authorization Configuration Loaded\n"
f"Auth Enabled: {self.auth_enabled}\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()
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)
"/access/api_key", ['GET', 'POST'],
self._handle_apikey_request, protocol=['http'])
app.register_local_handler(
"/access/oneshot_token", None, ['GET'],
self._handle_token_request, http_only=True)
"/access/oneshot_token", ['GET'],
self._handle_token_request, protocol=['http'])
async def _handle_apikey_request(self, path, method, args):
if method.upper() == 'POST':
async def _handle_apikey_request(self, web_request):
action = web_request.get_action()
if action.upper() == 'POST':
self.api_key = self._create_api_key()
return self.api_key
async def _handle_token_request(self, path, method, args):
async def _handle_token_request(self, web_request):
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:
if os.path.exists(self.api_key_file):
with open(self.api_key_file, '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))
f"No API Key file found, creating new one at:"
f"\n{self.api_key_file}")
return self._create_api_key()
def _create_api_key(self):
api_key = uuid.uuid4().hex
with open(self.api_key_loc, 'w') as f:
with open(self.api_key_file, '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
@@ -123,7 +131,7 @@ class Authorization:
for ip in expired_conns:
self.trusted_connections.pop(ip, None)
logging.info(
"Trusted Connection Expired, IP: %s" % (ip))
f"Trusted Connection Expired, IP: {ip}")
def _token_expire_handler(self, token):
self.access_tokens.pop(token, None)
@@ -145,7 +153,7 @@ class Authorization:
return True
elif self._check_authorized_ip(ip):
logging.info(
"Trusted Connection Detected, IP: %s" % (ip))
f"Trusted Connection Detected, IP: {ip}")
self.trusted_connections[ip] = time.time()
return True
return False
@@ -168,7 +176,7 @@ class Authorization:
ip = ipaddress.ip_address(request.remote_ip)
except ValueError:
logging.exception(
"Unable to Create IP Address %s" % (request.remote_ip))
f"Unable to Create IP Address {request.remote_ip}")
ip = None
if self._check_trusted_connection(ip):
return True
@@ -184,63 +192,115 @@ class Authorization:
return True
return False
def check_cors(self, origin, request=None):
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, request)
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, request)
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, request):
if request is None:
return
request.set_header("Access-Control-Allow-Origin", origin)
request.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
request.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token")
def close(self):
self.prune_handler.stop()
class AuthorizedRequestHandler(tornado.web.RequestHandler):
def initialize(self, server, auth):
self.server = server
self.auth = auth
def initialize(self):
app = self.settings['parent']
self.server = app.get_server()
self.auth = app.get_auth()
self.wsm = app.get_websocket_manager()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
# it is necessary to look up the parent app here,
# as initialize() may not yet be called
auth = self.settings['parent'].get_auth()
self.cors_enabled = auth.check_cors(origin, self)
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']:
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
super(AuthorizedRequestHandler, self).options()
def get_associated_websocket(self):
# Return associated websocket connection if an id
# was provided by the request
conn = None
conn_id = self.get_argument('connection_id', None)
if conn_id is not None:
try:
conn_id = int(conn_id)
except Exception:
pass
else:
conn = self.wsm.get_websocket(conn_id)
return conn
# 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):
def initialize(self, path, default_filename=None):
super(AuthorizedFileHandler, self).initialize(path, default_filename)
self.server = server
self.auth = auth
app = self.settings['parent']
self.server = app.get_server()
self.auth = app.get_auth()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
auth = self.settings['parent'].get_auth()
self.cors_enabled = auth.check_cors(origin, self)
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']:
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
@@ -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>
#
+140
View File
@@ -0,0 +1,140 @@
# 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.
import logging
import time
from collections import deque
from tornado.ioloop import IOLoop, PeriodicCallback
TEMPERATURE_UPDATE_MS = 1000
class DataStore:
def __init__(self, config):
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 = {}
self.gcode_queue = deque(maxlen=self.gcode_store_size)
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: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):
klippy_apis = self.server.lookup_component('klippy_apis')
# Fetch sensors
try:
result = await klippy_apis.query_objects({'heaters': None})
except self.server.error as e:
logging.info(f"Error Configuring Sensors: {e}")
return
sensors = result.get("heaters", {}).get("available_sensors", [])
if sensors:
# Add Subscription
sub = {s: None for s in sensors}
try:
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 = {}
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):
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):
# 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):
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 _update_gcode_store(self, response):
curtime = time.time()
self.gcode_queue.append(
{'message': response, 'time': curtime, 'type': "response"})
def store_gcode_command(self, script):
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):
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):
return DataStore(config)
+388
View File
@@ -0,0 +1,388 @@
# 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.
import os
import json
import struct
import operator
import logging
from io import BytesIO
from functools import reduce
import lmdb
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)),
}
def getitem_with_default(item, field):
if field not in item:
item[field] = {}
return item[field]
class Sentinel:
pass
class MoonrakerDatabase:
def __init__(self, config):
self.server = config.get_server()
self.namespaces = {}
self.protected_namespaces = {"moonraker"}
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)
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, key, value):
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 = 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, key, value):
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:
record = value
else:
try:
item = 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, key, drop_empty_db=False):
key_list = self._process_key(key)
val = record = self._get_record(namespace, key_list[0])
remove_record = True
if len(key_list) > 1:
try:
item = 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, key=None, default=Sentinel):
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)
except Exception:
if default != Sentinel:
return default
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
return val
def ns_length(self, namespace):
return len(self.ns_keys(namespace))
def ns_keys(self, namespace):
keys = []
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):
ns = self._get_namespace(namespace)
return ns.values()
def ns_items(self, namespace):
ns = self._get_namespace(namespace)
return ns.items()
def ns_contains(self, namespace, key):
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):
if namespace not in self.namespaces:
self.namespaces[namespace] = self.lmdb_env.open_db(
namespace.encode())
self.protected_namespaces.add(namespace)
def wrap_namespace(self, namespace, parse_keys=True):
if namespace not in self.namespaces:
raise self.server.error(
f"Namespace '{namespace}' not found", 404)
self.protected_namespaces.add(namespace)
return NamespaceWrapper(namespace, self, parse_keys)
def _process_key(self, key):
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, key, val):
db = self.namespaces[namespace]
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, key, force=False):
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):
if namespace not in self.namespaces:
raise self.server.error(
f"Invalid database namespace '{namespace}'")
db = self.namespaces[namespace]
result = {}
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()
result[k] = self._decode_value(value)
return result
def _encode_value(self, value):
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):
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}, format: {chr(fmt)}")
async def _handle_list_request(self, web_request):
return {'namespaces': list(self.namespaces.keys())}
async def _handle_item_request(self, web_request):
action = web_request.get_action()
namespace = web_request.get_str("namespace")
if action != "GET":
if namespace in self.protected_namespaces:
raise self.server.error(
f"Namespace '{namespace}' is write protected")
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):
# 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, database, parse_keys):
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, value):
if isinstance(key, str) and not self.parse_keys:
key = [key]
self.db.insert_item(self.namespace, key, value)
def update_child(self, key, value):
if isinstance(key, str) and not self.parse_keys:
key = [key]
self.db.update_item(self.namespace, key, value)
def update(self, value):
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, default=None):
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.get_item(self.namespace, key, default)
def delete(self, key):
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.delete_item(self.namespace, key)
def __len__(self):
return self.db.ns_length(self.namespace)
def __getitem__(self, key):
return self.get(key, default=Sentinel)
def __setitem__(self, key, value):
self.insert(key, value)
def __delitem__(self, key):
self.delete(key)
def __contains__(self, key):
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.ns_contains(self.namespace, key)
def keys(self):
return self.db.ns_keys(self.namespace)
def values(self):
return self.db.ns_values(self.namespace)
def items(self):
return self.db.ns_items(self.namespace)
def pop(self, key, default=Sentinel):
try:
val = self.delete(key)
except Exception:
if default == Sentinel:
raise
val = default
return val
def clear(self):
keys = self.keys()
for k in keys:
try:
self.delete([k])
except Exception:
pass
def load_component(config):
return MoonrakerDatabase(config)
+768
View File
@@ -0,0 +1,768 @@
# 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 zipfile
import logging
import json
import tempfile
from concurrent.futures import ThreadPoolExecutor
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.locks import Event
VALID_GCODE_EXTS = ['.gcode', '.g', '.gco', '.ufp', '.nc']
FULL_ACCESS_ROOTS = ["gcodes", "config"]
METADATA_SCRIPT = os.path.abspath(os.path.join(
os.path.dirname(__file__), "../../scripts/extract_metadata.py"))
UFP_MODEL_PATH = "/3D/model.gcode"
UFP_THUMB_PATH = "/Metadata/thumbnail.png"
class FileManager:
def __init__(self, config):
self.server = config.get_server()
self.file_paths = {}
database = self.server.load_component(config, "database")
gc_path = database.get_item("moonraker", "file_manager.gcode_path", "")
self.gcode_metadata = MetadataStorage(self.server, gc_path, database)
self.fixed_path_args = {}
# Register file management endpoints
self.server.register_endpoint(
"/server/files/list", ['GET'], self._handle_filelist_request)
self.server.register_endpoint(
"/server/files/metadata", ['GET'], self._handle_metadata_request)
self.server.register_endpoint(
"/server/files/directory", ['GET', 'POST', 'DELETE'],
self._handle_directory_request)
self.server.register_endpoint(
"/server/files/move", ['POST'], self._handle_file_move_copy)
self.server.register_endpoint(
"/server/files/copy", ['POST'], self._handle_file_move_copy)
self.server.register_endpoint(
"/server/files/delete_file", ['DELETE'], self._handle_file_delete,
protocol=["websocket"])
# register client notificaitons
self.server.register_notification("file_manager:filelist_changed")
self.server.register_notification("file_manager:metadata_update")
# Register APIs to handle file uploads
self.server.register_upload_handler("/server/files/upload")
self.server.register_upload_handler("/api/files/local")
self.server.register_event_handler(
"server:klippy_identified", self._update_fixed_paths)
# Register Klippy Configuration Path
config_path = config.get('config_path', None)
if config_path is not None:
ret = self.register_directory('config', config_path)
if not ret:
raise config.error(
"Option 'config_path' is not a valid directory")
# If gcode path is in the database, register it
if gc_path:
self.register_directory('gcodes', gc_path)
def _update_fixed_paths(self):
kinfo = self.server.get_klippy_info()
paths = {k: kinfo.get(k) for k in
['klipper_path', 'python_path',
'log_file', 'config_file']}
if paths == self.fixed_path_args:
# No change in fixed paths
return
self.fixed_path_args = paths
str_paths = "\n".join([f"{k}: {v}" for k, v in paths.items()])
logging.debug(f"\nUpdating Fixed Paths:\n{str_paths}")
# Register path for example configs
klipper_path = paths.get('klipper_path', None)
if klipper_path is not None:
example_cfg_path = os.path.join(klipper_path, "config")
self.register_directory("config_examples", example_cfg_path)
docs_path = os.path.join(klipper_path, "docs")
self.register_directory("docs", docs_path)
# Register log path
log_file = paths.get('log_file')
if log_file is not None:
log_path = os.path.abspath(os.path.expanduser(log_file))
self.server.register_static_file_handler(
"klippy.log", log_path, force=True)
def register_directory(self, root, path):
if path is None:
return False
path = os.path.abspath(os.path.expanduser(path))
if os.path.islink(path):
path = os.path.realpath(path)
if not os.path.isdir(path) or path == "/":
logging.info(
f"\nSupplied path ({path}) for ({root}) a valid. Make sure\n"
"that the path exists and is not the file system root.")
return False
permissions = os.R_OK
if root in FULL_ACCESS_ROOTS:
permissions |= os.W_OK
if not os.access(path, permissions):
logging.info(
f"\nMoonraker does not have permission to access path "
f"({path}) for ({root}).")
return False
if path != self.file_paths.get(root, ""):
self.file_paths[root] = path
self.server.register_static_file_handler(root, path)
if root == "gcodes":
database = self.server.lookup_component(
"database").wrap_namespace("moonraker")
database["file_manager.gcode_path"] = path
# scan for metadata changes
self.gcode_metadata.update_gcode_path(path)
try:
self.get_file_list("gcodes")
except Exception:
logging.exception(
f"Unable to initialize gcode metadata")
return True
def get_sd_directory(self):
return self.file_paths.get('gcodes', "")
def get_registered_dirs(self):
return list(self.file_paths.keys())
def get_fixed_path_args(self):
return dict(self.fixed_path_args)
def check_file_exists(self, root, filename):
root_dir = self.file_paths.get(root, "")
file_path = os.path.join(root_dir, filename)
return os.path.exists(file_path)
async def _handle_filelist_request(self, web_request):
root = web_request.get_str('root', "gcodes")
return self.get_file_list(root, list_format=True, notify=True)
async def _handle_metadata_request(self, web_request):
requested_file = web_request.get_str('filename')
metadata = self.gcode_metadata.get(requested_file, None)
if metadata is None:
raise self.server.error(
f"Metadata not available for <{requested_file}>", 404)
metadata['filename'] = requested_file
return metadata
async def _handle_directory_request(self, web_request):
directory = web_request.get_str('path', "gcodes")
root, rel_path, dir_path = self._convert_path(directory)
action = web_request.get_action()
if action == 'GET':
is_extended = web_request.get_boolean('extended', False)
# Get list of files and subdirectories for this target
dir_info = self._list_directory(dir_path, is_extended)
return dir_info
elif action == 'POST' and root 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("create_dir", rel_path, root)
elif action == 'DELETE' and root in FULL_ACCESS_ROOTS:
# Remove a directory
if directory.strip("/") == root:
raise self.server.error(
"Cannot delete root directory")
if not os.path.isdir(dir_path):
raise self.server.error(
f"Directory does not exist ({directory})")
force = web_request.get_boolean('force', False)
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)
if root == "gcodes":
self.gcode_metadata.prune_metadata()
else:
try:
os.rmdir(dir_path)
except Exception as e:
raise self.server.error(str(e))
self.notify_filelist_changed("delete_dir", rel_path, root)
else:
raise self.server.error("Operation Not Supported", 405)
return "ok"
async def _handle_operation_check(self, requested_path):
# Get virtual_sdcard status
klippy_apis = self.server.lookup_component('klippy_apis')
result = await klippy_apis.query_objects({'print_stats': None})
pstats = result.get('print_stats', {})
loaded_file = pstats.get('filename', "")
state = pstats.get('state', "")
gc_path = self.file_paths.get('gcodes', "")
full_path = os.path.join(gc_path, loaded_file)
if loaded_file and state != "complete":
if os.path.isdir(requested_path):
# Check to see of the loaded file is in the request
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 = state in ["printing", "paused"]
return ongoing
def _convert_path(self, request_path):
# Parse the root, relative path, and disk path from a remote request
parts = request_path.strip("/").split("/")
if not parts:
raise self.server.error(f"Invalid path: {request_path}")
root = parts[0]
if root not in self.file_paths:
raise self.server.error(f"Invalid root path ({root})")
disk_path = self.file_paths[root]
rel_path = ""
if len(parts) > 1:
rel_path = "/".join(parts[1:])
disk_path = os.path.join(disk_path, rel_path)
return root, rel_path, disk_path
async def _handle_file_move_copy(self, web_request):
source = web_request.get_str("source")
destination = web_request.get_str("dest")
ep = web_request.get_endpoint()
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_root, src_rel_path, source_path = self._convert_path(source)
dest_root, dst_rel_path, dest_path = self._convert_path(destination)
if dest_root not in FULL_ACCESS_ROOTS:
raise self.server.error(
f"Destination path is read-only: {dest_root}")
if not os.path.exists(source_path):
raise self.server.error(f"File {source_path} does not exist")
# make sure the destination is not in use
if os.path.exists(dest_path):
await self._handle_operation_check(dest_path)
action = op_result = ""
if ep == "/server/files/move":
if source_root not in FULL_ACCESS_ROOTS:
raise self.server.error(
f"Source path is read-only, cannot move: {source_root}")
# if moving the file, make sure the source is not in use
await self._handle_operation_check(source_path)
try:
op_result = shutil.move(source_path, dest_path)
except Exception as e:
raise self.server.error(str(e))
if source_root == "gcodes":
if os.path.isdir(op_result):
self.gcode_metadata.prune_metadata()
else:
self.gcode_metadata.remove_file(src_rel_path)
action = "move_item"
elif ep == "/server/files/copy":
try:
if os.path.isdir(source_path):
op_result = shutil.copytree(source_path, dest_path)
else:
op_result = shutil.copy2(source_path, dest_path)
except Exception as e:
raise self.server.error(str(e))
action = "copy_item"
if op_result != dest_path:
dst_rel_path = os.path.join(
dst_rel_path, os.path.basename(op_result))
self.notify_filelist_changed(
action, dst_rel_path, dest_root,
{'path': src_rel_path, 'root': source_root})
return "ok"
def _list_directory(self, path, is_extended=False):
if not os.path.isdir(path):
raise self.server.error(
f"Directory does not exist ({path})")
flist = {'dirs': [], 'files': []}
for fname in os.listdir(path):
full_path = os.path.join(path, fname)
if not os.path.exists(full_path):
continue
path_info = self._get_path_info(full_path)
if os.path.isdir(full_path):
path_info['dirname'] = fname
flist['dirs'].append(path_info)
elif os.path.isfile(full_path):
path_info['filename'] = fname
# Check to see if a filelist update is necessary
ext = os.path.splitext(fname)[-1].lower()
gc_path = self.file_paths.get('gcodes', None)
if gc_path is not None and full_path.startswith(gc_path) and \
ext in VALID_GCODE_EXTS:
if ext == ".ufp":
try:
full_path = self._process_ufp_from_refresh(
full_path)
except Exception:
logging.exception("Error processing ufp file")
continue
path_info = self._get_path_info(full_path)
path_info['filename'] = os.path.split(full_path)[-1]
rel_path = os.path.relpath(full_path, start=gc_path)
self.gcode_metadata.parse_metadata(
rel_path, path_info['size'], path_info['modified'],
notify=True)
metadata = self.gcode_metadata.get(rel_path, None)
if metadata is not None and is_extended:
path_info.update(metadata)
flist['files'].append(path_info)
usage = shutil.disk_usage(path)
flist['disk_usage'] = usage._asdict()
return flist
def _get_path_info(self, path):
modified = os.path.getmtime(path)
size = os.path.getsize(path)
path_info = {'modified': modified, 'size': size}
return path_info
def gen_temp_upload_path(self):
ioloop = IOLoop.current()
return os.path.join(
tempfile.gettempdir(),
f"moonraker.upload-{int(ioloop.time())}.mru")
async def finalize_upload(self, form_args):
# lookup root file path
try:
upload_info = self._parse_upload_args(form_args)
root = upload_info['root']
if root == "gcodes":
result = await self._finish_gcode_upload(upload_info)
elif root in FULL_ACCESS_ROOTS:
result = await self._finish_standard_upload(upload_info)
else:
raise self.server.error(f"Invalid root request: {root}")
except Exception:
try:
os.remove(form_args['tmp_file_path'])
except Exception:
pass
raise
return result
def _parse_upload_args(self, upload_args):
if 'filename' not in upload_args:
raise self.server.error(
"No file name specifed in upload form")
# check relative path
root = upload_args.get('root', "gcodes").lower()
if root not in self.file_paths:
raise self.server.error(f"Root {root} not available")
root_path = self.file_paths[root]
dir_path = upload_args.get('path', "")
if os.path.isfile(root_path):
filename = os.path.basename(root_path)
dest_path = root_path
dir_path = ""
else:
filename = upload_args['filename'].strip().lstrip("/")
if dir_path:
filename = os.path.join(dir_path, filename)
dest_path = os.path.abspath(os.path.join(root_path, filename))
# Validate the path. Don't allow uploads to a parent of the root
if not dest_path.startswith(root_path):
raise self.server.error(
f"Cannot write to path: {dest_path}")
start_print = upload_args.get('print', "false") == "true"
f_ext = os.path.splitext(dest_path)[-1].lower()
unzip_ufp = f_ext == ".ufp" and root == "gcodes"
if unzip_ufp:
filename = os.path.splitext(filename)[0] + ".gcode"
dest_path = os.path.splitext(dest_path)[0] + ".gcode"
return {
'root': root,
'filename': filename,
'dir_path': dir_path,
'dest_path': dest_path,
'tmp_file_path': upload_args['tmp_file_path'],
'start_print': start_print,
'unzip_ufp': unzip_ufp
}
async def _finish_gcode_upload(self, upload_info):
print_ongoing = False
start_print = upload_info['start_print']
# Verify that the operation can be done if attempting to upload a gcode
try:
check_path = upload_info['dest_path']
print_ongoing = await self._handle_operation_check(
check_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
ioloop = IOLoop.current()
with ThreadPoolExecutor(max_workers=1) as tpe:
await ioloop.run_in_executor(
tpe, self._process_uploaded_file, upload_info)
# Fetch Metadata
finfo = self._get_path_info(upload_info['dest_path'])
evt = self.gcode_metadata.parse_metadata(
upload_info['filename'], finfo['size'], finfo['modified'])
await evt.wait()
if start_print:
# Make a Klippy Request to "Start Print"
klippy_apis = self.server.lookup_component('klippy_apis')
try:
await klippy_apis.start_print(upload_info['filename'])
except self.server.error:
# Attempt to start print failed
start_print = False
self.notify_filelist_changed(
'upload_file', upload_info['filename'], "gcodes")
return {
'result': upload_info['filename'],
'print_started': start_print
}
async def _finish_standard_upload(self, upload_info):
ioloop = IOLoop.current()
with ThreadPoolExecutor(max_workers=1) as tpe:
await ioloop.run_in_executor(
tpe, self._process_uploaded_file, upload_info)
self.notify_filelist_changed(
'upload_file', upload_info['filename'], upload_info['root'])
return {'result': upload_info['filename']}
def _process_uploaded_file(self, upload_info):
try:
if upload_info['dir_path']:
os.makedirs(os.path.dirname(
upload_info['dest_path']), exist_ok=True)
if upload_info['unzip_ufp']:
self._unzip_ufp(upload_info['tmp_file_path'],
upload_info['dest_path'])
else:
shutil.move(upload_info['tmp_file_path'],
upload_info['dest_path'])
except Exception:
logging.exception("Upload Write Error")
raise self.server.error("Unable to save file", 500)
# UFP Extraction Implementation inspired by GitHub user @cdkeito
def _unzip_ufp(self, ufp_path, dest_path):
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)
finally:
try:
os.remove(ufp_path)
except Exception:
logging.exception(f"Error removing ufp file: {ufp_path}")
def _process_ufp_from_refresh(self, ufp_path):
dest_path = os.path.splitext(ufp_path)[0] + ".gcode"
self._unzip_ufp(ufp_path, dest_path)
return dest_path
def get_file_list(self, root, list_format=False, notify=False):
# Use os.walk find files in sd path and subdirs
filelist = {}
path = self.file_paths.get(root, None)
if path is None or not os.path.isdir(path):
msg = f"Failed to build file list, invalid path: {root}: {path}"
logging.info(msg)
raise self.server.error(msg)
logging.info(f"Updating File List <{root}>...")
st = os.stat(path)
visited_dirs = {(st.st_dev, st.st_ino)}
for dir_path, dir_names, files in os.walk(path, followlinks=True):
scan_dirs = []
# Filter out directories that have already been visted. This
# prevents infinite recrusion "followlinks" is set to True
for dname in dir_names:
st = os.stat(os.path.join(dir_path, dname))
key = (st.st_dev, st.st_ino)
if key not in visited_dirs:
visited_dirs.add(key)
scan_dirs.append(dname)
dir_names[:] = scan_dirs
for name in files:
ext = os.path.splitext(name)[-1].lower()
if root == 'gcodes' and ext not in VALID_GCODE_EXTS:
continue
full_path = os.path.join(dir_path, name)
if ext == ".ufp":
try:
full_path = self._process_ufp_from_refresh(full_path)
except Exception:
logging.exception("Error processing ufp file")
continue
fname = full_path[len(path) + 1:]
finfo = self._get_path_info(full_path)
filelist[fname] = finfo
if root == 'gcodes':
self.gcode_metadata.parse_metadata(
fname, finfo['size'], finfo['modified'], notify)
if list_format:
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:]
return self.gcode_metadata.get(filename, {})
def list_dir(self, directory, simple_format=False):
# List a directory relative to its root.
if directory[0] == "/":
directory = directory[1:]
parts = directory.split("/", 1)
root = parts[0]
if root not in self.file_paths:
raise self.server.error(
f"Invalid Directory Request: {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(
f"Directory does not exist ({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 = os.path.splitext(fname)[-1].lower()
if root == "gcodes" and ext in VALID_GCODE_EXTS:
simple_list.append(fname)
return simple_list
return flist
async def _handle_file_delete(self, web_request):
file_path = web_request.get_str("path")
return await self.delete_file(file_path)
async def delete_file(self, path):
parts = path.lstrip("/").split("/", 1)
if len(parts) != 2:
raise self.server.error(
f"Path not available for DELETE: {path}", 405)
root = parts[0]
filename = parts[1]
if root not in self.file_paths or root not in FULL_ACCESS_ROOTS:
raise self.server.error(
f"Path not available for DELETE: {path}", 405)
root_path = self.file_paths[root]
full_path = os.path.join(root_path, filename)
if not os.path.isfile(full_path):
raise self.server.error(f"Invalid file path: {path}")
if root == "gcodes":
try:
await self._handle_operation_check(full_path)
except self.server.error as e:
if e.status_code == 403:
raise
self.gcode_metadata.remove_file(filename)
os.remove(full_path)
self.notify_filelist_changed('delete_file', filename, root)
return filename
def notify_filelist_changed(self, action, fname, root, source_item={}):
flist = self.get_file_list(root, notify=True)
file_info = flist.get(fname, {'size': 0, 'modified': 0})
file_info.update({'path': fname, 'root': root})
result = {'action': action, 'item': file_info}
if source_item:
result.update({'source_item': source_item})
self.server.send_event("file_manager:filelist_changed", result)
def close(self):
self.gcode_metadata.close()
METADATA_PRUNE_TIME = 600000
METADATA_NAMESPACE = "gcode_metadata"
METADATA_VERSION = 3
class MetadataStorage:
def __init__(self, server, gc_path, database):
self.server = server
database.register_local_namespace(METADATA_NAMESPACE)
self.mddb = database.wrap_namespace(
METADATA_NAMESPACE, parse_keys=False)
version = database.get_item(
"moonraker", "file_manager.metadata_version", 0)
if version != METADATA_VERSION:
# Clear existing metadata when version is bumped
self.mddb.clear()
database.insert_item(
"moonraker", "file_manager.metadata_version",
METADATA_VERSION)
self.pending_requests = {}
self.events = {}
self.busy = False
self.gc_path = gc_path
self.prune_cb = PeriodicCallback(
self.prune_metadata, METADATA_PRUNE_TIME)
def update_gcode_path(self, path):
if path == self.gc_path:
return
self.mddb.clear()
self.gc_path = path
if not self.prune_cb.is_running():
self.prune_cb.start()
def close(self):
self.prune_cb.stop()
def get(self, key, default=None):
return self.mddb.get(key, default)
def __getitem__(self, key):
return self.mddb[key]
def prune_metadata(self):
for fname in list(self.mddb.keys()):
fpath = os.path.join(self.gc_path, fname)
if not os.path.exists(fpath):
self.remove_file(fname)
logging.info(f"Pruned file: {fname}")
continue
def _has_valid_data(self, fname, fsize, modified):
mdata = self.mddb.get(fname, {'size': "", 'modified': 0})
return mdata['size'] == fsize and mdata['modified'] == modified
def remove_file(self, fname):
metadata = self.mddb.pop(fname, None)
if metadata is None:
return
# Delete associated thumbnails
fdir = os.path.dirname(os.path.join(self.gc_path, fname))
if "thumbnails" in metadata:
for thumb in metadata["thumbnails"]:
path = thumb.get("relative_path", None)
if path is None:
continue
thumb_path = os.path.join(fdir, path)
try:
os.remove(thumb_path)
except Exception:
logging.debug(f"Error removing thumb at {thumb_path}")
def parse_metadata(self, fname, fsize, modified, notify=False):
evt = Event()
if fname in self.pending_requests or \
self._has_valid_data(fname, fsize, modified):
# request already pending or not necessary
evt.set()
return evt
self.pending_requests[fname] = (fsize, modified, notify, evt)
if self.busy:
return evt
self.busy = True
IOLoop.current().spawn_callback(self._process_metadata_update)
return evt
async def _process_metadata_update(self):
while self.pending_requests:
fname, (fsize, modified, notify, evt) = \
self.pending_requests.popitem()
if self._has_valid_data(fname, fsize, modified):
evt.set()
continue
retries = 3
while retries:
try:
await self._run_extract_metadata(fname, notify)
except Exception:
logging.exception("Error running extract_metadata.py")
retries -= 1
else:
break
else:
self.mddb[fname] = {
'size': fsize,
'modified': modified,
'print_start_time': None,
'job_id': None
}
logging.info(
f"Unable to extract medatadata from file: {fname}")
evt.set()
self.busy = False
async def _run_extract_metadata(self, filename, notify):
# Escape single quotes in the file name so that it may be
# properly loaded
filename = filename.replace("\"", "\\\"")
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
self.gc_path, "-f", f"\"{filename}\""])
shell_command = self.server.lookup_component('shell_command')
scmd = shell_command.build_shell_command(cmd, log_stderr=True)
result = await scmd.run_with_response(timeout=10.)
try:
decoded_resp = json.loads(result.strip())
except Exception:
logging.debug(f"Invalid metadata response:\n{result}")
raise
path = decoded_resp['file']
metadata = decoded_resp['metadata']
if not metadata:
# This indicates an error, do not add metadata for this
raise self.server.error("Unable to extract metadata")
metadata.update({'print_start_time': None, 'job_id': None})
self.mddb[path] = dict(metadata)
metadata['filename'] = path
if notify:
self.server.send_event(
"file_manager:metadata_update", metadata)
def load_component(config):
return FileManager(config)
+294
View File
@@ -0,0 +1,294 @@
# History cache for printer jobs
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
import time
HIST_NAMESPACE = "history"
MAX_JOBS = 10000
class History:
def __init__(self, config):
self.server = config.get_server()
self.file_manager = self.server.lookup_component('file_manager')
database = self.server.lookup_component("database")
self.gcdb = database.wrap_namespace("gcode_metadata", parse_keys=False)
self.job_totals = 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 = None
self.current_job_id = None
self.print_stats = {}
self.next_job_id = 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):
klippy_apis = self.server.lookup_component('klippy_apis')
sub = {"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):
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]}
async def _handle_jobs_list(self, web_request):
i = 0
end_num = len(self.history_ns)
jobs = []
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)
if start >= end_num or end_num == 0:
return {"count": 0, "jobs": []}
for job_id in self.cached_job_ids:
job = self.history_ns[job_id]
if since != -1 and since > job.get('start_time'):
start_num += 1
continue
if before != -1 and before < job.get('end_time'):
end_num -= 1
continue
if limit != 0 and i >= limit:
continue
if start != 0:
start -= 1
continue
jobs.append(self._prep_requested_job(job, job_id))
i += 1
return {"count": end_num - start_num, "jobs": jobs}
async def _handle_job_totals(self, web_request):
return {'job_totals': self.job_totals}
async def _status_update(self, data):
ps = data.get("print_stats", {})
if "state" in ps:
old_state = self.print_stats['state']
new_state = 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)
if new_state == "standby":
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):
self.finish_job("klippy_shutdown", self.print_stats)
def _handle_disconnect(self):
self.finish_job("klippy_disconnect", self.print_stats)
def _check_need_cancel(self, new_stats):
# 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):
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):
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, pstats):
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):
if isinstance(job_id, int):
job_id = f"{job_id:06X}"
return self.history_ns.get(job_id, None)
def grab_job_metadata(self):
if self.current_job is None:
return
filename = self.current_job.get("filename")
metadata = 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:
for thumb in metadata['thumbnails']:
thumb.pop('data', None)
self.current_job.set("metadata", metadata)
def save_current_job(self):
self.history_ns[self.current_job_id] = self.current_job.get_stats()
def _update_job_totals(self):
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 = self.server.lookup_component("database")
database.insert_item(
"moonraker", "history.job_totals", self.job_totals)
def send_history_event(self, evt_action):
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, job_id):
job['job_id'] = job_id
job['exists'] = self.file_manager.check_file_exists(
"gcodes", job['filename'])
return job
def on_exit(self):
self.finish_job("server_exit", self.print_stats)
class PrinterJob:
def __init__(self, data={}):
self.end_time = None
self.filament_used = 0
self.filename = None
self.metadata = None
self.print_duration = 0
self.status = "in_progress"
self.start_time = time.time()
self.total_duration = 0
self.update_from_ps(data)
def finish(self, status, print_stats={}):
self.end_time = time.time()
self.status = status
self.update_from_ps(print_stats)
def get(self, name):
if not hasattr(self, name):
return None
return getattr(self, name)
def get_stats(self):
return self.__dict__.copy()
def set(self, name, val):
if not hasattr(self, name):
return
setattr(self, name, val)
def update_from_ps(self, data):
for i in data:
if hasattr(self, i):
setattr(self, i, data[i])
def load_component(config):
return History(config)
+161
View File
@@ -0,0 +1,161 @@
# 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.
import utils
from websockets import WebRequest
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"
class Sentinel:
pass
class KlippyAPI:
def __init__(self, config):
self.server = config.get_server()
# Maintain a subscription for all moonraker requests, as
# we do not want to overwrite them
self.host_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):
return await self.run_gcode("PAUSE")
async def _gcode_resume(self, web_request):
return await self.run_gcode("RESUME")
async def _gcode_cancel(self, web_request):
return await self.run_gcode("CANCEL_PRINT")
async def _gcode_start_print(self, web_request):
filename = web_request.get_str('filename')
return await self.start_print(filename)
async def _gcode_restart(self, web_request):
return await self.do_restart("RESTART")
async def _gcode_firmware_restart(self, web_request):
return await self.do_restart("FIRMWARE_RESTART")
async def _send_klippy_request(self, method, params, default=Sentinel):
try:
result = await self.server.make_request(
WebRequest(method, params, conn=self))
except self.server.error as e:
if default == Sentinel:
raise
result = default
return result
async def run_gcode(self, script, default=Sentinel):
params = {'script': script}
result = await self._send_klippy_request(
GCODE_ENDPOINT, params, default)
return result
async def start_print(self, filename):
# 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):
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=Sentinel):
return await self._send_klippy_request(
LIST_EPS_ENDPOINT, {}, default)
async def emergency_stop(self, default=Sentinel):
return await self._send_klippy_request(ESTOP_ENDPOINT, {}, default)
async def get_klippy_info(self, send_id=False, default=Sentinel):
params = {}
if send_id:
ver = utils.get_software_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=Sentinel):
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, default=Sentinel):
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, default=Sentinel):
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, default=Sentinel):
template = {'response_template':
{'method': "process_gcode_response"}}
return await self._send_klippy_request(
GC_OUTPUT_ENDPOINT, template, default)
async def register_method(self, method_name):
return await self._send_klippy_request(
REG_METHOD_ENDPOINT,
{'response_template': {"method": method_name},
'remote_method': method_name})
def send_status(self, status):
self.server.send_event("server:status_update", status)
def load_component(config):
return KlippyAPI(config)
+80
View File
@@ -0,0 +1,80 @@
# 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
from tornado.ioloop import IOLoop
ALLOWED_SERVICES = ["moonraker", "klipper", "webcamd"]
class Machine:
def __init__(self, config):
self.server = config.get_server()
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)
# Register remote methods
self.server.register_remote_method(
"shutdown_machine", self.shutdown_machine)
self.server.register_remote_method(
"reboot_machine", self.reboot_machine)
async def _handle_machine_request(self, web_request):
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):
await self._execute_cmd("sudo shutdown now")
async def reboot_machine(self):
await self._execute_cmd("sudo shutdown -r now")
async def do_service_action(self, action, service_name):
await self._execute_cmd(
f'sudo systemctl {action} {service_name}')
async def _handle_service_request(self, web_request):
name = web_request.get('service').lower()
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 ALLOWED_SERVICES:
await self.do_service_action(action, name)
else:
raise self.server.error(
f"Invalid argument recevied for 'name': {name}")
return "ok"
async def _execute_cmd(self, cmd):
shell_command = self.server.lookup_component('shell_command')
scmd = shell_command.build_shell_command(cmd, None)
try:
await scmd.run(timeout=2., verbose=False)
except Exception:
logging.exception(f"Error running cmd '{cmd}'")
raise
def load_component(config):
return Machine(config)
+281
View File
@@ -0,0 +1,281 @@
# Octoprint API compatibility
#
# Copyright (C) 2021 Nickolas Grigoriadis <nagrigoriadis@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
import utils
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):
self.server = config.get_server()
self.software_version = config['system_args'].get('software_version')
# Local variables
self.klippy_apis = None
self.heaters = []
# Register status update event
self.server.register_event_handler(
'server:klippy_ready', self._init)
# Version & Server information
self.server.register_endpoint(
'/api/version', ['GET'], self._get_version, wrap_result=False)
self.server.register_endpoint(
'/api/server', ['GET'], self._get_server, wrap_result=False)
# Login, User & Settings
self.server.register_endpoint(
'/api/login', ['POST'], self._post_login_user, wrap_result=False)
self.server.register_endpoint(
'/api/currentuser', ['GET'], self._post_login_user,
wrap_result=False)
self.server.register_endpoint(
'/api/settings', ['GET'], self._get_settings, 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, wrap_result=False)
# TODO: start/cancel/restart/pause jobs
# Printer operations
self.server.register_endpoint(
'/api/printer', ['GET'], self._get_printer, wrap_result=False)
self.server.register_endpoint(
'/api/printer/command', ['POST'], self._post_command,
wrap_result=False)
# TODO: head/tool/bed/chamber specific read/issue
# Printer profiles
self.server.register_endpoint(
'/api/printerprofiles', ['GET'], self._get_printerprofiles,
wrap_result=False)
# System
# TODO: shutdown/reboot/restart operations
async def _init(self):
self.klippy_apis = self.server.lookup_component('klippy_apis')
# Fetch heaters
try:
result = await self.klippy_apis.query_objects({'heaters': None})
except self.server.error as e:
logging.info(f'Error Configuring heaters: {e}')
return
self.heaters = result.get('heaters', {}).get('available_sensors', [])
async def printer_state(self):
if not self.klippy_apis:
return 'Offline'
if self.server.klippy_state != 'ready':
return 'Error'
result = await self.klippy_apis.query_objects({'print_stats': None})
return {
'standby': 'Operational',
'printing': 'Printing',
'paused': 'Paused',
'complete': 'Operational'
}.get(result.get('state', 'standby'), 'Error')
async def printer_temps(self):
temps = {}
if not self.klippy_apis:
return temps
if self.heaters:
result = await self.klippy_apis.query_objects(
{heater: None for heater in self.heaters})
for heater in self.heaters:
if heater not in result:
continue
data = result[heater]
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):
"""
Version information
"""
return {
'server': OCTO_VERSION,
'api': '0.1',
'text': f'OctoPrint (Moonraker {self.software_version})',
}
async def _get_server(self, web_request):
"""
Server status
"""
return {
'server': OCTO_VERSION,
'safemode': (
None if self.server.klippy_state == 'ready' else 'settings')
}
async def _post_login_user(self, web_request):
"""
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):
"""
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):
"""
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': await self.printer_state()
}
async def _get_printer(self, web_request):
"""
Get Printer status
"""
state = await self.printer_state()
return {
'temperature': await 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):
"""
Request to run some gcode command
"""
commands = 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):
"""
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):
return OctoprintCompat(config)
@@ -9,42 +9,36 @@ import time
import json
import errno
import logging
import tempfile
import asyncio
from collections import deque
from utils import ServerError
from tornado import gen, netutil
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.locks import Lock
MIN_EST_TIME = 10.
INITIALIZE_TIMEOUT = 10.
class PanelDueError(ServerError):
pass
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
class SerialConnection:
def __init__(self, paneldue):
def __init__(self, config, paneldue):
self.ioloop = IOLoop.current()
self.paneldue = paneldue
self.port = ""
self.baud = 57200
self.sendlock = Lock()
self.port = config.get('serial')
self.baud = config.getint('baud', 57600)
self.partial_input = b""
self.ser = self.fd = None
self.connected = False
self.send_busy = False
self.send_buffer = b""
self.attempting_connect = True
self.ioloop.spawn_callback(self._connect)
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):
def disconnect(self, reconnect=False):
if self.connected:
if self.fd is not None:
self.ioloop.remove_handler(self.fd)
@@ -52,7 +46,13 @@ class SerialConnection:
self.connected = False
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)
async def _connect(self):
start_time = connect_time = time.time()
@@ -60,7 +60,7 @@ class SerialConnection:
if connect_time > start_time + 30.:
logging.info("Unable to connect, aborting")
break
logging.info("Attempting to connect to: %s" % (self.port))
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
@@ -68,7 +68,7 @@ class SerialConnection:
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))
logging.exception(f"Unable to open port: {self.port}")
await gen.sleep(2.)
connect_time += time.time()
continue
@@ -78,11 +78,12 @@ class SerialConnection:
self.fd, self._handle_incoming, IOLoop.READ | IOLoop.ERROR)
self.connected = True
logging.info("PanelDue Connected")
self.attempting_connect = False
def _handle_incoming(self, fd, events):
if events & IOLoop.ERROR:
logging.info("PanelDue Connection Error")
self.disconnect()
self.disconnect(reconnect=True)
return
# Process incoming data using same method as gcode.py
try:
@@ -92,85 +93,126 @@ class SerialConnection:
if not data:
# possibly an error, disconnect
self.disconnect()
self.disconnect(reconnect=True)
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)
line = line.strip().decode('utf-8', 'ignore')
self.paneldue.process_line(line)
except ServerError:
logging.exception(
"GCode Processing Error: " + line)
f"GCode Processing Error: {line}")
self.paneldue.handle_gcode_response(
"!! GCode Processing Error: " + line)
f"!! 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
def send(self, data):
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):
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, server):
self.server = server
def __init__(self, config):
self.server = config.get_server()
self.ioloop = IOLoop.current()
self.ser_conn = SerialConnection(self)
self.file_manager = self.server.load_plugin('file_manager')
self.file_manager = self.server.lookup_component('file_manager')
self.klippy_apis = self.server.lookup_component('klippy_apis')
self.kinematics = "none"
self.machine_name = "Klipper"
self.machine_name = config.get('machine_name', "Klipper")
self.firmware_name = "Repetier | Klipper"
self.last_message = None
self.last_gcode_response = None
self.current_file = ""
self.file_metadata = {}
self.enable_checksum = config.getboolean('enable_checksum', True)
self.debug_queue = deque(maxlen=100)
# Initialize tracked state.
self.printer_state = {
'gcode': {}, 'toolhead': {}, 'virtual_sdcard': {},
'pause_resume': {}, 'fan': {}, 'display_status': {}}
self.available_macros = {}
self.non_trivial_keys = []
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
'fan': {}, 'display_status': {}, 'print_stats': {},
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
self.extruder_count = 0
self.heaters = []
self.is_ready = False
self.is_shutdown = False
self.initialized = False
self.cq_busy = self.gq_busy = False
self.command_queue = []
self.gc_queue = []
self.last_printer_state = 'O'
self.last_update_time = 0.
# Set up macros
self.confirmed_gcode = ""
self.mbox_sequence = 0
self.available_macros = {}
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
macros = [m for m in macros.split('\n') if m.strip()]
self.available_macros = {m.split()[0]: m for m in macros}
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
conf_macros = [m for m in conf_macros.split('\n') if m.strip()]
self.confirmed_macros = {m.split()[0]: m for m in conf_macros}
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_state_changed", self.handle_klippy_state)
"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.handle_paneldue_beep)
"paneldue_beep", self.paneldue_beep)
# These commands are directly executued on the server and do not to
# make a request to Klippy
@@ -193,50 +235,20 @@ class PanelDue:
'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"
}
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
printer_info = cfg_status = {}
while retries:
try:
printer_info = await self._klippy_request("info")
cfg_status = await self._klippy_request(
"objects/status", args={'configfile': []})
except PanelDueError:
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:
@@ -245,23 +257,24 @@ class PanelDue:
continue
break
self.firmware_name = "Repetier | Klipper " + printer_info['version']
self.firmware_name = "Repetier | Klipper " + \
printer_info['software_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)))
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': {}, 'toolhead': {}, 'virtual_sdcard': {},
'pause_resume': {}, 'fan': {}, 'display_status': {}}
sub_args = {'gcode': [], 'toolhead': []}
'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:
@@ -269,99 +282,111 @@ class PanelDue:
self.extruder_count += 1
self.printer_state[cfg] = {}
self.heaters.append(cfg)
sub_args[cfg] = []
sub_args[cfg] = None
elif cfg == "heater_bed":
self.printer_state[cfg] = {}
self.heaters.append(cfg)
sub_args[cfg] = []
elif cfg in self.printer_state:
sub_args[cfg] = []
sub_args[cfg] = None
try:
await self._klippy_request(
"objects/subscription", method='POST', args=sub_args)
except PanelDueError:
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
async def _process_klippy_shutdown(self):
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
def _process_klippy_disconnect(self):
# 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
async def handle_status_update(self, status):
self.printer_state.update(status)
def handle_status_update(self, status):
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 handle_paneldue_beep(self, frequency, duration):
def paneldue_beep(self, frequency, duration):
duration = int(duration * 1000.)
self.ioloop.spawn_callback(
self.write_response,
self.write_response(
{'beep_freq': frequency, 'beep_length': duration})
async def process_line(self, line):
def process_line(self, line):
self.debug_queue.append(line)
# If we find M112 in the line then skip verification
if "M112" in line.upper():
await self._klippy_request("emergency_stop", method='POST')
self.ioloop.spawn_callback(self.klippy_apis.emergency_stop)
return
# Get line number
line_index = line.find(' ')
try:
line_no = int(line[1:line_index])
except Exception:
line_index = -1
line_no = None
if self.enable_checksum:
# 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)
# 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 = " Line Number: %d" % line_no
logging.info("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)
await self._run_gcode(line[line_index+1:cs_index])
async def _run_gcode(self, script):
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 = {}
for p in parts[1:]:
arg = p[0].lower() if p[0].lower() in "psr" else "p"
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()
val = int(p[1:].strip()) if arg in "sr" \
else p[1:].strip(" \"\t\n")
except Exception:
msg = "paneldue: Error parsing direct gcode %s" % (script)
msg = f"paneldue: Error parsing direct gcode {script}"
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
return
params["arg_" + arg] = val
params[f"arg_{arg}"] = val
func = self.direct_gcodes[cmd]
await func(**params)
self.queue_command(func, **params)
return
# Prepare GCodes that require special handling
@@ -369,16 +394,50 @@ class PanelDue:
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)
if not script:
return
self.queue_gcode(script)
def queue_gcode(self, script):
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):
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, *args, **kwargs):
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):
while self.command_queue:
cmd, args, kwargs = self.command_queue.pop(0)
try:
ret = cmd(*args, **kwargs)
if asyncio.iscoroutine(ret):
await ret
except Exception:
logging.exception("Error processing command")
self.cq_busy = False
def _clean_filename(self, filename):
# Remove quotes and whitespace
filename.strip(" \"\t\n")
# Remove drive number
if filename.startswith("0:/"):
filename = filename[3:]
@@ -395,26 +454,55 @@ class PanelDue:
return filename
def _prepare_M23(self, args):
filename = self._clean_filename(args[0].strip())
return "M23 " + filename
filename = self._clean_filename(args[0])
return f"M23 {filename}"
def _prepare_M32(self, args):
filename = self._clean_filename(args[0].strip())
return "M23 " + filename + "\n" + "M24"
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):
macro = args[0][1:].strip()
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("Macro %s invalid" % (macro))
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):
# args should in in the format Z0.02
offset = args[0][1:].strip()
return "SET_GCODE_OFFSET Z_ADJUST=%s MOVE=1" % (offset)
return f"SET_GCODE_OFFSET Z_ADJUST={offset} MOVE=1"
def _prepare_M292(self, args):
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, gcode):
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 = {}
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):
# Only queue up "non-trivial" gcode responses. At the
@@ -428,9 +516,9 @@ class PanelDue:
self.last_gcode_response = response
return
async def write_response(self, response):
def write_response(self, response):
byte_resp = json.dumps(response) + "\r\n"
await self.ser_conn.send(byte_resp.encode())
self.ser_conn.send(byte_resp.encode())
def _get_printer_status(self):
# PanelDue States applicable to Klipper:
@@ -441,39 +529,49 @@ class PanelDue:
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:
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'
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):
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
curtime = self.ioloop.time()
if curtime - self.last_update_time > INITIALIZE_TIMEOUT:
self.initialized = False
self.last_update_time = curtime
# Send gcode responses
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
@@ -483,28 +581,30 @@ class PanelDue:
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)
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 = 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)
sfactor = round(p_state['gcode_move'].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:
print_stats = p_state['print_stats']
fname = print_stats.get('filename', "")
sd_print_state = 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 = p_state['virtual_sdcard'].get('progress', 0)
progress = sd_status.get('progress', 0)
# progress and print tracking
if progress:
response['fraction_printed'] = round(progress, 3)
@@ -515,19 +615,20 @@ class PanelDue:
# filament estimate
est_total_fil = self.file_metadata.get('filament_total')
if est_total_fil:
cur_filament = sd_status.get('filament_used', 0.)
cur_filament = 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 = self.file_metadata.get('object_height')
if obj_height:
cur_height = p_state['gcode'].get('move_zpos', 0.)
cur_height = 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 = sd_status.get('print_duration', 0.)
duration = print_stats.get('print_duration', 0.)
times_left = [int(duration / progress - duration)]
response['timesLeft'] = times_left
else:
@@ -548,7 +649,8 @@ class PanelDue:
response['tool'] = tool
# Report Heater Status
efactor = round(p_state['gcode'].get('extrude_factor', 1.) * 100., 2)
efactor = round(p_state['gcode_move'].get(
'extrude_factor', 1.) * 100., 2)
for name in self.heaters:
temp = round(p_state[name].get('temperature', 0.0), 1)
@@ -569,14 +671,13 @@ class PanelDue:
# is strange about this, and displays it as a full screen
# notification
self.last_message = msg
await self.write_response(response)
self.write_response(response)
async def _run_paneldue_M20(self, arg_p, arg_s=0):
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))
f"Cannot process response type {response_type} in M20")
return
path = arg_p
@@ -610,7 +711,7 @@ class PanelDue:
flist = self.file_manager.list_dir(path, simple_format=True)
if flist:
response['files'] = flist
await self.write_response(response)
self.write_response(response)
async def _run_paneldue_M30(self, arg_p=None):
# Delete a file. Clean up the file name and make sure
@@ -624,32 +725,34 @@ class PanelDue:
if not path.startswith("gcodes/"):
path = "gcodes/" + path
self.file_manager.delete_file(path)
await self.file_manager.delete_file(path)
async def _run_paneldue_M36(self, arg_p=None):
def _run_paneldue_M36(self, arg_p=None):
response = {}
filename = 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:
filename = sd_status['filename']
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
await self.write_response(response)
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
@@ -658,7 +761,7 @@ class PanelDue:
response['err'] = 0
response['size'] = metadata['size']
# workaround for PanelDue replacing the first "T" found
response['lastModified'] = "T" + metadata['modified']
response['lastModified'] = "T" + time.ctime(metadata['modified'])
slicer = metadata.get('slicer')
if slicer is not None:
response['generatedBy'] = slicer
@@ -676,10 +779,14 @@ class PanelDue:
response['printTime'] = int(est_time + .5)
else:
response['err'] = 1
await self.write_response(response)
self.write_response(response)
async def close(self):
def close(self):
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_plugin(server):
return PanelDue(server)
def load_component(config):
return PanelDue(config)
+588
View File
@@ -0,0 +1,588 @@
# 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
import asyncio
import json
import struct
import socket
import gpiod
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
from tornado.escape import json_decode
class PrinterPower:
def __init__(self, config):
self.server = config.get_server()
self.chip_factory = GpioChipFactory()
self.devices = {}
prefix_sections = config.get_prefix_sections("power")
logging.info(f"Power component loading devices: {prefix_sections}")
try:
for section in prefix_sections:
cfg = config[section]
dev_type = cfg.get("type")
if dev_type == "gpio":
dev = GpioDevice(cfg, self.chip_factory)
elif dev_type == "tplink_smartplug":
dev = TPLinkSmartPlug(cfg)
elif dev_type == "tasmota":
dev = Tasmota(cfg)
elif dev_type == "shelly":
dev = Shelly(cfg)
elif dev_type == "homeseer":
dev = HomeSeer(cfg)
else:
raise config.error(f"Unsupported Device Type: {dev_type}")
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_power_request)
self.server.register_endpoint(
"/machine/device_power/on", ['POST'],
self._handle_power_request)
self.server.register_endpoint(
"/machine/device_power/off", ['POST'],
self._handle_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):
klippy_apis = self.server.lookup_component('klippy_apis')
result = await klippy_apis.query_objects(
{'print_stats': None}, default={})
pstate = result.get('print_stats', {}).get('state', "").lower()
return pstate == "printing"
async def _initalize_devices(self, inital_devs):
for dev in inital_devs:
ret = dev.initialize()
if asyncio.iscoroutine(ret):
await ret
async def _handle_klippy_shutdown(self):
for name, dev in self.devices.items():
if hasattr(dev, "off_when_shutdown"):
if dev.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):
dev_list = [d.get_device_info() for d in self.devices.values()]
output = {"devices": dev_list}
return output
async def _handle_power_request(self, web_request):
args = web_request.get_args()
ep = web_request.get_endpoint()
if not args:
raise self.server.error("No arguments provided")
requsted_devs = {k: self.devices.get(k, None) for k in args}
result = {}
req = ep.split("/")[-1]
for name, device in requsted_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, req):
if req in ["on", "off"]:
cur_state = device.get_device_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 asyncio.iscoroutine(ret):
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":
ret = device.refresh_status()
if asyncio.iscoroutine(ret):
await ret
dev_info = device.get_device_info()
else:
raise self.server.error(f"Unsupported power request: {req}")
return dev_info['status']
def set_device_power(self, device, state):
status = 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, device):
if name in self.devices:
raise self.server.error(
f"Device [{name}] already configured")
ret = device.initialize()
if asyncio.iscoroutine(ret):
await ret
self.devices[name] = device
async def close(self):
for device in self.devices.values():
if hasattr(device, "close"):
ret = device.close()
if asyncio.iscoroutine(ret):
await ret
self.chip_factory.close()
class PowerDevice:
def __init__(self, config):
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.state = "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):
return self.name
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
'locked_while_printing': self.locked_while_printing
}
def get_locked_while_printing(self):
return self.locked_while_printing
def run_power_changed_action(self):
if self.state == "on" and self.klipper_restart:
ioloop = IOLoop.current()
klippy_apis = self.server.lookup_component("klippy_apis")
ioloop.call_later(self.restart_delay, klippy_apis.do_restart,
"FIRMWARE_RESTART")
class GpioChipFactory:
def __init__(self):
self.chips = {}
def get_gpio_chip(self, chip_name):
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):
for chip in self.chips.values():
chip.close()
class GpioDevice(PowerDevice):
def __init__(self, config, chip_factory):
super().__init__(config)
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")
self.initial_state = config.getboolean('initial_state', False)
def _parse_pin(self, config):
pin = cfg_pin = config.get("pin")
invert = False
if pin[0] == "!":
pin = pin[1:]
invert = True
chip_id = "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 = int(pin[4:])
return pin, chip_id, invert
def initialize(self):
self.set_power("on" if self.initial_state else "off")
def get_device_info(self):
return {
**super().get_device_info(),
'type': "gpio"
}
def refresh_status(self):
try:
val = self.line.get_value()
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 val else "off"
def set_power(self, state):
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):
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):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
self.port = config.getint("port", 9999)
async def _send_tplink_command(self, command):
out_cmd = {}
if command in ["on", "off"]:
out_cmd = {'system': {'set_relay_state':
{'state': int(command == "on")}}}
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, self.port))
await stream.write(self._encrypt(out_cmd))
data = await stream.read_bytes(2048, partial=True)
length = 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, data):
data = json.dumps(data)
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):
key = self.START_KEY
res = ""
for c in data:
val = key ^ c
key = c
res += chr(val)
return res
async def initialize(self):
await self.refresh_status()
def get_device_info(self):
return {
**super().get_device_info(),
'type': "tplink_smartplug"
}
async def refresh_status(self):
try:
res = await self._send_tplink_command("info")
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):
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(PowerDevice):
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
self.output_id = config.getint("output_id", 1)
self.password = config.get("password", "")
async def _send_tasmota_command(self, command, password=None):
if command in ["on", "off"]:
out_cmd = f"Power{self.output_id}%20{command}"
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}"
data = ""
http_client = AsyncHTTPClient()
try:
response = await http_client.fetch(url)
data = json_decode(response.body)
except Exception:
msg = f"Error sending tplink command: {command}"
logging.exception(msg)
raise self.server.error(msg)
return data
async def initialize(self):
await self.refresh_status()
def get_device_info(self):
return {
**super().get_device_info(),
'type': "tasmota"
}
async def refresh_status(self):
try:
res = await self._send_tasmota_command("info")
state = res[f"POWER{self.output_id}"].lower()
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):
try:
res = await self._send_tasmota_command(state)
state = res[f"POWER{self.output_id}"].lower()
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 Shelly(PowerDevice):
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
self.output_id = config.getint("output_id", 0)
self.user = config.get("user", "admin")
self.password = config.get("password", "")
async def _send_shelly_command(self, command):
if command in ["on", "off"]:
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}"
data = ""
http_client = AsyncHTTPClient()
try:
response = await http_client.fetch(url)
data = json_decode(response.body)
except Exception:
msg = f"Error sending shelly command: {command}"
logging.exception(msg)
raise self.server.error(msg)
return data
async def initialize(self):
await self.refresh_status()
def get_device_info(self):
return {
**super().get_device_info(),
'type': "shelly"
}
async def refresh_status(self):
try:
res = await self._send_shelly_command("info")
state = res[f"ison"]
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):
try:
res = await self._send_shelly_command(state)
state = res[f"ison"]
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 = "on" if state else "off"
class HomeSeer(PowerDevice):
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
self.device = config.getint("device")
self.user = config.get("user", "admin")
self.password = config.get("password", "")
async def _send_homeseer(self, request, additional=""):
url = (f"http://{self.user}:{self.password}@{self.addr}"
f"/JSON?user={self.user}&pass={self.password}"
f"&request={request}&ref={self.device}&{additional}")
data = ""
http_client = AsyncHTTPClient()
try:
response = await http_client.fetch(url)
data = json_decode(response.body)
except Exception:
msg = f"Error sending HomeSeer command: {request}"
logging.exception(msg)
raise self.server.error(msg)
return data
async def initialize(self):
await self.refresh_status()
def get_device_info(self):
return {
**super().get_device_info(),
'type': "homeseer"
}
async def refresh_status(self):
try:
res = await self._send_homeseer("getstatus")
state = res[f"Devices"][0]["status"].lower()
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):
try:
if state == "on":
state_hs = "On"
elif state == "off":
state_hs = "Off"
res = await self._send_homeseer("controldevicebylabel",
f"label={state_hs}")
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
# The power component has multiple configuration sections
def load_component_multi(config):
return PrinterPower(config)
+137
View File
@@ -0,0 +1,137 @@
# 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.
import time
import re
import os
import pathlib
import logging
from collections import deque
from tornado.ioloop import IOLoop, PeriodicCallback
VC_GEN_CMD_FILE = "/usr/bin/vcgencmd"
STATM_FILE_PATH = "/proc/self/smaps_rollup"
STAT_UPDATE_TIME_MS = 1000
REPORT_QUEUE_SIZE = 30
THROTTLE_CHECK_INTERVAL = 10
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):
self.server = config.get_server()
self.ioloop = IOLoop.current()
self.stat_update_cb = PeriodicCallback(
self._handle_stat_update, STAT_UPDATE_TIME_MS)
self.vcgencmd = None
if os.path.exists(VC_GEN_CMD_FILE):
logging.info("Detected 'vcgencmd', throttle checking enabled")
shell_command = self.server.load_component(config, "shell_command")
self.vcgencmd = shell_command.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.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.proc_stat_queue = deque(maxlen=30)
self.last_update_time = time.time()
self.last_proc_time = time.process_time()
self.throttled = False
self.update_sequence = 0
self.stat_update_cb.start()
async def _handle_stat_request(self, web_request):
ts = None
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
return {
'moonraker_stats': list(self.proc_stat_queue),
'throttled_state': ts
}
async def _handle_shutdown(self):
msg = "\nMoonraker System Usage Statistics:"
for stats in self.proc_stat_queue:
msg += f"\n{self._format_stats(stats)}"
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):
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)
mem, mem_units = self._get_memory_usage()
self.proc_stat_queue.append({
"time": update_time,
"cpu_usage": usage,
"memory": mem,
"mem_units": mem_units
})
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'] & 0xF
if cur_throttled and not self.throttled:
logging.info(
f"CPU Throttled State Detected: {ts['flags']}")
self.server.send_event("proc_stats:cpu_throttled", ts)
self.throttled = cur_throttled
async def _check_throttled_state(self):
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):
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 _format_stats(self, stats):
return f"System Time: {stats['time']:2f}, " \
f"Usage: {stats['cpu_usage']}%, " \
f"Memory: {stats['memory']} {stats['mem_units']}"
def close(self):
self.stat_update_cb.stop()
def load_component(config):
return ProcStats(config)
+227
View File
@@ -0,0 +1,227 @@
# 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 logging
import signal
import asyncio
from tornado import gen
from utils import ServerError
class ShellCommandError(ServerError):
def __init__(self, message, return_code, stdout=b"",
stderr=b"", status_code=500):
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, std_out_cb, std_err_cb, log_stderr):
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):
transport = self._transport.get_pipe_transport(fd)
if fd == 2:
stream = self.stderr
cb = self.std_err_cb
else:
assert fd == 1
stream = self.stdout
cb = self.std_out_cb
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}: {output.decode()}")
output = output.rstrip(b'\n')
if output and cb is not None:
cb(output)
transport.close()
return output
async def cancel(self, sig_idx=1):
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=None):
if input is not None:
stdin = self._feed_stdin(input)
else:
stdin = self._noop()
if self.stdout is not None and self.std_out_cb is not None:
stdout = self._read_stream_with_cb(1)
else:
stdout = self._noop()
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 = self._read_stream_with_cb(2)
else:
stderr = self._noop()
stdin, stdout, stderr = await asyncio.tasks.gather(
stdin, stdout, stderr, loop=self._loop)
await self.wait()
class ShellCommand:
IDX_SIGINT = 0
IDX_SIGTERM = 1
IDX_SIGKILL_= 2
def __init__(self, cmd, std_out_callback, std_err_callback,
env=None, log_stderr=False, cwd=None):
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 = None
self.cancelled = False
self.return_code = None
async def cancel(self, sig_idx=1):
self.cancelled = True
if self.proc is not None:
await self.proc.cancel(sig_idx)
def get_return_code(self):
return self.return_code
def _reset_command_data(self):
self.return_code = self.proc = None
self.cancelled = False
async def run(self, timeout=2., verbose=True, log_complete=True,
sig_idx=1):
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():
return False
try:
if verbose:
ret = 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
return self._check_proc_success(complete, log_complete)
async def run_with_response(self, timeout=2., retries=1,
log_complete=True, sig_idx=1):
self._reset_command_data()
retries = max(1, retries)
while retries > 0:
stdout = stderr = b""
if await self._create_subprocess():
try:
ret = self.proc.communicate()
stdout, stderr = await asyncio.wait_for(
ret, timeout=timeout)
except asyncio.TimeoutError:
complete = False
await self.proc.cancel(sig_idx)
else:
complete = not self.cancelled
if self.log_stderr and stderr:
logging.info(f"{self.command[0]}: {stderr.decode()}")
if self._check_proc_success(complete, log_complete):
return stdout.decode().rstrip("\n")
elif stdout:
logging.debug(
f"Shell command '{self.name}' output:"
f"\n{stdout.decode()}")
retries -= 1
await gen.sleep(.5)
raise ShellCommandError(
f"Error running shell command: '{self.command}'",
self.return_code, stdout, stderr)
async def _create_subprocess(self):
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, log_complete):
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 build_shell_command(self, cmd, callback=None, std_err_callback=None,
env=None, log_stderr=False, cwd=None):
return ShellCommand(cmd, callback, std_err_callback, env,
log_stderr, cwd)
def load_component(config):
return ShellCommandFactory()
File diff suppressed because it is too large. Load diff
+141
View File
@@ -0,0 +1,141 @@
# Configuration Helper
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import configparser
import os
import logging
class ConfigError(Exception):
pass
class Sentinel:
pass
class ConfigHelper:
error = ConfigError
def __init__(self, server, config, section, orig_sects, parsed={}):
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):
return self.server
def __getitem__(self, key):
return self.getsection(key)
def __contains__(self, key):
return key in self.config
def get_name(self):
return self.section
def get_options(self):
return dict(self.config[self.section])
def get_prefix_sections(self, prefix):
return [s for s in self.sections() if s.startswith(prefix)]
def getsection(self, section):
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, option, default):
try:
val = func(option, default)
except Exception:
raise ConfigError(
f"Error parsing option ({option}) from "
f"section [{self.section}]")
if val == Sentinel:
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, default=Sentinel):
return self._get_option(
self.config[self.section].get, option, default)
def getint(self, option, default=Sentinel):
return self._get_option(
self.config[self.section].getint, option, default)
def getboolean(self, option, default=Sentinel):
return self._get_option(
self.config[self.section].getboolean, option, default)
def getfloat(self, option, default=Sentinel):
return self._get_option(
self.config[self.section].getfloat, option, default)
def read_supplemental_config(self, file_name):
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:
self.config.read(cfg_file_path)
except Exception:
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'")
def write_config(self, file_obj):
self.config.write(file_obj)
def get_parsed_config(self):
return dict(self.parsed)
def validate_config(self):
for sect in self.orig_sections:
if sect not in self.parsed:
logging.warn(
f"Invalid config section [{sect}] detected. 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:
logging.warn(
f"Invalid option '{opt}' detected in section "
f"[{sect}]. In the future this will result in a "
"startup error.")
def get_configuration(server, system_args):
cfg_file_path = os.path.normpath(os.path.expanduser(
system_args.configfile))
if not os.path.isfile(cfg_file_path):
raise ConfigError(f"Configuration File Not Found: '{cfg_file_path}''")
config = configparser.ConfigParser(interpolation=None)
try:
config.read(cfg_file_path)
except Exception:
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'") from None
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
config['system_args'] = {
'configfile': system_args.configfile,
'logfile': system_args.logfile,
'software_version': system_args.software_version}
return ConfigHelper(server, config, 'server', orig_sections)
Regular → Executable
+551 -337
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)
-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)
+55 -24
View File
@@ -4,44 +4,50 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license
import logging
import logging.handlers
import os
import sys
import subprocess
import asyncio
from queue import SimpleQueue as Queue
class ServerError(Exception):
def __init__(self, message, status_code=400):
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
self.server_manager.klippy_send(record)
# 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):
def __init__(self, software_version, 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"
self.rollover_info = {
'header': f"{'-'*20}Moonraker Log Start{'-'*20}",
'version': f"Git Version: {software_version}",
}
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 set_rollover_info(self, name, item):
self.rollover_info[name] = item
def doRollover(self):
super(MoonrakerLoggingHandler, self).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.
@@ -51,7 +57,7 @@ def get_software_version():
# Obtain version info from "git" program
prog = ('git', '-C', moonraker_path, 'describe', '--always',
'--tags', '--long', '--dirty', "--all")
'--tags', '--long', '--dirty')
try:
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
@@ -63,8 +69,33 @@ def get_software_version():
version = version.decode()
return version
else:
logging.debug("Error getting git version: %s", err)
logging.debug(f"Error getting git version: {err}")
except OSError:
logging.exception("Error runing git describe")
return "?"
def setup_logging(log_file, software_version):
root_logger = logging.getLogger()
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)
file_hdlr = None
if log_file:
file_hdlr = MoonrakerLoggingHandler(
software_version, log_file, 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
+158 -80
View File
@@ -11,6 +11,68 @@ from tornado.ioloop import IOLoop
from tornado.websocket import WebSocketHandler, WebSocketClosedError
from utils import ServerError
class Sentinel:
pass
class WebRequest:
def __init__(self, endpoint, args, action="", conn=None):
self.endpoint = endpoint
self.action = action
self.args = args
self.conn = conn
def get_endpoint(self):
return self.endpoint
def get_action(self):
return self.action
def get_args(self):
return self.args
def get_connection(self):
return self.conn
def _get_converted_arg(self, key, default=Sentinel, dtype=str):
if key not in self.args:
if default == Sentinel:
raise ServerError(f"No data for argument: {key}")
return default
val = self.args[key]
try:
if dtype != bool:
return dtype(val)
else:
if isinstance(val, str):
val = val.lower()
if val in ["true", "false"]:
return True if val == "true" else False
elif isinstance(val, bool):
return val
raise TypeError
except Exception:
raise ServerError(
f"Unable to convert argument [{key}] to {dtype}: "
f"value recieved: {val}")
def get(self, key, default=Sentinel):
val = self.args.get(key, default)
if val == Sentinel:
raise ServerError(f"No data for argument: {key}")
return val
def get_str(self, key, default=Sentinel):
return self._get_converted_arg(key, default)
def get_int(self, key, default=Sentinel):
return self._get_converted_arg(key, default, int)
def get_float(self, key, default=Sentinel):
return self._get_converted_arg(key, default, float)
def get_boolean(self, key, default=Sentinel):
return self._get_converted_arg(key, default, bool)
class JsonRPC:
def __init__(self):
self.methods = {}
@@ -21,12 +83,12 @@ class JsonRPC:
def remove_method(self, name):
self.methods.pop(name, None)
async def dispatch(self, data):
async def dispatch(self, data, ws):
response = None
try:
request = json.loads(data)
except Exception:
msg = "Websocket data not json: %s" % (str(data))
msg = f"Websocket data not json: {data}"
logging.exception(msg)
response = self.build_error(-32700, "Parse error")
return json.dumps(response)
@@ -34,19 +96,19 @@ class JsonRPC:
if isinstance(request, list):
response = []
for req in request:
resp = await self.process_request(req)
resp = await self.process_request(req, ws)
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, ws)
if response is not None:
response = json.dumps(response)
logging.debug("Websocket Response::" + response)
return response
async def process_request(self, request):
async def process_request(self, request, ws):
req_id = request.get('id', None)
rpc_version = request.get('jsonrpc', "")
method_name = request.get('method', None)
@@ -58,25 +120,29 @@ 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, ws, *params)
elif isinstance(params, dict):
response = await self.execute_method(method, req_id, **params)
response = await self.execute_method(
method, req_id, ws, **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, ws)
return response
async def execute_method(self, method, req_id, *args, **kwargs):
async def execute_method(self, method, req_id, ws, *args, **kwargs):
try:
result = await method(*args, **kwargs)
result = await method(ws, *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)
@@ -88,7 +154,12 @@ class JsonRPC:
'id': req_id
}
def build_error(self, code, msg, req_id=None):
def build_error(self, code, msg, req_id=None, is_exc=False):
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},
@@ -102,104 +173,97 @@ class WebsocketManager:
self.ws_lock = tornado.locks.Lock()
self.rpc = JsonRPC()
# Register events
self.rpc.register_method("server.websocket.id", self._handle_id_request)
def register_notification(self, event_name, notify_name=None):
if notify_name is None:
notify_name = event_name.split(':')[-1]
async def notify_handler(*args):
await 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)
def register_local_handler(self, api_def, callback):
for ws_method, req_method in \
zip(api_def.ws_methods, api_def.request_methods):
rpc_cb = self._generate_local_callback(
api_def.endpoint, req_method, callback)
self.rpc.register_method(ws_method, rpc_cb)
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
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)
def register_remote_handler(self, api_def):
ws_method = api_def.ws_methods[0]
rpc_cb = self._generate_callback(api_def.endpoint)
self.rpc.register_method(ws_method, rpc_cb)
def remove_handler(self, ws_method):
for prefix in ["get", "post", "delete"]:
self.rpc.remove_method(prefix + "_" + ws_method)
self.rpc.remove_method(ws_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):
async def func(ws, **kwargs):
result = await self.server.make_request(
WebRequest(endpoint, kwargs, conn=ws))
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
async def func(ws, **kwargs):
result = await callback(
WebRequest(endpoint, kwargs, request_method, ws))
return result
return func
async def _handle_id_request(self, ws, **kwargs):
return {'websocket_id': ws.uid}
def has_websocket(self, ws_id):
return ws_id in self.websockets
def get_websocket(self, ws_id):
return self.websockets.get(ws_id, None)
async def add_websocket(self, ws):
async with self.ws_lock:
self.websockets[ws.uid] = ws
logging.info("New Websocket Added: %d" % ws.uid)
logging.info(f"New Websocket Added: {ws.uid}")
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)
self.server.remove_subscription(old_ws)
logging.info(f"Websocket Removed: {ws.uid}")
async def notify_websockets(self, name, data):
notification = json.dumps({
'jsonrpc': "2.0",
'method': "notify_" + name,
'params': [data]})
async def notify_websockets(self, name, data=Sentinel):
msg = {'jsonrpc': "2.0", 'method': "notify_" + name}
if data != Sentinel:
msg['params'] = [data]
async with self.ws_lock:
for ws in list(self.websockets.values()):
try:
ws.write_message(notification)
ws.write_message(msg)
except WebSocketClosedError:
self.websockets.pop(ws.uid, None)
logging.info("Websocket Removed: %d" % ws.uid)
self.server.remove_subscription(ws)
logging.info(f"Websocket Removed: {ws.uid}")
except Exception:
logging.exception(
"Error sending data over websocket: %d" % (ws.uid))
f"Error sending data over websocket: {ws.uid}")
async def close(self):
async with self.ws_lock:
for ws in self.websockets.values():
for ws in list(self.websockets.values()):
ws.close()
self.websockets = {}
class WebSocket(WebSocketHandler):
def initialize(self, wsm, auth):
self.wsm = wsm
self.auth = auth
def initialize(self):
app = self.settings['parent']
self.auth = app.get_auth()
self.wsm = app.get_websocket_manager()
self.rpc = self.wsm.rpc
self.uid = id(self)
self.is_closed = False
async def open(self):
await self.wsm.add_websocket(self)
@@ -210,23 +274,37 @@ class WebSocket(WebSocketHandler):
async def _process_message(self, message):
try:
response = await self.rpc.dispatch(message)
response = await self.rpc.dispatch(message, self)
if response is not None:
self.write_message(response)
except Exception:
logging.exception("Websocket Command Error")
def send_status(self, status):
if not status or self.is_closed:
return
try:
self.write_message({
'jsonrpc': "2.0",
'method': "notify_status_update",
'params': [status]})
except WebSocketClosedError:
self.is_closed = True
logging.info(
f"Websocket Closed During Status Update: {self.uid}")
except Exception:
logging.exception(
f"Error sending data over websocket: {self.uid}")
def on_close(self):
self.is_closed = True
io_loop = IOLoop.current()
io_loop.spawn_callback(self.wsm.remove_websocket, self)
def check_origin(self, origin):
if self.settings['enable_cors']:
# allow CORS
return True
else:
return super(WebSocket, self).check_origin(origin)
if not super(WebSocket, self).check_origin(origin):
return self.auth.check_cors(origin)
return True
# Check Authorized User
def prepare(self):
if not self.auth.check_authorized(self.request):
+425 -127
View File
@@ -1,3 +1,4 @@
#!/usr/bin/env python3
# GCode metadata extraction utility
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
@@ -9,7 +10,14 @@ import argparse
import re
import os
import sys
import time
import base64
import traceback
import io
from PIL import Image
def log_to_stderr(msg):
sys.stderr.write(f"{msg}\n")
sys.stderr.flush()
# regex helpers
def _regex_find_floats(pattern, data, strict=False):
@@ -37,68 +45,160 @@ def _regex_find_ints(pattern, data):
pass
return []
def _regex_find_first(pattern, data, cast=float):
match = re.search(pattern, data)
val = None
if match:
try:
val = cast(match.group(1))
except Exception:
return None
return val
# 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 __init__(self, file_path):
self.path = file_path
self.header_data = self.footer_data = None
self.layer_height = None
def set_data(self, header_data, footer_data, log):
def set_data(self, header_data, footer_data, fsize):
self.header_data = header_data
self.footer_data = footer_data
self.log = log
self.size = fsize
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)
def _parse_min_float(self, pattern, data, strict=False):
result = _regex_find_floats(pattern, data, strict)
if result:
return min(result)
else:
return None
def _parse_max_float(self, pattern, data):
result = _regex_find_floats(pattern, data)
def _parse_max_float(self, pattern, data, strict=False):
result = _regex_find_floats(pattern, data, strict)
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 check_identity(self, data):
return None
def parse_gcode_start_byte(self):
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):
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):
return self._parse_min_float(
r"; first_layer_height =.*", self.footer_data)
return None
def parse_layer_height(self):
return self._parse_min_float(r"; layer_height =.*", self.footer_data)
return None
def parse_object_height(self):
return None
def parse_filament_total(self):
return None
def parse_estimated_time(self):
return None
def parse_first_layer_bed_temp(self):
return None
def parse_first_layer_extr_temp(self):
return None
def parse_thumbnails(self):
return None
class UnknownSlicer(BaseSlicer):
def check_identity(self, data):
return {'slicer': "Unknown"}
def parse_first_layer_height(self):
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_object_height(self):
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"M109 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
class PrusaSlicer(BaseSlicer):
def check_identity(self, data):
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):
# 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):
self.layer_height = _regex_find_first(
r"; layer_height = (\d+\.?\d*)", self.footer_data)
return self.layer_height
def parse_object_height(self):
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):
return self._parse_max_float(
r"filament\sused\s\[mm\]\s=\s\d+\.\d*", self.footer_data)
return _regex_find_first(
r"filament\sused\s\[mm\]\s=\s(\d+\.\d*)", self.footer_data)
def parse_estimated_time(self):
time_matches = re.findall(
time_match = re.search(
r';\sestimated\sprinting\stime.*', self.footer_data)
if not time_matches:
if not time_match:
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
time_match = 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_match)
if t:
total_time += int(t.group(1)) * multiplier
except Exception:
return None
return round(total_time, 2)
def parse_thumbnails(self):
@@ -106,66 +206,112 @@ class PrusaSlicer(BaseSlicer):
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
thumb_base = os.path.splitext(os.path.basename(self.path))[0]
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])})
log_to_stderr(
f"MetadataError: Error parsing thumbnail"
f" header: {lines[0]}")
continue
if len(data) != info[2]:
self.log.append(
{'MetadataError': "Thumbnail Size Mismatch: detected %d, "
"actual %d" % (info[2], len(data))})
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': info[2], 'data': data})
'size': info[2], 'data': data,
'relative_path': rel_thumb_path})
return parsed_matches
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"; first_layer_temperature = (\d+\.?\d*)", self.footer_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"; first_layer_bed_temperature = (\d+\.?\d*)", self.footer_data)
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 check_identity(self, data):
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):
return self._parse_max_float(
r"filament\sused\s=\s\d+\.\d+mm", self.footer_data)
return _regex_find_first(
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 check_identity(self, data):
match = re.search(r"Slic3r\s(\d.*)\son", data)
if match:
return {
'slicer': "Slic3r",
'slicer_version': match.group(1)
}
return None
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)
def check_identity(self, data):
match = re.search(r"SuperSlicer\s(.*)\son", data)
if match:
return {
'slicer': "SuperSlicer",
'slicer_version': match.group(1)
}
return None
class Cura(BaseSlicer):
def __init__(self, name="Cura", id_pattern=r"Cura_SteamEngine.*"):
super(Cura, self).__init__(name, id_pattern)
class Cura(PrusaSlicer):
def check_identity(self, data):
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):
return self._parse_min_float(r";MINZ:.*", self.header_data)
return _regex_find_first(r";MINZ:(\d+\.?\d*)", self.header_data)
def parse_layer_height(self):
return self._parse_min_float(r";Layer\sheight:.*", self.header_data)
self.layer_height = _regex_find_first(
r";Layer\sheight:\s(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
return self._parse_max_float(r";MAXZ:.*", self.header_data)
return _regex_find_first(r";MAXZ:(\d+\.?\d*)", self.header_data)
def parse_filament_total(self):
filament = self._parse_max_float(
r";Filament\sused:.*", self.header_data)
filament = _regex_find_first(
r";Filament\sused:\s(\d+\.?\d*)m", self.header_data)
if filament is not None:
filament *= 1000
return filament
@@ -173,55 +319,144 @@ class Cura(BaseSlicer):
def parse_estimated_time(self):
return self._parse_max_float(r";TIME:.*", self.header_data)
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"M109 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
def parse_thumbnails(self):
return None
# 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 open(thumb_path, 'rb') as thumb_file:
fbytes = thumb_file.read()
with Image.open(io.BytesIO(fbytes)) as im:
thumb_full_b64 = base64.b64encode(fbytes).decode()
thumbs.append({
'width': im.width, 'height': im.height,
'size': len(thumb_full_b64), 'data': thumb_full_b64,
'relative_path': rel_path_full
})
# Create 32x32 thumbnail
im.thumbnail((32, 32), Image.ANTIALIAS)
tmp_thumb = io.BytesIO()
im.save(tmp_thumb, format="PNG")
im.save(thumb_path_small, format="PNG")
thumb_small_b64 = base64.b64encode(
tmp_thumb.getbuffer()).decode()
tmp_thumb.close()
thumbs.insert(0, {
'width': im.width, 'height': im.height,
'size': len(thumb_small_b64), 'data': thumb_small_b64,
'relative_path': rel_path_small
})
except Exception as e:
log_to_stderr(str(e))
return None
return thumbs
class Simplify3D(BaseSlicer):
def __init__(self, name="Simplify3D", id_pattern=r"Simplify3D\(R\)"):
super(Simplify3D, self).__init__(name, id_pattern)
def check_identity(self, data):
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):
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)
self.layer_height = _regex_find_first(
r";\s+layerHeight,(\d+\.?\d*)", self.header_data)
return self.layer_height
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)
return _regex_find_first(
r";\s+Filament\slength:\s(\d+\.?\d*)\smm", self.footer_data)
def parse_estimated_time(self):
time_matches = re.findall(
time_match = re.search(
r';\s+Build time:.*', self.footer_data)
if not time_matches:
if not time_match:
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
time_match = 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_match)
if t:
total_time += int(t.group(1)) * multiplier
except Exception:
return None
return round(total_time, 2)
def parse_thumbnails(self):
def _get_temp_items(self, pattern):
match = re.search(pattern, self.header_data)
if match is None:
return []
return match.group().split(",")[1:]
def _get_first_layer_temp(self, heater):
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):
return self._get_first_layer_temp("Extruder 1")
def parse_first_layer_bed_temp(self):
return self._get_first_layer_temp("Heated Bed")
class KISSlicer(BaseSlicer):
def __init__(self, name="KISSlicer", id_pattern=r";\sKISSlicer"):
super(KISSlicer, self).__init__(name, id_pattern)
def check_identity(self, data):
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):
return self._parse_min_float(
r";\s+first_layer_thickness_mm\s=\s\d.*", self.header_data)
return _regex_find_first(
r";\s+first_layer_thickness_mm\s=\s(\d+\.?\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)
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):
return self._parse_max_float(
@@ -235,18 +470,32 @@ class KISSlicer(BaseSlicer):
return None
def parse_estimated_time(self):
time = self._parse_max_float(
r";\sCalculated.*Build\sTime:.*", self.footer_data)
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)
def parse_thumbnails(self):
return round(time, 2)
return None
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"; first_layer_C = (\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"; bed_C = (\d+\.?\d*)", self.header_data)
class IdeaMaker(BaseSlicer):
def __init__(self, name="IdeaMaker", id_pattern=r"\sideaMaker\s.*,",):
super(IdeaMaker, self).__init__(name, id_pattern)
def check_identity(self, data):
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):
layer_info = _regex_find_floats(
@@ -259,12 +508,13 @@ class IdeaMaker(BaseSlicer):
layer_info = _regex_find_floats(
r";LAYER:1\s*.*\s*;HEIGHT.*", self.header_data)
if len(layer_info) >= 3:
return layer_info[2]
self.layer_height = layer_info[2]
return self.layer_height
return None
def parse_object_height(self):
bounds = _regex_find_floats(
r";Bounding Box:.*", self.footer_data)
r";Bounding Box:.*", self.header_data)
if len(bounds) >= 6:
return bounds[5]
return None
@@ -277,60 +527,108 @@ class IdeaMaker(BaseSlicer):
return None
def parse_estimated_time(self):
return self._parse_max_float(r";Print\sTime:.*", self.footer_data)
return _regex_find_first(
r";Print\sTime:\s(\d+\.?\d*)", self.footer_data)
def parse_thumbnails(self):
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"M109 T0 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
class IceSL(BaseSlicer):
def check_identity(self, data):
match = re.search(r"; <IceSL.*>", data)
if match:
return {'slicer': "IceSL"}
return None
def parse_first_layer_height(self):
return _regex_find_first(
r"; z_layer_height_first_layer_mm :\s+(\d+\.\d+)",
self.header_data, float)
def parse_layer_height(self):
self.layer_height = _regex_find_first(
r"; z_layer_height_mm :\s+(\d+\.\d+)",
self.header_data, float)
return self.layer_height
def parse_object_height(self):
return self._parse_max_float(
r"G0 F\d+ Z\d+\.\d+", self.footer_data, strict=True)
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"; extruder_temp_degree_c_0 :\s+(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"; bed_temp_degree_c :\s+(\d+\.?\d*)", self.header_data)
READ_SIZE = 512 * 1024
SUPPORTED_SLICERS = [
PrusaSlicer, Slic3rPE, Slic3r, SuperSlicer,
Cura, Simplify3D, KISSlicer, IdeaMaker]
Cura, Simplify3D, KISSlicer, IdeaMaker, IceSL]
SUPPORTED_DATA = [
'first_layer_height', 'layer_height', 'object_height',
'filament_total', 'estimated_time', 'thumbnails']
'layer_height', 'first_layer_height', 'object_height',
'filament_total', 'estimated_time', 'thumbnails',
'first_layer_bed_temp', 'first_layer_extr_temp',
'gcode_start_byte', 'gcode_end_byte']
def extract_metadata(file_path):
metadata = {}
slicers = [s(file_path) for s in SUPPORTED_SLICERS]
header_data = footer_data = slicer = 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 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
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, 'log': log, 'metadata': metadata}).encode()
{'file': filename, 'metadata': metadata}).encode()
while data:
try:
ret = os.write(fd, data)
+67 -31
View File
@@ -3,11 +3,15 @@
# 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"
# 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 +20,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 rsync zlib1g-dev"
# Update system package info
report_status "Running apt-get update..."
@@ -30,52 +47,62 @@ 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}
ln -s /usr/lib/python3/dist-packages/gpiod* ${PYTHONDIR}/lib/python*/site-packages
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=Starts Moonraker on startup
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
ExecStart=${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}
Restart=always
RestartSec=10
EOF
# Use systemctl to enable the klipper systemd service script
sudo systemctl enable moonraker.service
}
# 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
@@ -98,11 +125,20 @@ set -e
# Find SRCDIR from the pathname of this script
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
# Parse command line arguments
while getopts "rfc:" arg; do
case $arg in
r) REBUILD_ENV="y";;
f) FORCE_DEFAULTS="y";;
c) CONFIG_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
+4 -1
View File
@@ -1,3 +1,6 @@
# Python dependencies for Moonraker
tornado==6.0.4
tornado==6.1.0
pyserial==3.4
pillow==8.1.2
lmdb==1.1.1
streaming-form-data==1.8.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()
+20
View File
@@ -0,0 +1,20 @@
# Supplemental configuration for Moonraker's Update Manager
# component. This file should not be modified.
[update_manager static debian moonraker]
origin: https://github.com/arksine/moonraker.git
requirements: scripts/moonraker-requirements.txt
venv_args: -p python3
install_script: scripts/install-moonraker.sh
python_dist_path: /usr/lib/python3/dist-packages
env_package_path: lib/python*/site-packages
python_dist_packages:
gpiod
[update_manager static debian klipper]
origin: https://github.com/kevinoconnor/klipper.git
requirements: scripts/klippy-requirements.txt
venv_args: -p python2
install_script: scripts/install-octopi.sh
python_dist_path: /usr/lib/python2.7/dist-packages
env_package_path: lib/python*/site-packages
+2
View File
@@ -0,0 +1,2 @@
env_version=0.2.6
deps_version=0.4.1
+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

+8 -19
View File
@@ -1,8 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="dist/themes/default/style.min.css"/>
<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>
<script src="dist/jstree.min.js"></script>
<script src="/js/main.js?v=0.1.2" type="module"></script>
</head>
<body>
<h3>Klippy Web API Test</h3>
@@ -37,27 +39,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 +53,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/>
+794 -409
View File
File diff suppressed because it is too large. Load diff